From 539b6a387b3b3d269e897547ed5fa013a6b068ab Mon Sep 17 00:00:00 2001 From: xhong Date: Thu, 8 Jan 2026 10:33:59 +0800 Subject: [PATCH] =?UTF-8?q?feat(utils):=20=E9=87=8D=E6=9E=84=E4=BC=A0?= =?UTF-8?q?=E7=BB=9FGeoTIFF=E8=BD=ACCOG=E6=A0=BC=E5=BC=8F=E7=9A=84?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E5=87=BD=E6=95=B0.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/{toCOG.py => raw_to_cog.py} | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) rename utils/{toCOG.py => raw_to_cog.py} (78%) diff --git a/utils/toCOG.py b/utils/raw_to_cog.py similarity index 78% rename from utils/toCOG.py rename to utils/raw_to_cog.py index b46e7c2..2d3075e 100644 --- a/utils/toCOG.py +++ b/utils/raw_to_cog.py @@ -7,8 +7,8 @@ COG (Cloud Optimized GeoTIFF) 是一种优化设计的 GeoTIFF 文件格式, 特 的存储和访问. 自带分块存储功能与影像金字塔, 能够在请求时按需加载, 实现了高效的压缩和传输. ------------------------------------------------------------------------------- -Authors: Hong Xie -Last Updated: 2025-10-20 +Authors: CVEO Team +Last Updated: 2026-01-08 =============================================================================== """ @@ -31,10 +31,10 @@ gdal.SetConfigOption("GDAL_NUM_THREADS", "ALL_CPUS") gdal.SetConfigOption("GDAL_CACHEMAX", "1024") -def tif2cog( +def tif_to_cog( input_path: str, output_path: str, - output_type: gdal.GDT_Float32 = gdal.GDT_Float32, + output_type: gdal.GDT_DataType = gdal.GDT_Float32, no_data: float = np.nan, compress: str = "DEFLATE", scaleParams: list = None, @@ -48,7 +48,7 @@ def tif2cog( 输入 GeoTIFF 文件路径 output_path : str 输出 COG 文件路径 - output_type : gdal.GDT_Float32, optional + output_type : gdal.GDT_DataType, optional 输出数据类型, 默认 float32, by default gdal.GDT_Float32 no_data : float, optional 无效值, 默认 np.nan, by default np.nan @@ -60,6 +60,23 @@ def tif2cog( if ds is None: logging.error(f"无法打开输入文件: {input_path}") return + # 查看原数据是否已设置无效值 + band = ds.GetRasterBand(1) + original_no_data = band.GetNoDataValue() + original_data_type = band.DataType + if np.isnan(no_data): + if original_no_data is None: + # 根据输出数据类型设置无效值 + if output_type == gdal.GDT_Int16: + no_data = -32768 + elif output_type == gdal.GDT_Float32: + no_data = -9999 + else: + no_data = np.nan + logging.warning(f"原数据未设无效值, 现已设为: {no_data}") + else: + no_data = original_no_data + logging.info(f"原数据无效值为: {no_data}") translate_options = gdal.TranslateOptions( format="COG", # 输出为 COG 格式, 自动构建金字塔 outputType=output_type, @@ -92,7 +109,7 @@ def main(input_dir, file_name, output_path): output_path = output_dir / file_name # 关于无效值 # Float32 类型可以设为 -9999; 8bit 类型可以设为 0 - tif2cog(str(input_path), str(output_path), no_data=-9999) + tif_to_cog(str(input_path), str(output_path), no_data=-9999) if __name__ == "__main__":