MATLAB实现:基于图像对比度和波段相关性的高光谱波段选择算法

一、主算法实现

1、主函数文件

matlab 复制代码
%% 主函数:波段选择算法
function selected_bands = band_selection_main(hsi_cube, num_bands, method, params)
% 基于对比度和相关性的波段选择算法
%
% 输入参数:
%   hsi_cube: 高光谱数据立方体 (M x N x L)
%   num_bands: 要选择的波段数量
%   method: 选择方法
%     'greedy' - 贪婪算法
%     'clustering' - 聚类算法
%     'ranking' - 排序算法
%     'hybrid' - 混合算法
%   params: 参数结构体
%
% 输出参数:
%   selected_bands: 选择的波段索引

% 默认参数
if nargin < 4
    params = struct();
end
if nargin < 3
    method = 'greedy';
end

% 添加默认参数
if ~isfield(params, 'alpha')
    params.alpha = 0.7;  % 对比度权重
end
if ~isfield(params, 'contrast_method')
    params.contrast_method = 'combined';  % 对比度计算方法
end
if ~isfield(params, 'verbose')
    params.verbose = true;  % 显示进度
end

% 检查输入
[M, N, L] = size(hsi_cube);
if num_bands > L
    error('选择的波段数不能超过总波段数');
end

if params.verbose
    fprintf('高光谱波段选择算法\n');
    fprintf('数据尺寸: %d x %d x %d\n', M, N, L);
    fprintf('目标波段数: %d\n', num_bands);
    fprintf('选择方法: %s\n', method);
    fprintf('对比度权重: %.2f\n', params.alpha);
end

% 计算对比度
if params.verbose, fprintf('计算对比度指标...\n'); end
contrast_scores = compute_contrast_scores(hsi_cube, params.contrast_method);

% 计算相关性矩阵
if params.verbose, fprintf('计算波段相关性...\n'); end
corr_matrix = compute_correlation_matrix(hsi_cube);

% 根据方法选择波段
switch lower(method)
    case 'greedy'
        selected_bands = greedy_selection(contrast_scores, corr_matrix, ...
                                         num_bands, params.alpha);
    case 'clustering'
        selected_bands = clustering_selection(hsi_cube, contrast_scores, ...
                                             num_bands, params);
    case 'ranking'
        selected_bands = ranking_selection(contrast_scores, corr_matrix, ...
                                          num_bands, params.alpha);
    case 'hybrid'
        selected_bands = hybrid_selection(hsi_cube, contrast_scores, ...
                                         corr_matrix, num_bands, params);
    otherwise
        error('未知的选择方法: %s', method);
end

% 排序选择的波段
selected_bands = sort(selected_bands);

if params.verbose
    fprintf('波段选择完成!\n');
    fprintf('选择的波段: %s\n', mat2str(selected_bands));
    
    % 评估结果
    evaluation = evaluate_selection(selected_bands, contrast_scores, corr_matrix);
    print_evaluation_results(evaluation);
end
end

2、对比度计算函数

matlab 复制代码
%% 对比度计算函数
function contrast_scores = compute_contrast_scores(hsi_cube, method)
% 计算波段对比度
%
% 输入参数:
%   hsi_cube: 高光谱数据立方体
%   method: 对比度计算方法
%     'std' - 标准差
%     'entropy' - 熵
%     'gradient' - 梯度
%     'laplacian' - 拉普拉斯
%     'combined' - 综合
%
% 输出参数:
%   contrast_scores: 对比度得分向量

[M, N, L] = size(hsi_cube);

switch lower(method)
    case 'std'
        contrast_scores = compute_std_contrast(hsi_cube);
    case 'entropy'
        contrast_scores = compute_entropy_contrast(hsi_cube);
    case 'gradient'
        contrast_scores = compute_gradient_contrast(hsi_cube);
    case 'laplacian'
        contrast_scores = compute_laplacian_contrast(hsi_cube);
    case 'combined'
        % 计算多种对比度
        std_scores = compute_std_contrast(hsi_cube);
        entropy_scores = compute_entropy_contrast(hsi_cube);
        gradient_scores = compute_gradient_contrast(hsi_cube);
        
        % 归一化
        std_scores = normalize_scores(std_scores);
        entropy_scores = normalize_scores(entropy_scores);
        gradient_scores = normalize_scores(gradient_scores);
        
        % 加权组合
        weights = [0.4, 0.3, 0.3];  % 可调整
        contrast_scores = weights(1) * std_scores + ...
                         weights(2) * entropy_scores + ...
                         weights(3) * gradient_scores;
    otherwise
        error('未知的对比度计算方法: %s', method);
end

% 归一化到[0,1]
contrast_scores = normalize_scores(contrast_scores);
end

%% 标准差对比度
function scores = compute_std_contrast(hsi_cube)
[M, N, L] = size(hsi_cube);
scores = zeros(L, 1);

for i = 1:L
    band = hsi_cube(:,:,i);
    scores(i) = std(band(:));
end
end

%% 熵对比度
function scores = compute_entropy_contrast(hsi_cube, num_bins)
if nargin < 2
    num_bins = 256;
end

[M, N, L] = size(hsi_cube);
scores = zeros(L, 1);

