GDAL(Geospatial Data Abstraction Library)是一个强大的开源库,用于处理栅格和矢量地理空间数据格式。使用GDAL,你可以读取多通道图像(如卫星图像或医学图像),并对其进行处理,包括假彩色(False Color)可视化。
首先,确保你已经安装了GDAL库以及Python的GDAL绑定(如GDAL
或rasterio
库)。你可以使用pip来安装:
pip install GDAL
GDAL读取多通道图像并False Color可视化,在此以高光谱图像IndianPines作为示例进行可视化,代码为:
# -*- coding:utf-8 -*-
"""
开发时间:2024/2/26 21:56
@author:xd
"""
import argparse
from osgeo import gdal
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
import numpy as np
import scipy.io as sio
parse = argparse.ArgumentParser("Data")
parse.add_argument("-r", '--root_folder', default="./data/19920612_AVIRIS_IndianPine_Site3.tif")
args = parse.parse_args()
class MultichannelData:
def __init__(self, root_folder):
gdal.PushErrorHandler('CPLQuietErrorHandler')
self.root_folder = root_folder
if self.root_folder.split(".")[-1] == "mat":
raw_data_package = sio.loadmat(self.root_folder)
data_array = raw_data_package["indian_pines"].astype(np.float32)
h, w, b = data_array.shape
self.data_array = np.transpose(data_array, (2, 0, 1))
else:
self.data = gdal.Open(self.root_folder)
self.data_array = self.data.ReadAsArray()
def scale(self):
scaler = MinMaxScaler()
raster_array = self.data_array
b, h, w = raster_array.shape
raster_array = scaler.fit_transform(raster_array.reshape((b, h * w)).T)
raster_array = raster_array.astype(np.float32)
print(raster_array)
return raster_array.reshape(h, w, b)
def get_b_h_w(self):
b, h, w = self.data_array.shape
return b, h, w
def show(self, bands=[29, 19, 9], ax=None):
ax = ax or plt.gca()
img = self.scale()[:, :, bands]
title = 'False Color'
ax.imshow(img)
ax.set_axis_off()
ax.set_title(title + '\nBands {}, {}, {}'.format(*bands))
plt.show()
if __name__ == '__main__':
multichanneldata = MultichannelData(args.root_folder)
b,h,w = multichanneldata.get_b_h_w()
print("bands:{}, height:{}, width:{}".format(str(b), str(h), str(w)))
multichanneldata.show()
cd到工程项目,运行指令:
python read_data.py -r "/home/lab/Data/Indian Pine/Indian_pines.mat"
输出图像为: