from osgeo import gdal from PIL import Image import numpy as np import os import datetime def print_with_timestamp(message): # 获取当前时间 current_time = datetime.datetime.now() # 格式化时间戳 timestamp = current_time.strftime("%Y-%m-%d %H:%M:%S") # 打印带有时间戳的消息 print(f"[{timestamp}] {message}") def reproject_and_resample_tiff(tiff_path, output_tiff_path, target_epsg, factor): # 打开TIFF文件 dataset = gdal.Open(tiff_path, gdal.GA_ReadOnly) if dataset is None: print_with_timestamp(f"无法打开TIFF文件: {tiff_path}") return # 获取TIFF文件的宽度和高度 width = dataset.RasterXSize height = dataset.RasterYSize # 计算重采样后的宽度和高度 new_width = int(width / factor) new_height = int(height / factor) # 设置重投影和重采样参数 options = gdal.WarpOptions( format='GTiff', width=new_width, height=new_height, dstSRS=f'EPSG:{target_epsg}', resampleAlg=gdal.GRA_Bilinear ) filename = os.path.basename(tiff_path) output_path = os.path.join(output_tiff_path,filename) # 执行重投影和重采样 gdal.Warp(output_path, dataset, options=options) print_with_timestamp(f"已将TIFF文件重投影并重采样到: {output_path}") return output_path def tiff_to_png(tiff_path, png_path, waterFlag, imageFlag): # 打开重投影和重采样后的TIFF文件 dataset = gdal.Open(tiff_path, gdal.GA_ReadOnly) if dataset is None: print_with_timestamp(f"无法打开TIFF文件:{tiff_path}") return # 获取TIFF文件的宽度和高度 width = dataset.RasterXSize height = dataset.RasterYSize # 获取TIFF文件的高度数据 band = dataset.GetRasterBand(1) heights = band.ReadAsArray() # mask_a = heights > -32766 # heights = mask_a * heights # 最高高度,要比测试数据的最高处21高 maxHeight = 23 # 创建一个空白的PNG图像 image = Image.new("RGB", (width, height)) # image = Image.new("L", (width, height)) # 创建二维数组 array = np.zeros((width, height), dtype="