for i = 1:L
    band = hsi_cube(:,:,i);
    
    % 归一化到0-255
    band_min = min(band(:));
    band_max = max(band(:));
    if band_max > band_min
        band_norm = (band - band_min) / (band_max - band_min) * 255;
    else
        band_norm = zeros(size(band));
    end
    
    % 计算直方图
    [counts, ~] = imhist(uint8(band_norm), num_bins);
    prob = counts / sum(counts);
    prob = prob(prob > 0);  % 移除零概率
    
    % 计算熵
    scores(i) = -sum(prob .* log2(prob));
end
end

%% 梯度对比度
function scores = compute_gradient_contrast(hsi_cube)
[M, N, L] = size(hsi_cube);
scores = zeros(L, 1);

for i = 1:L
    band = double(hsi_cube(:,:,i));
    
    % Sobel梯度
    [Gx, Gy] = imgradientxy(band, 'sobel');
    
    % 梯度幅值
    G = sqrt(Gx.^2 + Gy.^2);
    
    % 平均梯度
    scores(i) = mean(G(:));
end
end

%% 拉普拉斯对比度
function scores = compute_laplacian_contrast(hsi_cube)
[M, N, L] = size(hsi_cube);
scores = zeros(L, 1);

for i = 1:L
    band = double(hsi_cube(:,:,i));
    
    % 拉普拉斯算子
    H = fspecial('laplacian', 0.2);
    L_img = imfilter(band, H, 'replicate');
    
    % 平均拉普拉斯响应
    scores(i) = mean(abs(L_img(:)));
end
end

3、相关性计算

matlab 复制代码
%% 相关性计算函数
function corr_matrix = compute_correlation_matrix(hsi_cube)
% 计算波段间的相关系数矩阵
%
% 输入参数:
%   hsi_cube: 高光谱数据立方体
%
% 输出参数:
%   corr_matrix: 相关系数矩阵 (L x L)

[M, N, L] = size(hsi_cube);

% 重塑为二维矩阵 (像素数 x 波段数)
data = reshape(hsi_cube, M*N, L);

% 计算相关系数矩阵
corr_matrix = corrcoef(data);
end

%% 互信息矩阵
function mi_matrix = compute_mutual_info_matrix(hsi_cube, num_bins)
% 计算波段间的互信息矩阵
if nargin < 2
    num_bins = 32;
end

[M, N, L] = size(hsi_cube);
data = reshape(hsi_cube, M*N, L);
mi_matrix = zeros(L, L);

for i = 1:L
    for j = i:L
        if i == j
            mi_matrix(i, j) = 1;
        else
            % 计算互信息
            mi = compute_mutual_information(data(:, i), data(:, j), num_bins);
            mi_matrix(i, j) = mi;
            mi_matrix(j, i) = mi;
        end
    end
end
end

%% 计算互信息
function mi = compute_mutual_information(x, y, num_bins)
% 计算两个变量间的互信息

% 联合直方图
[hist_2d, ~] = hist3([x, y], [num_bins, num_bins]);

% 归一化得到联合概率分布
p_xy = hist_2d / sum(hist_2d(:));
p_x = sum(p_xy, 2);
p_y = sum(p_xy, 1);

% 计算互信息
mi = 0;
for i = 1:num_bins
    for j = 1:num_bins
        if p_xy(i,j) > 0 && p_x(i) > 0 && p_y(j) > 0
            mi = mi + p_xy(i,j) * log2(p_xy(i,j) / (p_x(i) * p_y(j)));
        end
    end
end
end

4、归一化函数

matlab 复制代码
%% 分数归一化
function normalized_scores = normalize_scores(scores)
% 将分数归一化到[0,1]区间

min_score = min(scores);
max_score = max(scores);

if max_score > min_score
    normalized_scores = (scores - min_score) / (max_score - min_score);
else
    normalized_scores = ones(size(scores));
end
end

二、选择算法实现

1、贪婪选择算法

matlab 复制代码
%% 贪婪选择算法
function selected_bands = greedy_selection(contrast_scores, corr_matrix, ...
                                         num_bands, alpha)
% 贪婪算法选择波段
%
% 输入参数:
%   contrast_scores: 对比度得分 (L x 1)
%   corr_matrix: 相关系数矩阵 (L x L)
%   num_bands: 要选择的波段数
%   alpha: 对比度权重 (0-1)
%
% 输出参数:
%   selected_bands: 选择的波段索引

L = length(contrast_scores);
selected_bands = [];
remaining_bands = 1:L;

% 第一步:选择对比度最高的波段
[~, first_band] = max(contrast_scores);
selected_bands = [selected_bands, first_band];
remaining_bands(remaining_bands == first_band) = [];

% 迭代选择
while length(selected_bands) < num_bands && ~isempty(remaining_bands)
    best_score = -inf;
    best_band = -1;
    
    for i = 1:length(remaining_bands)
        band = remaining_bands(i);
        
        % 计算与已选波段的最大相关性
        max_corr = 0;
        for j = 1:length(selected_bands)
            corr_val = abs(corr_matrix(band, selected_bands(j)));
            if corr_val > max_corr
                max_corr = corr_val;
            end
        end
        
        % 计算综合得分
        % 相关性越低越好,所以用(1 - max_corr)
        score = alpha * contrast_scores(band) + (1 - alpha) * (1 - max_corr);
        
        if score > best_score
            best_score = score;
            best_band = band;
        end
    end
    
    if best_band > 0
        selected_bands = [selected_bands, best_band];
        remaining_bands(remaining_bands == best_band) = [];
    end
end
end

2、聚类选择算法

