使用Python-GDAL写入GeoTIFF时显示为灰度而非彩色的问题
问题:彩色GeoTIFF超分辨率后显示为灰度图
我尝试用深度学习对彩色GeoTIFF做超分辨率放大,通过GDAL读取图像后分波段处理,再将处理后的波段写入新的GeoTIFF驱动。代码片段如下:
# 移除缩放并为每个波段创建单独图像 bands = tiffimg.shape[-1] # 创建与输入格式一致的TIFF驱动 driver = gdal.GetDriverByName("GTiff") outdata = driver.Create(f'{save_dir}/{imgname}.{fileExtension}', tiffDS.RasterXSize*2, tiffDS.RasterYSize*2, bands, gdal.GDT_UInt16) outpng = np.ones((tiffimg.shape[0]*2,tiffimg.shape[1]*2,tiffimg.shape[2]),dtype=tiffimg.dtype) for band in range(bands): singleBand = tiffimg[:,:,band] bandMaxValue = np.ndarray.max(singleBand) print(f'Band {band+1} 处理前的极值: {np.ndarray.min(singleBand)} \t {np.ndarray.max(singleBand)}') scaledBand = (singleBand).astype(np.float32)/bandMaxValue img_lq = np.stack((scaledBand,)*3,axis=-1) resizedImg = getSRImage(args, img_lq, imgname) # 获取超分辨率后的波段 resizedImg = (resizedImg[:,:,1]*bandMaxValue).round().astype(tiffimg.dtype) print(f'Band {band+1} 处理后的极值: {np.ndarray.min(resizedImg)} \t {np.ndarray.max(resizedImg)}') outdata.GetRasterBand(band+1).WriteArray(resizedImg) outdata.GetRasterBand(band+1).SetNoDataValue(100000) # 设置透明值 outpng[band] = resizedImg outdata.SetGeoTransform(tiffDS.GetGeoTransform()) # 复制输入的地理变换参数 outdata.SetProjection(tiffDS.GetProjection()) # 复制输入的投影参数 outdata.SetMetadata(tiffDS.GetMetadata()) outdata.FlushCache() # 写入磁盘!! cv2.imwrite(f'{save_dir}/backup/{imgname}.png', outpng[:,:,0:3])
最终生成的图像数据类型、波段数和原图像一致,但显示时却是灰度图而非彩色。
问题分析:对比元数据差异
通过exiftool查看原图像和输出图像的元数据,发现核心差异:
- 原图像的
Photometric Interpretation(光度解释)为RGB - 超分辨率后的图像该参数为BlackIsZero
这个元数据参数决定了图像的色彩解析方式,BlackIsZero会被图像查看器识别为灰度模式,导致彩色数据无法正确渲染。
解决方案
创建GTiff驱动时,显式指定PHOTOMETRIC=RGB选项,同时保留GeoTIFF配置。修改后的代码如下:
driver = gdal.GetDriverByName("GTiff") options = ['PHOTOMETRIC=RGB', 'PROFILE=GeoTIFF'] outdata = driver.Create(f'{save_dir}/{imgname}.{fileExtension}', tiffDS.RasterXSize*2, tiffDS.RasterYSize*2, bands, gdal.GDT_UInt16, options=options)
内容的提问来源于stack exchange,提问作者spacemanspiff
相关产品推荐
相关产品推荐

