(Python)使用Gdal进行批量的多光谱影像波段合成

(Python)使用Gdal进行批量的多光谱影像波段合成

摘要

项目中经常遇到批量多光谱合成的任务需求,数量不多时,可以利用ENVI、ARCGIS等软件进行手工操作,但是当遇到数据量大且数据名称类似的任务时,很容易陷入机械劳动,耗时且易出错。

本文提供了个人学习科研进行中,撰写的批量多光谱合成代码。其可以按照合成对象的命名特点搜索文件中的待合成波段的影像列表,并使用Gdal完成简单的波段合成,最后使用Envi检验合成结果。

方法

代码介绍

代码主要分为两个函数:

  1. 自动获待要合成的影像名称和地址。
  2. 进行合成图像的创建与多波段的合成。

完整代码

#载入相关库
import os
import re
from osgeo import gdal
import numpy as np

'''
功能:从图中找到要波段融合的影像,然后合成为一个波段(可做批处理)
函数构成:
        1.自动获取待合成的图像名称和地址。
        2.进行图像的创建与多波段的合成。
作者:卫少东
单位:WHU
时间:20211109
'''

def getImageList(image_dir,out_dir,image):
    """
    获取相关待合成的多光谱影像地址列表
    :param image_dir: 影像文件所在文件夹
    :param out_dir: 输出文件夹
    :param image: 待寻找文件名称的正则项
    :return: 创建好的文件列表地址
    """
    image_name = re.compile(image)
    dirPath = image_dir#影像们所在的总目录,也即是遍历进行的目录
    str_size = len(image_name_list[0])
    result_file = out_dir+'\\'+image[0:25]+image[str_size-11:str_size-1]+ r'.txt'#这里按照自己影像的命名规则改变
    fresult_file = open(result_file, 'w')  # 创建影像列表文件
    for root, dirs, files in os.walk(dirPath):
        if files:
            for file in files:
                mo = image_name.search(file)
                if mo:
                    print((root + '\\' + file))
                    fresult_file.write((root + '\\' + file + '\n'))
    print("image list created.")
    return result_file

def SynthesisBands(dstlist,outfile_dir):
    """
    将多光谱波段合成一个tif
    :param dstlist: 输入待合成文件的列表
    :param outfile_dir: 影像的输出文件夹
    """
    image_dst_list = np.loadtxt(dst_list, 'str')
    dataset_init = gdal.Open(image_dst_list[0])
    #创建待输出的图
    gtiff_driver = gdal.GetDriverByName('GTiff')
    dst_name = outfile_dir+ dstlist[dstlist.rfind('\\'):dstlist.rfind('x')] + 'if'#从后往前找第一个"\"注意要用双\\表示
    out_ds = gtiff_driver.Create(dst_name, dataset_init.RasterXSize, dataset_init.RasterYSize, 4)#本文合成的对象是4个波段,按照自己的需要改变
    out_ds.SetProjection(dataset_init.GetProjection())
    out_ds.SetGeoTransform(dataset_init.GetGeoTransform())#获得原始波段的地理信息
    #往图中填各波段
    for i in range(len(image_dst_list)):
        dataset = gdal.Open(image_dst_list[i])
        band_temp = dataset.GetRasterBand(1)
        out_ds.GetRasterBand(1+i).WriteArray(band_temp.ReadAsArray())#注意band从1开始,所以要加一
    del out_ds
    print("the bands systhesised to one tif.")


bands_name = [6,8,14,28] #共四个波段
image_name_list = [r'HHZ3_20201114005237_0007_L1B_B\d\d_CMOS2_ortho',
                   r'HHZ3_20201114005237_0008_L1B_B\d\d_CMOS2_ortho',
                   r'HHZ3_20201114005237_0009_L1B_B\d\d_CMOS2_ortho',
                   r'HHZ3_20201114005237_0010_L1B_B\d\d_CMOS1_ortho',
                   r'HHZ3_20201114005237_0010_L1B_B\d\d_CMOS3_ortho',
                   r'HHZ3_20201114005237_0011_L1B_B\d\d_CMOS1_ortho',
                   r'HHZ3_20201114005237_0011_L1B_B\d\d_CMOS3_ortho'] #这里是正确搜索影像文件名称的正则表达式,需要按照自己的改变