matlab 复制代码
%% 聚类选择算法
function selected_bands = clustering_selection(hsi_cube, contrast_scores, ...
                                             num_bands, params)
% 基于聚类的波段选择
%
% 输入参数:
%   hsi_cube: 高光谱数据立方体
%   contrast_scores: 对比度得分
%   num_bands: 要选择的波段数
%   params: 参数结构体
%
% 输出参数:
%   selected_bands: 选择的波段索引

[M, N, L] = size(hsi_cube);

% 提取波段特征
features = zeros(L, 8);  % 8个特征
for i = 1:L
    band_data = hsi_cube(:,:,i);
    band_vector = band_data(:);
    
    % 统计特征
    features(i, 1) = mean(band_vector);
    features(i, 2) = std(band_vector);
    features(i, 3) = max(band_vector);
    features(i, 4) = min(band_vector);
    features(i, 5) = median(band_vector);
    features(i, 6) = skewness(band_vector);
    features(i, 7) = kurtosis(band_vector);
    features(i, 8) = contrast_scores(i);
end

% 标准化特征
features_norm = zscore(features);

% K-means聚类
if ~isfield(params, 'n_clusters')
    n_clusters = num_bands;
else
    n_clusters = params.n_clusters;
end

[idx, centers] = kmeans(features_norm, n_clusters, ...
                       'Replicates', 5, 'MaxIter', 300);

% 从每个类中选择对比度最高的波段
selected_bands = [];
for c = 1:n_clusters
    cluster_bands = find(idx == c);
    
    if ~isempty(cluster_bands)
        % 找到类中对比度最高的波段
        [~, max_idx] = max(contrast_scores(cluster_bands));
        selected_bands = [selected_bands, cluster_bands(max_idx)];
    end
end

% 如果选择的波段数超过需求,按对比度排序
if length(selected_bands) > num_bands
    [~, sort_idx] = sort(contrast_scores(selected_bands), 'descend');
    selected_bands = selected_bands(sort_idx(1:num_bands));
end
end

3、排序选择算法

matlab 复制代码
%% 排序选择算法
function selected_bands = ranking_selection(contrast_scores, corr_matrix, ...
                                          num_bands, alpha)
% 基于排序的选择算法
%
% 计算每个波段的综合得分,然后选择得分最高的波段

L = length(contrast_scores);
scores = zeros(L, 1);

% 计算每个波段的综合得分
for i = 1:L
    % 计算与其他波段的相关性平均值
    corr_with_others = mean(abs(corr_matrix(i, [1:i-1, i+1:end])));
    
    % 综合得分
    scores(i) = alpha * contrast_scores(i) + (1 - alpha) * (1 - corr_with_others);
end

% 按得分排序
[~, sorted_indices] = sort(scores, 'descend');

% 选择前num_bands个
selected_bands = sorted_indices(1:num_bands);
end

4、混合选择算法

matlab 复制代码
%% 混合选择算法
function selected_bands = hybrid_selection(hsi_cube, contrast_scores, ...
                                         corr_matrix, num_bands, params)
% 混合选择算法
%
% 结合多种方法提高选择质量

L = length(contrast_scores);

% 使用多种方法选择
methods = {'greedy', 'clustering', 'ranking'};
all_selections = cell(length(methods), 1);

% 计算每种方法的结果
for m = 1:length(methods)
    switch lower(methods{m})
        case 'greedy'
            all_selections{m} = greedy_selection(contrast_scores, corr_matrix, ...
                                               num_bands, params.alpha);
        case 'clustering'
            all_selections{m} = clustering_selection(hsi_cube, contrast_scores, ...
                                                   num_bands, params);
        case 'ranking'
            all_selections{m} = ranking_selection(contrast_scores, corr_matrix, ...
                                                num_bands, params.alpha);
    end
end

% 投票选择
band_votes = zeros(L, 1);
for m = 1:length(methods)
    for b = 1:length(all_selections{m})
        band = all_selections{m}(b);
        band_votes(band) = band_votes(band) + 1;
    end
end

% 按投票数排序
[~, sorted_bands] = sort(band_votes, 'descend');
selected_bands = sorted_bands(1:min(num_bands, length(sorted_bands)));

% 如果平票,用对比度排序
if length(selected_bands) > num_bands
    % 处理平票
    tie_bands = selected_bands(num_bands:end);
    [~, tie_sort] = sort(contrast_scores(tie_bands), 'descend');
    tie_bands = tie_bands(tie_sort);
    
    % 选择前num_bands个
    selected_bands = [selected_bands(1:num_bands-1); tie_bands(1)];
end
end

三、评估函数

matlab 复制代码
%% 评估选择结果
function evaluation = evaluate_selection(selected_bands, contrast_scores, corr_matrix)
% 评估波段选择结果
%
% 输入参数:
%   selected_bands: 选择的波段索引
%   contrast_scores: 对比度得分
%   corr_matrix: 相关系数矩阵
%
% 输出参数:
%   evaluation: 评估结果结构体

evaluation = struct();

% 选择的波段数
evaluation.num_selected = length(selected_bands);

% 平均对比度
evaluation.avg_contrast = mean(contrast_scores(selected_bands));

% 对比度标准差
evaluation.std_contrast = std(contrast_scores(selected_bands));

% 与原始对比度的比值
evaluation.contrast_ratio = evaluation.avg_contrast / mean(contrast_scores);

