这篇我们不做建模,而是用 KSC 数据做 4 种常见可视化:
假彩色合成、PCA 主成分合成、LBP 纹理、各类别平均光谱曲线。
1. 环境与数据加载
1.1 导入依赖 & 画图风格
import os
import numpy as np
import scipy.io
import matplotlib
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from skimage.feature import local_binary_pattern
from skimage import img_as_ubyte, exposure
# Matplotlib 全局风格(中文 & 清晰)
matplotlib.rcParams['font.family'] = 'SimHei'
matplotlib.rcParams['axes.unicode_minus'] = False
plt.rcParams['figure.dpi'] = 120
解释
scipy.io.loadmat读.mat文件;PCA用于主成分;local_binary_pattern计算 LBP。- 设置中文字体与 DPI,避免中文乱码、图像发糊。
1.2 路径与加载函数
# 数据路径(按你的实际路径修改)
DATA_DIR = r"your_path"
X_FILE = "KSC.mat"
Y_FILE = "KSC_gt.mat"
def load_data(x_path, y_path):
"""从 .mat 读取影像与标签,返回 X:(H,W,B), y:(H,W)"""
x_data = scipy.io.loadmat(x_path)
y_data = scipy.io.loadmat(y_path)
x_key = [k for k in x_data.keys() if not k.startswith('__')][0]
y_key = [k for k in y_data.keys() if not k.startswith('__')][0]
return x_data[x_key], y_data[y_key]
# 读取数据
X_img, y_img = load_data(os.path.join(DATA_DIR, X_FILE),
os.path.join(DATA_DIR, Y_FILE))
h, w, bands = X_img.shape
print(f"图像尺寸: {
h}×{
w},波段数: {
bands}")
解释
.mat文件通常包含多个键,过滤掉__header__这类系统键。X_img是三维高光谱数据(H, W, Bands),y_img是标签图(H, W)(0 表示未标注)。
2. 工具函数(统一做拉伸/归一/类型转换)
def minmax_norm(arr):
"""全局 min-max 到 [0,1](避免除零)"""
a_min, a_max = np.min(arr), np.max(arr)
if a_max - a_min < 1e-12:
return np.zeros_like(arr, dtype=np.float32)
return (arr - a_min) / (a_max - a_min)
def perc_stretch(arr, p_low=2, p_high=98):
"""百分位拉伸,更鲁棒(减少极端值影响),输出 [0,1]"""
low, high = np.percentile(arr, [p_low, p_high])
arr = np.clip(arr, low, high)
return minmax_norm(arr)
def to_uint8(gray01):
"""把 [0,1] 灰度安全转为 uint8,供 LBP 使用(消除 skimage 浮点警告)"""
gray01 = np.clip(gray01, 0, 1)
return img_as_ubyte(gray01) # 等价于 (gray01*255).astype(np.uint8)
解释
- 百分位拉伸比简单 min-max 更稳,适合遥感影像可视化。
- LBP 官方建议用整型图像,我们先归一化再转
uint8,不会再弹警告。
3. 假彩色合成(任意 3 波段 → RGB)
def show_false_color(X, bands_rgb=(50, 30, 10), title="假彩色合成图"):
"""选择三个波段分别映射到 R/G/B 通道"""
r, g, b = bands_rgb
R = perc_stretch(X[:, :, r])
G = perc_stretch(X[:, :, g])
B = perc_stretch(X[:, :, b])
rgb = np.dstack([R, G, B])
plt.figure(figsize=(7, 6))
plt.imshow(rgb)
plt.title(f"{
title}(R/G/B = {
r}/{
g}/{
b})")
plt.axis('off')
plt.tight_layout()
plt.show()
# 示例:两组组合
show_false_color(X_img, bands_rgb=(50, 30, 10))
show_false_color(X_img, bands_rgb=(100, 50, 20), title="假彩色合成图(另一组合)")
解释
- 选择 3 个光谱波段映射到 RGB,直观看地物分布。
- 先做百分位拉伸,视觉层次更自然。
4. PCA 前三主成分合成(PC1/2/3 → RGB)
def show_pca_composite(X, n_components=3, title="PCA前三主成分合成图"):

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



