img_util.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import geopandas as gpd
  2. import matplotlib.pyplot as plt
  3. from shapely.wkt import loads
  4. from PIL import Image
  5. # 调整尺寸
  6. def resizeImage(filePath):
  7. # 打开原始图片
  8. original_image = Image.open(filePath)
  9. # 调整图片尺寸到 256x256
  10. resized_image = original_image.resize((256, 256))
  11. filePath = filePath.replace('tb', 'tb_256')
  12. # 保存调整后的图片
  13. resized_image.save(filePath)
  14. # resizeImage('img/tb/6401812024070108270001change.png')
  15. # # 矢量保存为 PNG 图片
  16. # def savePng(fileName, ewkt):
  17. # # 新的 WKT 数据字符串
  18. # # 创建一个 GeoDataFrame
  19. # polygon = loads(ewkt.split(';')[1]) # 解析 WKT
  20. # gdf = gpd.GeoDataFrame(geometry=[polygon])
  21. # # 绘制
  22. # fig, ax = plt.subplots(figsize=(10, 10))
  23. # # 绘制多边形,外部填充为黑色,内部(洞)为白色
  24. # gdf.plot(ax=ax, edgecolor='black', facecolor='black')
  25. # # 设定中间洞为白色
  26. # ax.fill(*polygon.exterior.xy, color='black') # 填充外部为黑色
  27. # for interior in polygon.interiors:
  28. # ax.fill(*interior.xy, color='white') # 填充内部(洞)为白色
  29. # # 设置坐标轴范围
  30. # ax.set_xlim(gdf.total_bounds[[0, 2]])
  31. # ax.set_ylim(gdf.total_bounds[[1, 3]])
  32. # # 去掉坐标轴
  33. # ax.axis('off')
  34. # # 保存为 PNG 图片
  35. # filePath = 'img/tb/'+fileName+'.png'
  36. # plt.savefig(filePath, dpi=300,
  37. # bbox_inches='tight', pad_inches=0)
  38. # plt.close()
  39. # resizeImage(filePath)
  40. def savePng(fileName, ewkt):
  41. # 解析 WKT 数据字符串
  42. geometry = loads(ewkt.split(';')[1]) # 解析 WKT
  43. gdf = gpd.GeoDataFrame(geometry=[geometry])
  44. # 创建绘图
  45. fig, ax = plt.subplots(figsize=(10, 10))
  46. # 如果是 Polygon,处理其外部和内部
  47. if geometry.geom_type == 'Polygon':
  48. ax.fill(*geometry.exterior.xy, color='black') # 填充外部为黑色
  49. for interior in geometry.interiors:
  50. ax.fill(*interior.xy, color='white') # 填充内部(洞)为白色
  51. # 如果是 MultiPolygon,遍历每个 Polygon
  52. elif geometry.geom_type == 'MultiPolygon':
  53. for poly in geometry.geoms: # 使用 geometry.geoms 进行迭代
  54. ax.fill(*poly.exterior.xy, color='black') # 填充外部为黑色
  55. for interior in poly.interiors:
  56. ax.fill(*interior.xy, color='white') # 填充内部(洞)为白色
  57. # 设置坐标轴范围
  58. ax.set_xlim(gdf.total_bounds[[0, 2]])
  59. ax.set_ylim(gdf.total_bounds[[1, 3]])
  60. # 去掉坐标轴
  61. ax.axis('off')
  62. # 保存为 PNG 图片
  63. filePath = 'img/tb/' + fileName + '.png'
  64. plt.savefig(filePath, dpi=300, bbox_inches='tight', pad_inches=0)
  65. plt.close()
  66. # 调用 resizeImage 函数来调整图片大小
  67. resizeImage(filePath)
  68. # 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))"
  69. # savePng('111',ewkt)