% 所选波段间的平均相关性
selected_corr = corr_matrix(selected_bands, selected_bands);
% 去掉对角线
selected_corr = selected_corr - diag(diag(selected_corr));
evaluation.avg_correlation = mean(abs(selected_corr(:)));

% 所选波段间的最大相关性
evaluation.max_correlation = max(abs(selected_corr(:)));

% 冗余度指标
evaluation.redundancy = 1 / (evaluation.num_selected * (1 - evaluation.avg_correlation + eps));

% 信息保留率
% 这里用对比度之和的比值作为近似
total_contrast = sum(contrast_scores);
selected_contrast = sum(contrast_scores(selected_bands));
evaluation.information_ratio = selected_contrast / total_contrast;

% 计算波段分布均匀性
band_indices = sort(selected_bands);
gaps = diff(band_indices);
evaluation.uniformity = std(gaps) / mean(gaps);  % 越小越均匀
end

%% 打印评估结果
function print_evaluation_results(evaluation)
fprintf('\n=== 波段选择评估结果 ===\n');
fprintf('选择的波段数: %d\n', evaluation.num_selected);
fprintf('平均对比度: %.4f\n', evaluation.avg_contrast);
fprintf('对比度标准差: %.4f\n', evaluation.std_contrast);
fprintf('对比度比值: %.4f\n', evaluation.contrast_ratio);
fprintf('平均相关性: %.4f\n', evaluation.avg_correlation);
fprintf('最大相关性: %.4f\n', evaluation.max_correlation);
fprintf('冗余度指标: %.4f\n', evaluation.redundancy);
fprintf('信息保留率: %.4f\n', evaluation.information_ratio);
fprintf('分布均匀性: %.4f\n', evaluation.uniformity);
fprintf('==========================\n\n');
end

参考代码 基于图像对比度和波段相关性的波段选择算法 www.youwenfan.com/contentcsu/70124.html

四、可视化函数

matlab 复制代码
%% 可视化结果
function visualize_band_selection(hsi_cube, selected_bands, contrast_scores, corr_matrix)
% 可视化波段选择结果
%
% 输入参数:
%   hsi_cube: 高光谱数据立方体
%   selected_bands: 选择的波段索引
%   contrast_scores: 对比度得分
%   corr_matrix: 相关系数矩阵

L = size(hsi_cube, 3);

% 创建图形
fig = figure('Position', [100, 100, 1400, 900]);
fig.Color = 'w';

% 1. 对比度曲线
subplot(2, 3, 1);
plot(1:L, contrast_scores, 'b-', 'LineWidth', 1.5);
hold on;
plot(selected_bands, contrast_scores(selected_bands), 'ro', ...
     'MarkerSize', 8, 'LineWidth', 2, 'MarkerFaceColor', 'r');
xlabel('波段索引');
ylabel('对比度得分');
title('波段对比度分布');
grid on;
legend('所有波段', '选择波段', 'Location', 'best');

% 2. 相关性矩阵
subplot(2, 3, 2);
imagesc(abs(corr_matrix));
colorbar;
xlabel('波段索引');
ylabel('波段索引');
title('波段相关性矩阵');
colormap('hot');
axis square;

% 3. 选择的波段在相关性矩阵中的位置
subplot(2, 3, 3);
selected_corr = corr_matrix(selected_bands, selected_bands);
imagesc(abs(selected_corr));
colorbar;
xlabel('选择波段索引');
ylabel('选择波段索引');
title('选择波段的相关性');
colormap('hot');
axis square;

% 4. 显示选择的波段图像
subplot(2, 3, 4);
if length(selected_bands) >= 1
    band1 = hsi_cube(:,:,selected_bands(1));
    imagesc(band1);
    colormap(gray);
    colorbar;
    title(sprintf('波段 %d', selected_bands(1)));
    axis image;
    axis off;
end

subplot(2, 3, 5);
if length(selected_bands) >= 2
    band2 = hsi_cube(:,:,selected_bands(2));
    imagesc(band2);
    colormap(gray);
    colorbar;
    title(sprintf('波段 %d', selected_bands(2)));
    axis image;
    axis off;
end

subplot(2, 3, 6);
if length(selected_bands) >= 3
    band3 = hsi_cube(:,:,selected_bands(3));
    imagesc(band3);
    colormap(gray);
    colorbar;
    title(sprintf('波段 %d', selected_bands(3)));
    axis image;
    axis off;
end

% 添加总体标题
sgtitle('高光谱波段选择结果可视化', 'FontSize', 16, 'FontWeight', 'bold');
end

%% 对比不同方法的性能
function compare_methods(hsi_cube, num_bands_list)
% 对比不同选择方法的性能
%
% 输入参数:
%   hsi_cube: 高光谱数据立方体
%   num_bands_list: 要测试的波段数列表

methods = {'greedy', 'clustering', 'ranking', 'hybrid'};
n_methods = length(methods);
n_cases = length(num_bands_list);

% 存储结果
results = struct();
for m = 1:n_methods
    results.(methods{m}).avg_contrast = zeros(n_cases, 1);
    results.(methods{m}).avg_correlation = zeros(n_cases, 1);
    results.(methods{m}).redundancy = zeros(n_cases, 1);
    results.(methods{m}).information_ratio = zeros(n_cases, 1);
end

% 预计算对比度和相关性矩阵
contrast_scores = compute_contrast_scores(hsi_cube, 'combined');
corr_matrix = compute_correlation_matrix(hsi_cube);

