如何在 python 中将 numpy 列表转换为 geoTIFF?

How to convert numpy list to geoTIFF in python?

我还没有找到这个简单问题的答案。请帮忙。如何将 Qcal(numpy 列表)转换为 TIFF 图像?我发现的所有内容都不起作用。

import math
import numpy as np
from osgeo import gdal

substr1 = 'RADIANCE_MULT_BAND_10'
substr2 = 'RADIANCE_ADD_BAND_10'
substr3 = 'K1_CONSTANT_BAND_10'
substr4 = 'K2_CONSTANT_BAND_10'

RADIANCE_MULT_BAND_10 = 1
RADIANCE_ADD_BAND_10 = 1
K1_CONSTANT_BAND_10 = 1
K2_CONSTANT_BAND_10 = 1

with open('LC08_L1TP_180028_20170623_20170630_01_T1_MTL.txt') as file:
    for line in file:
        if substr1 in line:
            startIndex = line.find('=')
            RADIANCE_MULT_BAND_10 = float((line[startIndex+2:]))
        if substr2 in line:
            startIndex = line.find('=')
            RADIANCE_ADD_BAND_10 = float((line[startIndex + 2:]))
        if substr3 in line:
            startIndex = line.find('=')
            K1_CONSTANT_BAND_10 = float((line[startIndex + 2:]))
        if substr4 in line:
            startIndex = line.find('=')
            K2_CONSTANT_BAND_10 = float((line[startIndex + 2:]))

ds = gdal.Open("B10.tif")
Qcal = np.array(ds.GetRasterBand(1).ReadAsArray()) # Quantized and calibrated standard product pixel values (DN)
for i in range(Qcal.shape[0]):
   for j in range(Qcal.shape[1]):
       Qcal[i][j] = RADIANCE_MULT_BAND_10 * Qcal[i][j] + RADIANCE_ADD_BAND_10
       Qcal[i][j] = K2_CONSTANT_BAND_10 / math.log1p(K1_CONSTANT_BAND_10/Qcal+1)

是否要修改现有图片?

如果是这样,您应该使用这样的更新选项打开它

gdal.Open("B10.tif", gdal.GA_Update)

接下来对 np 数组进行修改。您实际上只是在编辑 numpy 数组 Qcal 而不是 tif 中的实际光栅带。

现在要将您的修改保存到同一个波段中,您可以执行以下操作

ds.GetRasterBand(1).WriteArray(Qcal)

这是将更新后的 Qcal 数组写入 tif 的光栅带。

如果要另存为新图片

您可以创建现有图像的副本,然后像这样将 Qcal 数组保存到其中

driver = gdal.GetDriverByName('Gtiff')
dst_ds = driver.CreateCopy("example.tif", ds, 1)
dst_ds.GetRasterBand(1).WriteArray(Qcal)