使用从.TIF到.JPG的“ gdal_translate”如何将背景设置为白色?

问题描述 投票:0回答:1

我尝试使用以下行:

gdal_translate -of jpeg -a_nodata 0 -b 1 -b 2 -b 3 c:\myfolder\mytif.tif c:\myfolder\myNewtif.jpg

这会生成具有所需规格的图像,但是即使原始图像是白色,也将背景变成黑色(透明度?)。我可以只用gdal_translate来完成白色背景吗?

带掩码的文件的文件转储:https://filebin.net/f15v63to2x3cc4z0

不带掩码的文件的文件转储:https://filebin.net/kc940hqotcoeny0w

产生预期的白色背景的Tif的gdalinfo输出:

Driver: GTiff/GeoTIFF
Files: test.tif
Size is 4799, 3196
Metadata:
  TIFFTAG_RESOLUTIONUNIT=2 (pixels/inch)
  TIFFTAG_XRESOLUTION=300
  TIFFTAG_YRESOLUTION=300
Image Structure Metadata:
  COMPRESSION=LZW
  INTERLEAVE=PIXEL
Corner Coordinates:
Upper Left  (    0.0,    0.0)
Lower Left  (    0.0, 3196.0)
Upper Right ( 4799.0,    0.0)
Lower Right ( 4799.0, 3196.0)
Center      ( 2399.5, 1598.0)
Band 1 Block=4799x1 Type=Byte, ColorInterp=Red
Band 2 Block=4799x1 Type=Byte, ColorInterp=Green
Band 3 Block=4799x1 Type=Byte, ColorInterp=Blue

产生黑色背景的Tif:

Warning 1: TIFFFetchNormalTag:Incompatible type for "RichTIFFIPTC"; tag ignored
Driver: GTiff/GeoTIFF
Files: 100011_1.tif
Size is 1640, 2401
Metadata:
  TIFFTAG_DATETIME=2020:01:13 12:29:55
  TIFFTAG_RESOLUTIONUNIT=2 (pixels/inch)
  TIFFTAG_SOFTWARE=Adobe Photoshop 21.0 (Windows)
  TIFFTAG_XRESOLUTION=300
  TIFFTAG_YRESOLUTION=300
Image Structure Metadata:
  COMPRESSION=LZW
  INTERLEAVE=PIXEL
Corner Coordinates:
Upper Left  (    0.0,    0.0)
Lower Left  (    0.0, 2401.0)
Upper Right ( 1640.0,    0.0)
Lower Right ( 1640.0, 2401.0)
Center      (  820.0, 1200.5)
Band 1 Block=1640x39 Type=Byte, ColorInterp=Red
  Mask Flags: PER_DATASET ALPHA
Band 2 Block=1640x39 Type=Byte, ColorInterp=Green
  Mask Flags: PER_DATASET ALPHA
Band 3 Block=1640x39 Type=Byte, ColorInterp=Blue
  Mask Flags: PER_DATASET ALPHA
Band 4 Block=1640x39 Type=Byte, ColorInterp=Alpha

还有以下在转换后具有黑色背景的图像,gdal会产生此警告“ Warning 1: TIFFFetchNormalTag: Incompatible type for "RichTIFFIPTC"; tag ignored

cmd gdal
1个回答
0
投票

您在文件库上共享的文件包含一个“ alpha”掩码,如在gdalinfo的输出中所见。该文件的遮罩表示背景被遮罩,而图像的其余部分未被遮罩。

例如,如果使用默认的Ubuntu查看器显示tiff,则可以看到背景像素被遮蔽了(它们显示为棋盘)masked tiff

如果检查栅格数据,还会看到背景中的基础像素是黑色,而不是白色。这就是gdal_translate生成背景为黑色像素的jpeg的原因,因为在原始的tiff文件中它们实际上是黑色的(但被屏蔽了)。

[如果您绝对希望背景为白色,则可以使用几行Python,例如使用rasterio库,通过将遮罩的像素显式设置为白色:

rasterio

这应该提供以下jpeg文件:

import rasterio with rasterio.open("101679_1.tif") as src: arr = src.read(masked=True) # Convert all masked values to white arr[arr.mask] = 255 # Write to jpeg file profile = src.profile profile["count"] = 3 profile["driver"] = "jpeg" with rasterio.open("test.jpeg", "w", **profile) as dst: dst.write(arr[:3])

我上面包含的代码段也将对已经具有白色背景的TIF文件起作用,因为如果文件不包含掩码,则jpeg with white background行将不执行任何操作。要处理充满arr[arr.mask] = 255文件的目录,您可以执行以下操作:

.tif
© www.soinside.com 2019 - 2024. All rights reserved.