如何在 python 或 java 中将 geotiff 转换为 jpg?

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

我有一个 geotiff 图像,有 3 个波段。

band1,2 是实际图像值,band3 是实例角度值。

band1,2 是 float32 数据类型

下面的代码是我之前尝试过的。

但它不起作用。

我认为波段数据的范围太大,所以没有

from osgeo import gdal, osr, ogr
from PIL import Image
import numpy as np


ds = gdal.Open('image path', gdal.GA_ReadOnly)
rb = ds.GetRasterBand(1)
test = rb.ReadAsArray()
rb2 = ds.GetRasterBand(2)
test2 = rb2.ReadAsArray()
rb3 = ds.GetRasterBand(3)
test3 = rb3.ReadAsArray()
slice56 = test2
formatted = (slice56 * 255 / np.max(slice56)).astype('uint8')
img = Image.fromarray(formatted)
img.save('save image path')

我该如何解决这个问题??

java python image gdal geotiff
3个回答
11
投票

您可以为此使用

gdal.Translate

您可以在这里阅读文档

from osgeo import gdal
    
options_list = [
    '-ot Byte',
    '-of JPEG',
    '-b 1',
    '-scale'
]           

options_string = " ".join(options_list)
    
gdal.Translate(
    'save_image_path.jpg',
    'image_path.tif',
    options=options_string
)

上面的代码简单地创建了一个 jpg 文件,其中 band 1 缩放到字节范围。您可以通过添加

'-b 2'
等来添加更多波段。另请注意,scale 会自动将整个范围包装到字节范围内。如果您喜欢其他东西,您可以使用
'-scale min_val max_val'
来指定您喜欢的范围,因为通常您不需要可用的最低值或最高值。


2
投票

以上对我来说效果很好,除了 JPEG 分辨率不是很好。将 JPEG 转换为 PNG 效果更好。


0
投票

我已经编写了以下模块,更多内容可以在我的 GitHub 上找到:

import os
from osgeo import gdal

def geotiff_to_png(input_path, output_path=None, return_object=False):
"""
Converts a GeoTIFF file to a PNG file or object. Specific to Skysatimages with 4 bands (blue, green, red, nir).

Args:
    input_path (str): The file path of the input GeoTIFF file.
    output_path (str, optional): The file path of the output PNG file. If not provided, PNG object is returned. Defaults to None.
    return_object (bool, optional): Whether to return the PNG data as an object. If True, the output_path parameter will be ignored. Defaults to False.

Returns:
    numpy.ndarray or None: If output_path is not provided and return_object is True, returns a 3D numpy array representing the PNG image. Otherwise, returns None.

"""
# Open input file
dataset = gdal.Open(input_path)
output_types = [gdal.GDT_Byte, gdal.GDT_UInt16, gdal.GDT_Float32]

# Define output format and options
options = gdal.TranslateOptions(format='PNG', bandList=[3,2,1], creationOptions=['WORLDFILE=YES'], outputType=output_types[0])

# Translate to PNG
if output_path is not None:
    gdal.Translate(output_path, dataset, options=options)
    print(f'Successfully saved PNG file to {output_path}')

# Return PNG object
if return_object:
    mem_driver = gdal.GetDriverByName('MEM')
    mem_dataset = mem_driver.CreateCopy('', dataset, 0)
    png_data = mem_dataset.ReadAsArray()
    return png_data
© www.soinside.com 2019 - 2024. All rights reserved.