现有一个栅格文件夹里面包含了多张tiff影像要求使用python实现影像拼接将所有栅格拼接到一张栅格影像中
要实现影像拼接,可以使用Python中的GDAL库来处理栅格影像。下面是一个示例代码,可以将给定文件夹中的所有栅格影像拼接到一张栅格影像中:
import os
from osgeo import gdal
def mosaic_images(input_folder, output_file):
# 获取文件夹中的所有tiff影像文件
image_files = [os.path.join(input_folder, file) for file in os.listdir(input_folder) if file.endswith('.tif')]
# 打开第一张影像,获取其宽度、高度和波段数等信息
first_image = gdal.Open(image_files[0], gdal.GA_ReadOnly)
width = first_image.RasterXSize
height = first_image.RasterYSize
bands = first_image.RasterCount
projection = first_image.GetProjection()
geotransform = first_image.GetGeoTransform()
# 创建输出影像
driver = gdal.GetDriverByName('GTiff')
output_image = driver.Create(output_file, width, height, bands, first_image.GetRasterBand(1).DataType)
output_image.SetProjection(projection)
output_image.SetGeoTransform(geotransform)
# 逐个读取影像并写入输出影像
for i in range(len(image_files)):
image = gdal.Open(image_files[i], gdal.GA_ReadOnly)
for band in range(bands):
data = image.GetRasterBand(band + 1).ReadAsArray()
output_image.GetRasterBand(band + 1).WriteArray(data)
# 关闭影像文件
output_image = None
# 测试
input_folder = 'path/to/input/folder'
output_file = 'path/to/output/mosaic.tif'
mosaic_images(input_folder, output_file)
请替换input_folder和output_file为实际的文件夹路径和输出文件路径。这段代码将会遍历给定文件夹中的所有tiff影像文件,并将它们拼接到一张新的栅格影像中,保存为指定的输出文件
原文地址: https://www.cveoy.top/t/topic/iZM6 著作权归作者所有。请勿转载和采集!