img_util.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import geopandas as gpd
  2. import matplotlib.pyplot as plt
  3. from shapely.wkt import loads
  4. from PIL import Image
  5. import os
  6. # 调整尺寸
  7. def resizeImage(dir,fileName):
  8. # 打开原始图片
  9. original_image = Image.open(dir+"/"+fileName)
  10. # 调整图片尺寸到 256x256
  11. resized_image = original_image.resize((256, 256))
  12. dir = dir.replace('tb', 'tb_256')
  13. if not os.path.exists(dir):
  14. os.makedirs(dir)
  15. # 保存调整后的图片
  16. resized_image.save(dir+"/"+fileName)
  17. # resizeImage('img/tb/6401812024070108270001change.png')
  18. # 保存为 PNG 图片
  19. def savePng(fileName, ewkt,dir):
  20. # 解析 WKT 数据字符串
  21. geometry = loads(ewkt.split(';')[1]) # 解析 WKT
  22. gdf = gpd.GeoDataFrame(geometry=[geometry])
  23. # 创建绘图
  24. fig, ax = plt.subplots(figsize=(10, 10))
  25. # 如果是 Polygon,处理其外部和内部
  26. if geometry.geom_type == 'Polygon':
  27. ax.fill(*geometry.exterior.xy, color='black') # 填充外部为黑色
  28. for interior in geometry.interiors:
  29. ax.fill(*interior.xy, color='white') # 填充内部(洞)为白色
  30. # 如果是 MultiPolygon,遍历每个 Polygon
  31. elif geometry.geom_type == 'MultiPolygon':
  32. for poly in geometry.geoms: # 使用 geometry.geoms 进行迭代
  33. ax.fill(*poly.exterior.xy, color='black') # 填充外部为黑色
  34. for interior in poly.interiors:
  35. ax.fill(*interior.xy, color='white') # 填充内部(洞)为白色
  36. # 设置坐标轴范围
  37. ax.set_xlim(gdf.total_bounds[[0, 2]])
  38. ax.set_ylim(gdf.total_bounds[[1, 3]])
  39. # 去掉坐标轴
  40. ax.axis('off')
  41. # 保存为 PNG 图片
  42. dir=dir+'/tb'
  43. if not os.path.exists(dir):
  44. os.makedirs(dir)
  45. fileName = fileName + '.png'
  46. plt.savefig(dir+"/"+fileName, dpi=300, bbox_inches='tight', pad_inches=0)
  47. plt.close()
  48. # 调用 resizeImage 函数来调整图片大小
  49. resizeImage(dir,fileName)
  50. # ewkt = "SRID=3857;POLYGON((13522050.0 3666550.0, 13522050.0 3657500.0, 13512100.0 3657500.0, 13512100.0 3666550.0, 13522050.0 3666550.0), (13516300.0 3662300.0, 13517350.0 3662300.0, 13517350.0 3663150.0, 13516300.0 3663150.0, 13516300.0 3662300.0))"
  51. # savePng('111',ewkt)