% 测试每种方法和每种波段数
for m = 1:n_methods
    method = methods{m};
    fprintf('测试方法: %s\n', method);
    
    for c = 1:n_cases
        num_bands = num_bands_list(c);
        fprintf('  波段数: %d...', num_bands);
        
        % 选择波段
        params = struct('alpha', 0.7, 'verbose', false);
        selected_bands = band_selection_main(hsi_cube, num_bands, method, params);
        
        % 评估
        evaluation = evaluate_selection(selected_bands, contrast_scores, corr_matrix);
        
        % 存储结果
        results.(method).avg_contrast(c) = evaluation.avg_contrast;
        results.(method).avg_correlation(c) = evaluation.avg_correlation;
        results.(method).redundancy(c) = evaluation.redundancy;
        results.(method).information_ratio(c) = evaluation.information_ratio;
        
        fprintf('完成\n');
    end
end

% 绘制对比图
fig = figure('Position', [100, 100, 1200, 800]);
fig.Color = 'w';

% 颜色
colors = lines(n_methods);

% 1. 平均对比度
subplot(2, 2, 1);
hold on;
for m = 1:n_methods
    plot(num_bands_list, results.(methods{m}).avg_contrast, ...
         'Color', colors(m,:), 'LineWidth', 2, 'Marker', 'o');
end
xlabel('选择的波段数');
ylabel('平均对比度');
title('平均对比度比较');
grid on;
legend(methods, 'Location', 'best');

% 2. 平均相关性
subplot(2, 2, 2);
hold on;
for m = 1:n_methods
    plot(num_bands_list, results.(methods{m}).avg_correlation, ...
         'Color', colors(m,:), 'LineWidth', 2, 'Marker', 'o');
end
xlabel('选择的波段数');
ylabel('平均相关性');
title('平均相关性比较');
grid on;
legend(methods, 'Location', 'best');

% 3. 冗余度
subplot(2, 2, 3);
hold on;
for m = 1:n_methods
    plot(num_bands_list, results.(methods{m}).redundancy, ...
         'Color', colors(m,:), 'LineWidth', 2, 'Marker', 'o');
end
xlabel('选择的波段数');
ylabel('冗余度');
title('冗余度比较');
grid on;
legend(methods, 'Location', 'best');

% 4. 信息保留率
subplot(2, 2, 4);
hold on;
for m = 1:n_methods
    plot(num_bands_list, results.(methods{m}).information_ratio, ...
         'Color', colors(m,:), 'LineWidth', 2, 'Marker', 'o');
end
xlabel('选择的波段数');
ylabel('信息保留率');
title('信息保留率比较');
grid on;
legend(methods, 'Location', 'best');

sgtitle('不同波段选择方法性能比较', 'FontSize', 16, 'FontWeight', 'bold');
end

五、主程序示例

matlab 复制代码
%% 主程序示例
function demo_band_selection()
% 演示波段选择算法

fprintf('=== 高光谱波段选择算法演示 ===\n\n');

% 1. 生成模拟高光谱数据
fprintf('1. 生成模拟高光谱数据...\n');
hsi_cube = generate_simulated_hsi_data();
[M, N, L] = size(hsi_cube);
fprintf('   数据尺寸: %d x %d x %d\n', M, N, L);

% 2. 设置参数
num_bands_to_select = 20;
method = 'hybrid';  % 可以尝试 'greedy', 'clustering', 'ranking', 'hybrid'

% 3. 执行波段选择
fprintf('2. 执行波段选择...\n');
fprintf('   方法: %s\n', method);
fprintf('   目标波段数: %d\n', num_bands_to_select);

params = struct();
params.alpha = 0.7;  % 对比度权重
params.contrast_method = 'combined';
params.verbose = true;

selected_bands = band_selection_main(hsi_cube, num_bands_to_select, method, params);

% 4. 计算评估指标
fprintf('3. 计算评估指标...\n');
contrast_scores = compute_contrast_scores(hsi_cube, params.contrast_method);
corr_matrix = compute_correlation_matrix(hsi_cube);
evaluation = evaluate_selection(selected_bands, contrast_scores, corr_matrix);
print_evaluation_results(evaluation);

% 5. 可视化结果
fprintf('4. 生成可视化...\n');
visualize_band_selection(hsi_cube, selected_bands, contrast_scores, corr_matrix);

% 6. 对比不同方法
fprintf('5. 对比不同方法性能...\n');
num_bands_list = [5, 10, 15, 20, 25, 30];
compare_methods(hsi_cube, num_bands_list);

fprintf('\n=== 演示完成 ===\n');
end

%% 生成模拟高光谱数据
function hsi_cube = generate_simulated_hsi_data()
% 生成模拟高光谱数据用于演示

height = 100;
width = 100;
bands = 200;

% 波长范围
wavelengths = linspace(400, 1000, bands);

% 创建空数据立方体
hsi_cube = zeros(height, width, bands);

% 模拟4种地物的光谱特征
% 1. 植被
for i = 1:height/2
    for j = 1:width/2
        % 植被光谱特征:绿峰和红边
        spectrum = 0.8 * exp(-0.5 * ((wavelengths - 550) / 50).^2) + ...
                   0.3 * exp(-0.5 * ((wavelengths - 680) / 30).^2);
        hsi_cube(i, j, :) = spectrum;
    end
end

