123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- import geopandas as gpd
- import matplotlib.pyplot as plt
- from shapely.wkt import loads
- from PIL import Image
- import os
- import rasterio
- import numpy as np
- import matplotlib.pyplot as plt
- # 调整尺寸
- def resizeImage(dir, fileName,size0,size1):
- # 打开原始图片
- original_image = Image.open(dir+"/"+fileName)
- # 调整图片尺寸到 256x256
- resized_image = original_image.resize((size0, size1))
- # dir = dir.replace('tb', 'tb_256')
- if not os.path.exists(dir):
- os.makedirs(dir)
- # 保存调整后的图片
- resized_image.save(dir+"/"+fileName)
- # resizeImage('img/tb/6401812024070108270001change.png')
- # 保存为 PNG 图片
- def savePng(fileName, ewkt, dir,size0,size1):
- # 解析 WKT 数据字符串
- geometry = loads(ewkt.split(';')[1]) # 解析 WKT
- gdf = gpd.GeoDataFrame(geometry=[geometry])
- # 创建绘图
- fig, ax = plt.subplots(figsize=(10, 10))
- # 如果是 Polygon,处理其外部和内部
- if geometry.geom_type == 'Polygon':
- ax.fill(*geometry.exterior.xy, color='black') # 填充外部为黑色
- for interior in geometry.interiors:
- ax.fill(*interior.xy, color='white') # 填充内部(洞)为白色
- # 如果是 MultiPolygon,遍历每个 Polygon
- elif geometry.geom_type == 'MultiPolygon':
- for poly in geometry.geoms:
- ax.fill(*poly.exterior.xy, color='black') # 填充外部为黑色
- for interior in poly.interiors:
- ax.fill(*interior.xy, color='white') # 填充内部(洞)为白色
- # 设置坐标轴范围
- ax.set_xlim(gdf.total_bounds[[0, 2]])
- ax.set_ylim(gdf.total_bounds[[1, 3]])
- # 去掉坐标轴
- ax.axis('off')
- # 检查目录是否存在,如果不存在则创建
- if not os.path.exists(dir):
- os.makedirs(dir)
- # 保存为 PNG 图片(暂存为 RGB 模式)
- temp_file_path = os.path.join(dir, fileName + '_temp.png')
- plt.savefig(temp_file_path, dpi=300, bbox_inches='tight', pad_inches=0)
- plt.close()
- # 使用 Pillow 将暂存的 RGB PNG 转换为灰度
- img = Image.open(temp_file_path).convert('L')
- gray_file_path = os.path.join(dir, fileName + '.png')
- img.save(gray_file_path)
- # 删除暂存文件
- os.remove(temp_file_path)
- # 调用 resizeImage 函数来调整图片大小
- resizeImage(dir, fileName + '.png',size0,size1)
- # 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))"
- # savePng('111',ewkt)
- # tif转png
- def saveImage(tifPath, pngPath):
- # 将tifPath保存到pngPath
- with rasterio.open(tifPath) as src:
- # 读取tif文件的数据
- data = src.read()
- # 读取tif文件的元数据
- meta = src.meta
- # 将数据保存到pngPath
- with rasterio.open(pngPath, 'w', **meta) as dst:
- dst.write(data)
- # 获取图片的尺寸
- def getImageSize(image_path):
- # 获取图片的尺寸
- with Image.open(image_path) as img:
- return img.size
|