根据选定波段索引生成RGB影像并导出.mat文件的技术咨询
解决方案
完整修改代码
from osgeo import gdal import numpy as np from tqdm_progress import TqdmUpTo import scipy.io as scio import matplotlib.pyplot as plt import h5py import mat73 def stretch_band(band, lower_percent=2, upper_percent=98): # 波段线性拉伸,适配显示范围 lower = np.percentile(band, lower_percent) upper = np.percentile(band, upper_percent) band_stretch = np.clip(band, lower, upper) band_stretch = (band_stretch - lower) / (upper - lower) return band_stretch def main(): remove_bands = [] mat_dict = mat73.loadmat('0042.mat') for key in mat_dict: if type(mat_dict[key]) is np.ndarray: image_data = mat_dict[key] # type: np.ndarray cols = image_data.shape[1] rows = image_data.shape[0] bands = image_data.shape[2] image_data = image_data.reshape(cols * rows, bands) sel_bands_list = [] sel_bands_list = mev_sfs(image_data, 3, remove_bands) # ----以下为新增逻辑---- # 若索引为1基(matlab风格),需先转为0基,取消注释下行即可 # sel_bands_list = [x-1 for x in sel_bands_list] # 1. 提取选中波段,恢复三维影像结构 sel_bands_data = image_data[:, sel_bands_list].reshape(rows, cols, 3) # 2. 保存为.mat格式文件 scio.savemat('selected_bands.mat', {'sel_bands_data': sel_bands_data, 'sel_bands_idx': sel_bands_list}) # 3. 生成RGB图像 r = stretch_band(sel_bands_data[:,:,0]) g = stretch_band(sel_bands_data[:,:,1]) b = stretch_band(sel_bands_data[:,:,2]) rgb_img = np.stack([r,g,b], axis=-1) plt.figure(figsize=(10,10)) plt.imshow(rgb_img) plt.axis('off') # 如需保存RGB图像取消下行注释 # plt.savefig('rgb_result.png', dpi=300, bbox_inches='tight') plt.show() if __name__ == "__main__": main()
逻辑说明
- 选中波段存储:通过
scio.savemat直接将选中的波段数据和对应索引存入mat文件,可直接在matlab中读取使用 - RGB图像生成:对三个选中波段分别做2%-98%百分位拉伸,消除极值对显示效果的影响,映射到0-1范围后拼接为RGB影像,支持直接显示和本地保存
- 索引适配:如果波段选择算法返回的是matlab风格的1基索引,取消对应行注释转为Python支持的0基索引即可
内容的提问来源于stack exchange,提问作者asif
相关产品推荐
相关产品推荐