% 2. 水体
for i = 1:height/2
    for j = width/2+1:width
        % 水体光谱特征:蓝光吸收
        spectrum = 0.6 * exp(-0.5 * ((wavelengths - 450) / 80).^2);
        hsi_cube(i, j, :) = spectrum;
    end
end

% 3. 土壤
for i = height/2+1:height
    for j = 1:width/2
        % 土壤光谱特征:逐渐上升
        spectrum = 0.4 + 0.3 * (wavelengths - 400) / 600;
        hsi_cube(i, j, :) = spectrum;
    end
end

% 4. 建筑
for i = height/2+1:height
    for j = width/2+1:width
        % 建筑光谱特征:相对平坦
        spectrum = 0.5 * ones(size(wavelengths));
        hsi_cube(i, j, :) = spectrum;
    end
end

% 添加高斯噪声
noise_level = 0.05;
hsi_cube = hsi_cube + noise_level * randn(size(hsi_cube));

% 添加高斯模糊
for b = 1:bands
    hsi_cube(:,:,b) = imgaussfilt(hsi_cube(:,:,b), 1);
end
end

六、高级功能

1、自适应权重调整

matlab 复制代码
%% 自适应权重调整
function alpha = compute_adaptive_alpha(hsi_cube)
% 根据数据特性自适应计算对比度权重
%
% 输入参数:
%   hsi_cube: 高光谱数据立方体
%
% 输出参数:
%   alpha: 自适应计算的对比度权重

% 计算波段的信息量
band_entropy = zeros(size(hsi_cube, 3), 1);
for i = 1:size(hsi_cube, 3)
    band = hsi_cube(:,:,i);
    band_entropy(i) = entropy(band);
end

% 计算信息量的分布特性
entropy_mean = mean(band_entropy);
entropy_std = std(band_entropy);
entropy_cv = entropy_std / entropy_mean;  % 变异系数

% 自适应调整权重
if entropy_cv > 0.3
    % 信息分布不均匀,更注重对比度
    alpha = 0.8;
elseif entropy_cv > 0.15
    % 中等分布
    alpha = 0.6;
else
    % 信息分布均匀,平衡考虑
    alpha = 0.5;
end

fprintf('自适应权重计算:\n');
fprintf('  熵均值: %.4f\n', entropy_mean);
fprintf('  熵标准差: %.4f\n', entropy_std);
fprintf('  变异系数: %.4f\n', entropy_cv);
fprintf('  计算的alpha: %.2f\n', alpha);
end

2、批量处理函数

matlab 复制代码
%% 批量处理
function batch_process_hsi_data(data_folder, output_folder, num_bands)
% 批量处理高光谱数据
%
% 输入参数:
%   data_folder: 数据文件夹路径
%   output_folder: 输出文件夹路径
%   num_bands: 要选择的波段数

% 创建输出文件夹
if ~exist(output_folder, 'dir')
    mkdir(output_folder);
end

% 获取所有.mat文件
file_list = dir(fullfile(data_folder, '*.mat'));
n_files = length(file_list);

% 进度条
h_wait = waitbar(0, '批量处理中...');

for f = 1:n_files
    % 更新进度
    waitbar(f/n_files, h_wait, sprintf('处理文件 %d/%d', f, n_files));
    
    % 加载数据
    file_name = file_list(f).name;
    file_path = fullfile(data_folder, file_name);
    
    try
        data = load(file_path);
        
        % 假设数据变量名为'hsi_data'
        if isfield(data, 'hsi_data')
            hsi_cube = data.hsi_data;
        else
            % 尝试找到高光谱数据
            field_names = fieldnames(data);
            found = false;
            for fn = 1:length(field_names)
                var_data = data.(field_names{fn});
                if ndims(var_data) == 3
                    hsi_cube = var_data;
                    found = true;
                    break;
                end
            end
            if ~found
                warning('文件 %s 中没有找到高光谱数据', file_name);
                continue;
            end
        end
        
        % 波段选择
        params = struct('alpha', 0.7, 'verbose', false);
        selected_bands = band_selection_main(hsi_cube, num_bands, 'hybrid', params);
        
        % 提取选择的波段
        selected_data = hsi_cube(:,:,selected_bands);
        
        % 保存结果
        [~, name, ~] = fileparts(file_name);
        output_file = fullfile(output_folder, [name '_selected.mat']);
        
        save(output_file, 'selected_data', 'selected_bands', '-v7.3');
        
        fprintf('已处理: %s\n', file_name);
        
    catch ME
        warning('处理文件 %s 时出错: %s', file_name, ME.message);
    end
end

% 关闭进度条
close(h_wait);
fprintf('批量处理完成!\n');
end

3、性能评估函数

matlab 复制代码
%% 性能评估
function performance = evaluate_classification_performance(original_data, selected_data, labels)
% 评估分类性能
%
% 输入参数:
%   original_data: 原始高光谱数据
%   selected_data: 选择后的高光谱数据
%   labels: 地物标签
%
% 输出参数:
%   performance: 性能指标结构体

% 确保标签是列向量
if isrow(labels)
    labels = labels';
end

% 移除未标记的像素
valid_idx = labels > 0;
labels = labels(valid_idx);

% 重塑数据
[M, N, L_orig] = size(original_data);
[M, N, L_sel] = size(selected_data);

X_orig = reshape(original_data, M*N, L_orig);
X_sel = reshape(selected_data, M*N, L_sel);

