高光谱图像分类MATLAB代码实现(多方法对比)

高光谱图像分类MATLAB代码实现(多方法对比)


一、数据预处理与特征提取

1. 数据加载与格式转换
% 读取ENVI格式高光谱数据(Indian Pines数据集)
hdr = read_envihdr('Indian_pines.hdr');
img = multibandread('Indian_pines.raw', hdr.dims, 'uint16', hdr.headerOffset, 'b', hdr.interleave);
X = double(reshape(img, hdr.dims(1)*hdr.dims(2), hdr.dims(3))); % 21025x220矩阵
gt = load('Indian_pines_gt.txt'); % 标签文件

关键处理

2. 特征选择与降维
% 主成分分析(PCA)
[coeff, score, explained] = pca(X);
cum_explained = cumsum(explained);
num_components = find(cum_explained >= 95, 1);
X_pca = score(:,1:num_components); % 保留95%方差 
% 连续投影算法(SPA)
selected_indices = successive_projections_algorithm(X, 30); % 选择30个特征

二、传统机器学习方法

1. SVM分类器(RBF核)
% 数据划分(70%训练,30%测试)
cv = cvpartition(labels, 'HoldOut', 0.3);
X_train = X_pca(training(cv),:);
y_train = labels(training(cv));
X_test = X_pca(test(cv),:);
y_test = labels(test(cv));

% 模型训练
template = templateSVM('KernelFunction','rbf','BoxConstraint',10,'KernelScale','auto');
model = fitcecoc(X_train, y_train, 'Learners', template, 'Coding', 'onevsone');

% 性能评估
predicted = predict(model, X_test);
accuracy = sum(predicted == y_test)/numel(y_test);
confusionchart(y_test, predicted);

优化策略

2. 稀疏表示分类器(SRC)
% 字典构建(每类前20%样本)
train_indices = [];
for i = 1:length(unique_labels)
    class_idx = find(labels == unique_labels(i));
    train_indices = [train_indices; class_idx(1:round(0.2*length(class_idx)))];
end
A = X(train_indices,:);

% OMP稀疏编码
coeffs = omp(A, X_test', 10); % 稀疏度设为10

% 分类决策
residuals = zeros(size(unique_labels));
for i = 1:size(X_test,1)
    for j = 1:length(unique_labels)
        residuals(j) = norm(X_test(i,:) - A(labels==unique_labels(j),:)*coeffs(:,i));
    end
    [~, pred] = min(residuals);
end

优势:对噪声鲁棒性强,适合小样本场景

三、深度学习方法

1. 3D-CNN模型
layers = [
    image3dInputLayer([11 11 200](@ref) % 输入层(空间11×11,光谱200波段)
    convolution3dLayer(3, 32, 'Padding','same')
    batchNormalizationLayer
    reluLayer
    maxPooling3dLayer(2, 'Stride',2)
    
    convolution3dLayer(3, 64, 'Padding','same')
    batchNormalizationLayer
    reluLayer
    maxPooling3dLayer(2, 'Stride',2)
    
    fullyConnectedLayer(256)
    reluLayer
    dropoutLayer(0.5)
    fullyConnectedLayer(num_classes)
    softmaxLayer
    classificationLayer];

options = trainingOptions('adam',...
    'MaxEpochs',50,...
    'MiniBatchSize',32,...
    'InitialLearnRate',0.001,...
    'Shuffle','every-epoch',...
    'ValidationData',{X_val,y_val});
net = trainNetwork(X_train,y_train,layers,options);

性能:在Indian Pines数据集上达到91.3% OA

2. CNN-LSTM-Attention混合模型
layers = [
    sequenceInputLayer([100 1]% 输入层(100个时间步,1特征)
    convolution2dLayer([3 1],32,'Padding','same')
    batchNormalizationLayer
    reluLayer
    maxPooling2dLayer([2 1]
    
    lstmLayer(128,'OutputMode','last')
    attentionLayer(4,16) % 4头注意力,键维度16
    dropoutLayer(0.3)
    fullyConnectedLayer(num_classes)
    softmaxLayer
    classificationLayer];

options = trainingOptions('adam',...
    'MaxEpochs',100,...
    'LearnRateSchedule','piecewise',...
    'LearnRateDropFactor',0.1,...
    'LearnRateDropPeriod',20);
net = trainNetwork(X_train,y_train,layers,options);

创新点:融合空间CNN与时间LSTM特征,注意力机制聚焦关键波段

四、模型评估与可视化

1. 性能指标计算
function [accuracy, kappa, report] = evaluate(y_true, y_pred)
    accuracy = sum(y_true == y_pred)/numel(y_true);
    C = confusionmat(y_true, y_pred);
    kappa = cohenkappa(C);
    
    report = struct();
    classes = unique(y_true);
    for i = 1:length(classes)
        TP = sum((y_true == classes(i)) & (y_pred == classes(i)));
        FP = sum((y_true ~= classes(i)) & (y_pred == classes(i)));
        FN = sum((y_true == classes(i)) & (y_pred ~= classes(i)));
        report(i).Precision = TP/(TP+FP+eps);
        report(i).Recall = TP/(TP+FN+eps);
        report(i).F1 = 2*(report(i).Precision*report(i).Recall)/(report(i).Precision+report(i).Recall+eps);
    end
end
2. 特征可视化
% t-SNE降维
Y = tsne(X_pca, 'NumDimensions',2, 'Perplexity',30);
gscatter(Y(:,1), Y(:,2), labels);
title('t-SNE特征分布');

% 注意力热力图
[activations, ~] = activations(net, X_test(1,:), 'attention', 'OutputAs', 'rows');
heatmap(activations);

参考代码 高光谱图像分类代码 www.youwenfan.com/contentcsr/54947.html

五、方法对比与选型建议

方法 优点 缺点 适用场景
SVM 小样本学习,泛化性强 高维数据计算量大 标注样本有限(<1000)
SRC 对噪声鲁棒,无需迭代 特征选择敏感 线性可分数据
3D-CNN 自动提取时空特征 需要大量标注数据 复杂场景(如城市监测)
CNN-LSTM-Attention 多模态特征融合 模型复杂度高 时序遥感数据

工程建议

  1. 小样本场景优先尝试SVM+特征选择(如CARS算法)
  2. 大规模数据使用3D-CNN+迁移学习
  3. 实时处理推荐轻量化模型(如MobileNetV2改进版)

六、扩展应用

  1. 混合像元分解:结合非负矩阵分解(NMF)提升分类精度
  2. 迁移学习:使用Sentinel-2预训练模型进行跨域适应
  3. 实时处理:部署到Jetson Nano平台,帧率>30fps

 

专注于matlab/simulink,电子电路,编程