使用 python 将 16 位 GeoTiff 文件转换为 8 位 JPEG 文件

Converting a 16bit GeoTiff file as an 8bit JPEG file using python

我正在尝试将 16 位 3 波段 RGB GeoTIFF 文件转换为 8 位 3 波段 JPEG 文件。看起来 gdal 库应该适用于此。 我的问题是如何在 python gdal API 中指定转换为 8 位输出,以及如何缩放该转换中的值?另外,如何判断输出是 8 位还是 16 位?

gdal.Translate() 功能应该可以达到目的。但是,我发现将值重新调整为 8 位的唯一示例涉及 C 接口。下面的两个 post 提供了这方面的示例,但它们也不符合我的目的,因为它们没有使用 Python 接口。

https://gis.stackexchange.com/questions/26249/how-to-convert-qgis-generated-tiff-images-into-jpg-jpeg-using-gdal-command-line/26252

https://gis.stackexchange.com/questions/206537/geotiff-to-16-bit-tiff-png-or-bmp-image-for-heightmap/206786

我想出的python代码是:

from osgeo import gdal
gdal.Translate(destName='test.jpg', srcDS='test.tif')

这会起作用,但我不认为输出被转换为 8 位或值被重新缩放。有谁知道如何应用这些特定设置?

请注意,下面的 post 非常相似,但使用了 PIL 包。然而,问题是显然 PIL 无法摄取 16 位图像。当我尝试这段代码时,我在读取数据时遇到了错误。因此,我无法使用此解决方案。

converting tiff to jpeg in python

您可以像这样使用选项

from osgeo import gdal

scale = '-scale min_val max_val'
options_list = [
    '-ot Byte',
    '-of JPEG',
    scale
] 
options_string = " ".join(options_list)

gdal.Translate('test.jpg',
               'test.tif',
               options=options_string)

选择适合图像的最小值和最大值,如 min_valmax_val

如果您想将缩放比例扩展到整个范围,您可以简单地跳过最小值和最大值,只使用 scale = '-scale'

我认为 gdal 方法是使用 gdal.TranslateOptions()

from osgeo import gdal

translate_options = gdal.TranslateOptions(format='JPEG',
                                          outputType=gdal.GDT_Byte,
                                          scaleParams=[''],
                                          # scaleParams=[min_val, max_val],
                                          )

gdal.Translate(destName='test.jpg', srcDS='test.tif', options=translate_options)