X_orig = X_orig(valid_idx, :);
X_sel = X_sel(valid_idx, :);

% 划分训练集和测试集
rng(42);  % 固定随机种子
cv = cvpartition(labels, 'HoldOut', 0.3);
train_idx = cv.training;
test_idx = cv.test;

X_train_orig = X_orig(train_idx, :);
X_test_orig = X_orig(test_idx, :);
X_train_sel = X_sel(train_idx, :);
X_test_sel = X_sel(test_idx, :);
y_train = labels(train_idx);
y_test = labels(test_idx);

% SVM分类器
template = templateSVM('KernelFunction', 'rbf', ...
                      'BoxConstraint', 1, ...
                      'KernelScale', 'auto');

% 训练原始数据分类器
fprintf('训练原始数据SVM分类器...\n');
svm_orig = fitcecoc(X_train_orig, y_train, 'Learners', template);

% 训练选择数据分类器
fprintf('训练选择数据SVM分类器...\n');
svm_sel = fitcecoc(X_train_sel, y_train, 'Learners', template);

% 预测
fprintf('进行预测...\n');
y_pred_orig = predict(svm_orig, X_test_orig);
y_pred_sel = predict(svm_sel, X_test_sel);

% 计算性能指标
accuracy_orig = sum(y_pred_orig == y_test) / length(y_test);
accuracy_sel = sum(y_pred_sel == y_test) / length(y_test);

% 混淆矩阵
C_orig = confusionmat(y_test, y_pred_orig);
C_sel = confusionmat(y_test, y_pred_sel);

% 各类别精度
class_acc_orig = diag(C_orig) ./ sum(C_orig, 2);
class_acc_sel = diag(C_sel) ./ sum(C_sel, 2);

% 保存结果
performance = struct();
performance.accuracy_orig = accuracy_orig;
performance.accuracy_sel = accuracy_sel;
performance.accuracy_ratio = accuracy_sel / accuracy_orig;
performance.class_acc_orig = class_acc_orig;
performance.class_acc_sel = class_acc_sel;
performance.confusion_orig = C_orig;
performance.confusion_sel = C_sel;

% 打印结果
fprintf('\n=== 分类性能评估 ===\n');
fprintf('原始数据精度: %.4f\n', accuracy_orig);
fprintf('选择数据精度: %.4f\n', accuracy_sel);
fprintf('精度比值: %.4f\n', performance.accuracy_ratio);
fprintf('波段减少: %.1f%%\n', (1 - L_sel/L_orig)*100);
fprintf('时间节省: %.1f%%\n', (1 - L_sel/L_orig)*100);
fprintf('=====================\n');

% 绘制混淆矩阵
figure('Position', [100, 100, 1200, 500]);

subplot(1, 2, 1);
imagesc(C_orig);
colorbar;
xlabel('预测类别');
ylabel('真实类别');
title('原始数据混淆矩阵');
colormap('hot');
axis square;

subplot(1, 2, 2);
imagesc(C_sel);
colorbar;
xlabel('预测类别');
ylabel('真实类别');
title('选择数据混淆矩阵');
colormap('hot');
axis square;

sgtitle('分类性能对比', 'FontSize', 16, 'FontWeight', 'bold');
end

七、使用示例脚本

matlab 复制代码
%% 示例脚本:完整工作流程
clear; clc; close all;

% 添加路径
addpath(genpath(pwd));

%% 1. 加载数据
fprintf('=== 示例:高光谱波段选择 ===\n\n');

% 如果使用真实数据,取消注释以下行
% load('indian_pines.mat');
% hsi_cube = indian_pines;

% 生成模拟数据
fprintf('1. 生成模拟高光谱数据...\n');
hsi_cube = generate_simulated_hsi_data();
[M, N, L] = size(hsi_cube);
fprintf('   数据尺寸: %d x %d x %d\n', M, N, L);

%% 2. 数据预处理
fprintf('2. 数据预处理...\n');

% 去除噪声波段
hsi_cube = hsi_cube(:,:,10:end-10);
[M, N, L] = size(hsi_cube);
fprintf('   预处理后尺寸: %d x %d x %d\n', M, N, L);

% 归一化
for i = 1:L
    band = hsi_cube(:,:,i);
    band = (band - mean(band(:))) / std(band(:));
    hsi_cube(:,:,i) = band;
end

%% 3. 自适应参数计算
fprintf('3. 计算自适应参数...\n');
alpha = compute_adaptive_alpha(hsi_cube);

%% 4. 波段选择
fprintf('4. 执行波段选择...\n');
num_bands = 20;
method = 'hybrid';  % 尝试 'greedy', 'clustering', 'ranking'

params = struct();
params.alpha = alpha;
params.contrast_method = 'combined';
params.verbose = true;

selected_bands = band_selection_main(hsi_cube, num_bands, method, params);

%% 5. 提取选择的波段
fprintf('5. 提取选择的波段...\n');
selected_data = hsi_cube(:,:,selected_bands);
fprintf('   选择后数据尺寸: %d x %d x %d\n', ...
        size(selected_data,1), size(selected_data,2), size(selected_data,3));
fprintf('   数据压缩率: %.1f%%\n', (1 - num_bands/L)*100);

%% 6. 保存结果
fprintf('6. 保存结果...\n');
save('band_selection_results.mat', 'selected_bands', 'selected_data', ...
     'hsi_cube', 'params', '-v7.3');
fprintf('   结果已保存到 band_selection_results.mat\n');

