img_util.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. import rasterio
  7. import numpy as np
  8. # 调整尺寸
  9. def resizeImage(dir, fileName):
  10. # 打开原始图片
  11. original_image = Image.open(dir+"/"+fileName)
  12. # 调整图片尺寸到 256x256
  13. resized_image = original_image.resize((256, 256))
  14. # dir = dir.replace('tb', 'tb_256')
  15. if not os.path.exists(dir):
  16. os.makedirs(dir)
  17. # 保存调整后的图片
  18. resized_image.save(dir+"/"+fileName)
  19. # resizeImage('img/tb/6401812024070108270001change.png')
  20. # 保存为 PNG 图片
  21. def savePng(fileName, ewkt, dir):
  22. # 解析 WKT 数据字符串
  23. geometry = loads(ewkt.split(';')[1]) # 解析 WKT
  24. gdf = gpd.GeoDataFrame(geometry=[geometry])
  25. # 创建绘图
  26. fig, ax = plt.subplots(figsize=(10, 10))
  27. # 如果是 Polygon,处理其外部和内部
  28. if geometry.geom_type == 'Polygon':
  29. ax.fill(*geometry.exterior.xy, color='black') # 填充外部为黑色
  30. for interior in geometry.interiors:
  31. ax.fill(*interior.xy, color='white') # 填充内部(洞)为白色
  32. # 如果是 MultiPolygon,遍历每个 Polygon
  33. elif geometry.geom_type == 'MultiPolygon':
  34. for poly in geometry.geoms: # 使用 geometry.geoms 进行迭代
  35. ax.fill(*poly.exterior.xy, color='black') # 填充外部为黑色
  36. for interior in poly.interiors:
  37. ax.fill(*interior.xy, color='white') # 填充内部(洞)为白色
  38. # 设置坐标轴范围
  39. ax.set_xlim(gdf.total_bounds[[0, 2]])
  40. ax.set_ylim(gdf.total_bounds[[1, 3]])
  41. # 去掉坐标轴
  42. ax.axis('off')
  43. # 保存为 PNG 图片
  44. if not os.path.exists(dir):
  45. os.makedirs(dir)
  46. fileName = fileName + '.png'
  47. plt.savefig(dir+"/"+fileName, dpi=300, bbox_inches='tight', pad_inches=0)
  48. plt.close()
  49. # 调用 resizeImage 函数来调整图片大小
  50. resizeImage(dir, fileName)
  51. # 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))"
  52. # savePng('111',ewkt)
  53. # tif转png
  54. def saveImage(tifPath, pngPath):
  55. # 将tifPath保存到pngPath
  56. with rasterio.open(tifPath) as src:
  57. # 读取tif文件的数据
  58. data = src.read()
  59. # 读取tif文件的元数据
  60. meta = src.meta
  61. # 将数据保存到pngPath
  62. with rasterio.open(pngPath, 'w', **meta) as dst:
  63. dst.write(data)
  64. # 获取图片的尺寸
  65. def getImageSize(image_path):
  66. # 获取图片的尺寸
  67. with Image.open(image_path) as img:
  68. return img.size