前言:主要使用GDAL完成多个波段(tif)合并成一个tif,以及一个多波段的tif拆分成单个的tif。
参考了下列博客
《 Python遥感图像处理应用篇(二十):Python+GDAL 批量提取多波段图像为单波段图像_多波段转单波段_空中旋转篮球的博客-CSDN博客》
《 Python遥感图像处理应用篇(二十五):Python+GDAL 波段组合_python在遥感中的应用_空中旋转篮球的博客-CSDN博客》
1 波段的合并
需求:如图所示,需要把图中的5个tif合并成1个tif
代码实现:
from osgeo import gdal
import os
if __name__ == '__main__':
inputpath = r"C:\Users\Administrator\Desktop\in" # 输入路径
outputpath = r"C:\Users\Administrator\Desktop\out" # 输出路径
outputname = 'pet2022.tif'
file_dir = r'C:\Users\Administrator\Desktop\in\pet_2002_01.tif'
file_list = os.listdir(inputpath)
bands_num = len(file_list) # 波段个数
# 以下是具体计算代码
gdal.UseExceptions()
ds = gdal.Open(file_dir)
band = ds.GetRasterBand(1)
gtiff_driver = gdal.GetDriverByName('GTiff')
output_image = os.path.join(outputpath, outputname)
out_ds = gtiff_driver.Create(output_image, band.XSize, band.YSize, bands_num, gdal.GDT_Float32,options=["TILED=YES", "COMPRESS=LZW"]) # 注意输出数据类型
out_ds.SetProjection(ds.GetProjection())
out_ds.SetGeoTransform(ds.GetGeoTransform())
j = 1 # 波段索引
for readPath in subfile_list:
print("第",j)
# 获取输入输出文件完整路径
file_dir = os.path.join(inputpath, readPath)
# 以下是具体计算代码
gdal.UseExceptions()
ds = gdal.Open(file_dir)
band = ds.GetRasterBand(1)
image_array = band.ReadAsArray()
nrows, ncols = image_array.shape
# 将数组的各通道写入tif图片
out_ds.GetRasterBand(j).WriteArray(image_array) # 将每个波段的数据写入内存,此时没有写入硬盘
j += 1
if j > bands_num:
break
out_ds.FlushCache() # 最终将数据写入硬盘
out_ds.BuildOverviews(overviewlist=[1, 2, 4, 8, 16])
out_ds = None # 注意必须关闭tif文件
2 波段的拆分
如图1所示,一个tif里面有5个波段,需要拆分成单个波段,代码如下所示:
from osgeo import gdal
# 将遥感影像归一化处理 写成函数
def GetEnvolopePoint(inputpath, output_filepath):
gdal.UseExceptions()
ds = gdal.Open(inputpath)
band01 = ds.GetRasterBand(1)
im_width, im_height = band01.XSize, band01.YSize
print(inputpath, "影像大小为:", im_width, im_height)
dim_z = ds.RasterCount # 图像通道数
for i in range(1, dim_z + 1):
band = ds.GetRasterBand(i)
band_array = band.ReadAsArray()
print("Image Shape:", band_array.shape)
print("开始提取第{}波段".format(i))
# 获取输出文件完整路径
output_image = input_image_filepath.split("\\")[-1]
print("output_image:", output_image)
output_image = output_filepath + "\\"+output_image
output_image = output_image.replace(".tif", "_b" + str(i) + ".tif")
print(output_image)
gtiff_driver = gdal.GetDriverByName('GTiff')
out_ds = gtiff_driver.Create(output_image, im_width, im_height, 1, gdal.GDT_Float32) # 注意输出数据类型和输入一致
out_ds.SetProjection(ds.GetProjection())
out_ds.SetGeoTransform(ds.GetGeoTransform())
out_ds.GetRasterBand(1).WriteArray(band_array) # 将每个波段的数据写入内存,此时没有写入硬盘
out_ds.FlushCache() # 最终将数据写入硬盘
out_ds = None # 注意必须关闭tif文件
if __name__ == '__main__':
# 输入路径 文件夹
input_image_filepath = r"C:\Users\Administrator\Desktop\in1\pet2022.tif"
# 输出路径 文件夹
output_folder = r"C:\Users\Administrator\Desktop\out1"
GetEnvolopePoint(input_image_filepath, output_folder)