%% 7. 可视化
fprintf('7. 生成可视化...\n');
contrast_scores = compute_contrast_scores(hsi_cube, 'combined');
corr_matrix = compute_correlation_matrix(hsi_cube);
visualize_band_selection(hsi_cube, selected_bands, contrast_scores, corr_matrix);

%% 8. 性能比较
fprintf('8. 比较不同方法...\n');
num_bands_list = [5, 10, 15, 20, 25, 30];
compare_methods(hsi_cube, num_bands_list);

fprintf('\n=== 示例完成 ===\n');

八、MATLAB工具箱需求

matlab 复制代码
%% 检查所需工具箱
function check_toolboxes()
% 检查所需工具箱是否安装

required_toolboxes = {
    'Image Processing Toolbox',      % 图像处理
    'Statistics and Machine Learning Toolbox',  % 统计分析
    'Deep Learning Toolbox',         % 深度学习(可选)
    'Parallel Computing Toolbox'     % 并行计算(可选)
};

installed_toolboxes = ver;
installed_names = {installed_toolboxes.Name};

fprintf('=== 工具箱检查 ===\n');

all_installed = true;
for i = 1:length(required_toolboxes)
    if ismember(required_toolboxes{i}, installed_names)
        fprintf('✓ %s\n', required_toolboxes{i});
    else
        fprintf('✗ %s (未安装)\n', required_toolboxes{i});
        all_installed = false;
    end
end

if all_installed
    fprintf('\n所有必需工具箱已安装。\n');
else
    fprintf('\n警告:部分工具箱未安装,某些功能可能无法使用。\n');
end
fprintf('================\n\n');
end

九、优化建议

1、内存优化版本

matlab 复制代码
%% 内存优化版本
function selected_bands = band_selection_memory_efficient(hsi_cube, num_bands)
% 内存优化的波段选择算法
% 适用于大尺寸高光谱数据

[M, N, L] = size(hsi_cube);
block_size = 1000;  % 每次处理的像素块大小
num_blocks = ceil(M*N / block_size);

fprintf('内存优化处理: 分%d块处理\n', num_blocks);

% 分块计算统计量
means = zeros(L, 1);
stds = zeros(L, 1);
maxs = zeros(L, 1);
mins = zeros(L, 1);

for b = 1:num_blocks
    start_idx = (b-1) * block_size + 1;
    end_idx = min(b * block_size, M*N);
    
    % 提取当前块
    data_block = reshape(hsi_cube, M*N, L);
    data_block = data_block(start_idx:end_idx, :);
    
    % 累加统计量
    means = means + sum(data_block, 1)';
    stds = stds + sum(data_block.^2, 1)';
    maxs = max(maxs, max(data_block, [], 1)');
    mins = min(mins, min(data_block, [], 1)');
end

% 计算最终统计量
means = means / (M*N);
stds = sqrt(stds/(M*N) - means.^2);

% 使用简化特征进行聚类
features = [means, stds, maxs, mins];
features_norm = zscore(features);

% 聚类选择
[idx, ~] = kmeans(features_norm, num_bands, 'Replicates', 3);

selected_bands = [];
for c = 1:num_bands
    cluster_bands = find(idx == c);
    if ~isempty(cluster_bands)
        % 选择标准差最大的波段
        [~, max_idx] = max(stds(cluster_bands));
        selected_bands = [selected_bands; cluster_bands(max_idx)];
    end
end

selected_bands = sort(selected_bands);
end

2、GPU加速版本

matlab 复制代码
%% GPU加速版本
function selected_bands = band_selection_gpu(hsi_cube, num_bands)
% 使用GPU加速的波段选择算法

% 检查GPU可用性
if gpuDeviceCount == 0
    warning('未检测到GPU,使用CPU版本');
    selected_bands = band_selection_main(hsi_cube, num_bands, 'greedy');
    return;
end

fprintf('使用GPU加速...\n');

% 将数据传输到GPU
hsi_gpu = gpuArray(hsi_cube);
[M, N, L] = size(hsi_gpu);

% GPU计算对比度
contrast_scores = zeros(L, 1, 'gpuArray');
for i = 1:L
    band = hsi_gpu(:,:,i);
    contrast_scores(i) = std(band(:));
end

% GPU计算相关性矩阵
data_gpu = reshape(hsi_gpu, M*N, L);
corr_matrix_gpu = corrcoef(data_gpu);

% 传输回CPU
contrast_scores = gather(contrast_scores);
corr_matrix = gather(corr_matrix_gpu);

% 贪婪选择
selected_bands = greedy_selection(contrast_scores, corr_matrix, num_bands, 0.7);
end
相关推荐
嘿嘿嘿x31 小时前
Linux-实践
linux·运维·算法
czt_java2 小时前
线程安全问题
java·开发语言·jvm
techdashen2 小时前
Rust 模块和文件不是一回事:一次讲清 `mod`、`use`、`pub use`
开发语言·后端·rust
Wy_编程2 小时前
go中的协程Goroutine
开发语言·golang
Godspeed Zhao2 小时前
从零开始学AI14——最大似然估计与对数损失函数
算法·逻辑回归·最大似然
basketball6162 小时前
C++ 命名空间知识点总结:从入门到合理设计
开发语言·c++
WL_Aurora2 小时前
Java多线程详解(一)
java·开发语言
流年如夢2 小时前
排序算法详解
数据结构·算法·排序算法