基于稀疏表示分类器(Sparse Representation Classifier, SRC)的高光谱图像分类MATLAB实现
一、架构
1. 算法流程

二、核心代码
1. 数据加载与预处理
%% 数据加载(ENVI格式)
hdr = read_envihdr('Indian_pines.hdr'); % 读取头文件
img = multibandread('Indian_pines.raw', hdr.dims, 'uint16', hdr.headerOffset, 'b', hdr.interleave); % 读取数据% 转换为MATLAB数组
X = double(reshape(img, hdr.dims(1)*hdr.dims(2), hdr.dims(3))); % 21025x220
gt = load('Indian_pines_gt.txt'); % 加载标签% 数据归一化
X = (X - min(X(:))) ./ (max(X(:)) - min(X(:))); % 最小-最大归一化
2. 字典构建与标签划分
%% 训练样本选择(每类前20%作为训练)
train_ratio = 0.2;
class_labels = unique(gt);
train_indices = [];
for i = 1:length(class_labels)class_idx = find(gt == class_labels(i));train_indices = [train_indices; class_idx(1:round(train_ratio*length(class_idx)))];
end% 构建字典矩阵A
A = [];
labels = [];
for i = 1:length(class_labels)class_idx = find(gt == class_labels(i));train_class = X(train_indices(class_idx), :);A = [A; train_class];labels = [labels; repmat(class_labels(i), size(train_class,1),1)];
end
3. 稀疏编码实现(OMP算法)
function coeffs = omp(A, y, sparsity)% A: 字典矩阵 (n×K)% y: 测试样本 (n×1)% sparsity: 稀疏度[n, K] = size(A);r = y; % 残差初始化idx = zeros(sparsity,1);coeffs = zeros(K,1);for iter = 1:sparsityproj = A' * r;[~, max_idx] = max(abs(proj));idx(iter) = max_idx;A_sub = A(:, idx(1:iter));coeffs(idx(1:iter)) = A_sub \ y;r = y - A_sub * coeffs(idx(1:iter));end
end
4. 分类决策
%% 测试样本处理
test_indices = setdiff(1:size(X,1), train_indices);
X_test = X(test_indices, :);%% 稀疏表示分类
num_classes = length(class_labels);
predictions = zeros(size(X_test,1),1);for i = 1:size(X_test,1)y = X_test(i,:)';coeffs = omp(A, y, 10); % 稀疏度设为10% 计算类间残差residuals = zeros(num_classes,1);for j = 1:num_classesclass_samples = A(labels == class_labels(j), :);residuals(j) = norm(y - class_samples * coeffs(labels == class_labels(j)));end[~, pred_class] = min(residuals);predictions(i) = class_labels(pred_class);
end
参考代码 稀疏表示分类器应用于高光谱图像分类的MATLAB代码实现 www.youwenfan.com/contentcnk/79441.html
三、优化
1. 字典优化
% 使用K-SVD优化字典
options = struct('MaxIter', 10, 'Tol', 1e-6);
[D, X] = ksvd(A, 10, options); % 10次迭代
2. 并行计算加速
% 启用并行计算池
parpool('local');% 并行化稀疏编码
parfor i = 1:size(X_test,1)coeffs(:,i) = omp(A, X_test(i,:), 10);
end
delete(gcp);
3. 特征选择
% 基于互信息的特征选择
[~, idx] = mutualinfo(X, gt);
X_selected = X(:, idx(1:50)); % 选择前50个特征
建议结合ENVI工具进行数据预处理,并使用MATLAB Parallel Server加速大规模计算。