image_dir ="D:\欧比特\欧比特ortho"
out_dir = r'D:\欧比特\欧比特ortho\res'
for name in image_name_list:
    dst_list = getImageList(image_dir, out_dir, name)
    SynthesisBands(dst_list, out_dir)
print("Patch synthesis done.")

实验结果

代码运行结果(部分)

D:\欧比特\欧比特ortho\ortho6\HHZ3_20201114005237_0011_L1B_B06_CMOS3_ortho.tif
D:\欧比特\欧比特ortho\ortho8\HHZ3_20201114005237_0011_L1B_B08_CMOS3_ortho.tif
D:\欧比特\欧比特ortho\ortho14\HHZ3_20201114005237_0011_L1B_B14_CMOS3_ortho.tif
D:\欧比特\欧比特ortho\ortho28\HHZ3_20201114005237_0011_L1B_B28_CMOS3_ortho.tif
image list created.
the bands systhesised to one tif.
Patch synthesis done.

多光谱合成结果

耗时

在商务本ThinkpadX1上,合成一组四张6000*6000左右大小的影像张耗时约3秒。

如需进一步交流,个人联系方式:WHUwsd1995(weixin)

### 使用Python库对多光谱遥感图像按不同波段进行可视化 对于多光谱遥感影像的可视化,在Python中有特定方法来处理这类数据。由于常规绘图库无法有效处理遥感影像,因此推荐使用专门针对地理空间数据分析设计的工具集。 #### 导入库 为了能够顺利操作和展示遥感影像中的各个波段信息,首先需要安装并加载必要的软件包: ```python from osgeo import gdal # GDAL用于读取栅格数据 import numpy as np # NumPy提供高效的数值计算能力 import matplotlib.pyplot as plt # Matplotlib负责最终图形渲染 ``` #### 打开并读取遥感影像 通过`gdal.Open()`函数可以打开指定路径下的遥感影像文件,并将其转换成适合进一步分析的形式。这里假设有一个名为`'O:\jcs543.tif'`的TIFF格式遥感影像文件待处理[^3]。 ```python dataset = gdal.Open(r'O:\jcs543.tif') if dataset is None: print('Unable to open the image file.') else: bands_count = dataset.RasterCount # 获取总共有多少个波段 ``` #### 提取单个波段的数据 每个多光谱遥感影像是由多个独立但相互关联的波段组成,每个波段代表不同的电磁辐射范围。下面这段代码展示了如何提取某个具体波段的内容作为NumPy数组存储起来以便后续加工[^2]。 ```python def read_band(dataset, band_index): """Read a specific band from the raster data.""" band = dataset.GetRasterBand(band_index) array_data = band.ReadAsArray() return array_data band_arrays = [] for i in range(1, bands_count + 1): # 遍历所有可用波段 band_array = read_band(dataset, i) band_arrays.append(band_array) # 将列表转置为numpy数组方便操作 bands_nparray = np.array(band_arrays) ``` #### 可视化选定波段 一旦获得了所需波段的数据之后就可以调用Matplotlib来进行直观呈现了。考虑到色彩映射等因素的影响,通常会先定义好颜色表再执行实际作图过程[^1]。 ```python plt.figure(figsize=(10, 8)) for idx, single_band in enumerate(bands_nparray, start=1): ax = plt.subplot(int(np.ceil(len(bands_nparray)/2)), 2, idx) cax = ax.imshow(single_band, cmap='gray', vmin=np.min(single_band), vmax=np.max(single_band)) plt.colorbar(cax) ax.set_title(f'Band {idx}') plt.tight_layout() plt.show() ``` 上述流程涵盖了从备环境到完成可视化的全过程,适用于大多数标多光谱遥感影像资料。当然,根据不同应用场景还可能涉及到更多高级功能和技术细节调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值