图像融合与拼接:完整MATLAB工具箱

图像融合与拼接MATLAB程序集,包含多种经典算法和实用功能。

图像融合与拼接:完整MATLAB工具箱

技术路线概览

图像融合与拼接包含多个技术层次,下图展示了完整的处理流程和算法选择:
图像拼接
特征点检测

SIFT/SURF
特征匹配与筛选
变换矩阵估计
图像变换与融合
图像融合
多分辨率融合

小波变换
像素级融合
特征级融合
决策级融合
输入图像
选择处理类型
融合结果评估
拼接质量分析
输出融合图像
输出拼接全景图

完整MATLAB实现

1. 主程序框架

matlab 复制代码
%% 图像融合与拼接工具箱 - 主程序
clear; close all; clc;
addpath(genpath(pwd));
fprintf('========== MATLAB图像融合与拼接工具箱 ==========\n');

%% 1. 选择处理模式
mode = input('请选择处理模式:\n1. 图像融合\n2. 图像拼接\n3. 两者都执行\n选择: ');

%% 2. 载入图像
fprintf('载入图像...\n');
image_paths = {'image1.jpg', 'image2.jpg', 'image3.jpg'};
images = cell(1, length(image_paths));
valid_images = 0;

for i = 1:length(image_paths)
    if exist(image_paths{i}, 'file')
        img = imread(image_paths{i});
        images{i} = img;
        valid_images = valid_images + 1;
        fprintf('  已载入: %s (%dx%dx%d)\n', image_paths{i}, size(img,1), size(img,2), size(img,3));
    else
        % 生成示例图像(如果文件不存在)
        fprintf('  %s 不存在,生成示例图像...\n', image_paths{i});
        if i == 1
            images{i} = create_sample_image('pattern1', 512, 512);
        elseif i == 2
            images{i} = create_sample_image('pattern2', 512, 512);
        else
            images{i} = create_sample_image('gradient', 512, 512);
        end
        valid_images = valid_images + 1;
    end
end

if valid_images < 2
    error('至少需要2张图像进行处理!');
end

%% 3. 图像预处理
fprintf('图像预处理...\n');
processed_images = cell(1, valid_images);
for i = 1:valid_images
    % 统一尺寸(如果需要)
    if i > 1 && ~isequal(size(images{i}), size(images{1}))
        fprintf('  调整图像%d尺寸到%d×%d\n', i, size(images{1},1), size(images{1},2));
        images{i} = imresize(images{i}, [size(images{1},1), size(images{1},2)]);
    end
    
    % 转换为双精度用于计算
    processed_images{i} = im2double(images{i});
end

%% 4. 执行选择的功能
if mode == 1 || mode == 3
    %% 图像融合
    fprintf('\n========== 图像融合 ==========\n');
    
    % 选择融合方法
    fusion_methods = {
        '小波变换融合', '金字塔融合', 'PCA融合', 
        'IHS融合', 'Brovey融合', '梯度域融合'
    };
    
    fprintf('可用的融合方法:\n');
    for i = 1:length(fusion_methods)
        fprintf('  %d. %s\n', i, fusion_methods{i});
    end
    
    method_choice = input('选择融合方法 (1-6): ');
    if method_choice < 1 || method_choice > length(fusion_methods)
        method_choice = 1; % 默认小波融合
    end
    
    fprintf('使用 %s 方法进行图像融合...\n', fusion_methods{method_choice});
    
    % 执行融合
    switch method_choice
        case 1
            fused_image = wavelet_fusion(processed_images{1}, processed_images{2});
        case 2
            fused_image = pyramid_fusion(processed_images{1}, processed_images{2});
        case 3
            fused_image = pca_fusion(processed_images{1}, processed_images{2});
        case 4
            fused_image = ihs_fusion(processed_images{1}, processed_images{2});
        case 5
            fused_image = brovey_fusion(processed_images{1}, processed_images{2});
        case 6
            fused_image = gradient_fusion(processed_images{1}, processed_images{2});
    end
    
    % 评估融合结果
    evaluate_fusion(processed_images{1}, processed_images{2}, fused_image, fusion_methods{method_choice});
    
    % 保存结果
    imwrite(fused_image, 'fused_result.jpg');
    fprintf('融合图像已保存为 fused_result.jpg\n');
end

if mode == 2 || mode == 3
    %% 图像拼接
    fprintf('\n========== 图像拼接 ==========\n');
    
    % 选择拼接图像(需要有一定重叠)
    if valid_images >= 2
        fprintf('使用图像1和图像2进行拼接...\n');
        
        % 执行拼接
        [panorama, panorama_info] = image_stitching(images{1}, images{2});
        
        if ~isempty(panorama)
            % 评估拼接结果
            evaluate_stitching(images{1}, images{2}, panorama, panorama_info);
            
            % 保存结果
            imwrite(panorama, 'panorama_result.jpg');
            fprintf('拼接图像已保存为 panorama_result.jpg\n');
            
            % 如果有第三张图像,尝试多图像拼接
            if valid_images >= 3
                fprintf('尝试三图像拼接...\n');
                [multi_panorama, multi_info] = multi_image_stitching({images{1}, images{2}, images{3}});
                
                if ~isempty(multi_panorama)
                    imwrite(multi_panorama, 'multi_panorama_result.jpg');
                    fprintf('多图像拼接结果已保存为 multi_panorama_result.jpg\n');
                end
            end
        else
            fprintf('图像拼接失败!\n');
        end
    end
end

%% 5. 高级功能演示
fprintf('\n========== 高级功能演示 ==========\n');
demo_advanced_features = input('是否演示高级功能? (1=是, 0=否): ');

if demo_advanced_features
    % 演示实时融合调节
    interactive_fusion_demo(processed_images{1}, processed_images{2});
    
    % 演示不同参数的影响
    parameter_sensitivity_analysis(processed_images{1}, processed_images{2});
    
    % 批量处理演示
    batch_processing_demo();
end

fprintf('\n程序执行完成!\n');

2. 图像融合核心算法

2.1 小波变换融合
matlab 复制代码
function fused_img = wavelet_fusion(img1, img2)
% 基于小波变换的图像融合
% 输入: img1, img2 - 双精度图像矩阵
% 输出: fused_img - 融合后的图像

    fprintf('  执行小波变换融合...\n');
    
    % 确保图像为灰度(如果是彩色,转换为Y通道处理)
    if size(img1, 3) == 3
        fprintf('  检测到彩色图像,转换为YIQ空间处理\n');
        % 转换到YIQ空间
        img1_yiq = rgb2ntsc(img1);
        img2_yiq = rgb2ntsc(img2);
        
        % 分离通道
        Y1 = img1_yiq(:,:,1);
        I1 = img1_yiq(:,:,2);
        Q1 = img1_yiq(:,:,3);
        
        Y2 = img2_yiq(:,:,1);
        I2 = img2_yiq(:,:,2);
        Q2 = img2_yiq(:,:,3);
        
        % 对亮度通道进行小波融合
        Y_fused = wavelet_fusion_gray(Y1, Y2);
        
        % 简单平均色度通道
        I_fused = (I1 + I2) / 2;
        Q_fused = (Q1 + Q2) / 2;
        
        % 合并通道
        fused_yiq = cat(3, Y_fused, I_fused, Q_fused);
        fused_img = ntsc2rgb(fused_yiq);
        
    else
        % 灰度图像直接处理
        fused_img = wavelet_fusion_gray(img1, img2);
    end
    
    fprintf('  小波融合完成\n');
end

function fused_gray = wavelet_fusion_gray(img1, img2)
% 灰度图像的小波融合
    
    % 参数设置
    wavelet_name = 'db4';  % 小波基
    level = 3;             % 分解层数
    
    % 小波分解
    [C1, S1] = wavedec2(img1, level, wavelet_name);
    [C2, S2] = wavedec2(img2, level, wavelet_name);
    
    % 初始化融合系数
    C_fused = zeros(size(C1));
    
    % 融合低频系数(平均)
    approx_len = S1(1,1) * S1(1,2);
    C_fused(1:approx_len) = (C1(1:approx_len) + C2(1:approx_len)) / 2;
    
    % 融合高频系数(取绝对值大的)
    idx = approx_len + 1;
    for l = 1:level
        % 当前层的高频系数数量
        detail_size = S1(l+1,1) * S1(l+1,2);
        
        for k = 1:3  % 三个方向: 水平、垂直、对角线
            range = idx:idx+detail_size-1;
            
            % 取绝对值大的系数
            abs1 = abs(C1(range));
            abs2 = abs(C2(range));
            
            % 选择机制
            selection_mask = abs1 >= abs2;
            C_fused(range) = selection_mask .* C1(range) + ...
                             (~selection_mask) .* C2(range);
            
            idx = idx + detail_size;
        end
    end
    
    % 小波重构
    fused_gray = waverec2(C_fused, S1, wavelet_name);
    
    % 确保值在[0,1]范围内
    fused_gray = min(max(fused_gray, 0), 1);
end
2.2 拉普拉斯金字塔融合
matlab 复制代码
function fused_img = pyramid_fusion(img1, img2)
% 基于拉普拉斯金字塔的图像融合
    
    fprintf('  执行金字塔融合...\n');
    
    if size(img1, 3) == 3
        % 彩色图像 - 分通道处理
        fused_img = zeros(size(img1));
        for ch = 1:3
            fused_img(:,:,ch) = pyramid_fusion_gray(img1(:,:,ch), img2(:,:,ch));
        end
    else
        fused_img = pyramid_fusion_gray(img1, img2);
    end
    
    fprintf('  金字塔融合完成\n');
end

function fused_gray = pyramid_fusion_gray(img1, img2)
% 灰度图像的金字塔融合
    
    % 参数
    levels = 4;  % 金字塔层数
    
    % 构建高斯金字塔
    G1 = cell(1, levels);
    G2 = cell(1, levels);
    
    G1{1} = img1;
    G2{1} = img2;
    
    for i = 2:levels
        G1{i} = impyramid(G1{i-1}, 'reduce');
        G2{i} = impyramid(G2{i-1}, 'reduce');
    end
    
    % 构建拉普拉斯金字塔
    L1 = cell(1, levels);
    L2 = cell(1, levels);
    
    for i = 1:levels-1
        expanded = impyramid(G1{i+1}, 'expand');
        % 调整尺寸
        if ~isequal(size(expanded), size(G1{i}))
            expanded = imresize(expanded, size(G1{i}));
        end
        L1{i} = G1{i} - expanded;
        
        expanded = impyramid(G2{i+1}, 'expand');
        if ~isequal(size(expanded), size(G2{i}))
            expanded = imresize(expanded, size(G2{i}));
        end
        L2{i} = G2{i} - expanded;
    end
    L1{levels} = G1{levels};
    L2{levels} = G2{levels};
    
    % 融合拉普拉斯金字塔(取绝对值大的)
    L_fused = cell(1, levels);
    for i = 1:levels
        if i == levels
            % 顶层取平均
            L_fused{i} = (L1{i} + L2{i}) / 2;
        else
            % 其他层取绝对值大的
            mask = abs(L1{i}) >= abs(L2{i});
            L_fused{i} = mask .* L1{i} + (~mask) .* L2{i};
        end
    end
    
    % 从融合的金字塔重构图像
    fused_gray = L_fused{levels};
    for i = levels-1:-1:1
        expanded = impyramid(fused_gray, 'expand');
        if ~isequal(size(expanded), size(L_fused{i}))
            expanded = imresize(expanded, size(L_fused{i}));
        end
        fused_gray = expanded + L_fused{i};
    end
    
    % 确保值在[0,1]范围内
    fused_gray = min(max(fused_gray, 0), 1);
end
2.3 PCA融合
matlab 复制代码
function fused_img = pca_fusion(img1, img2)
% 基于主成分分析(PCA)的图像融合
    
    fprintf('  执行PCA融合...\n');
    
    if size(img1, 3) == 3
        % 彩色图像 - 转换为灰度处理
        fprintf('  彩色图像转换为灰度进行处理\n');
        img1_gray = rgb2gray(img1);
        img2_gray = rgb2gray(img2);
        
        % PCA融合灰度图像
        fused_gray = pca_fusion_gray(img1_gray, img2_gray);
        
        % 将融合结果应用到彩色图像(保持原始颜色)
        fused_img = zeros(size(img1));
        for ch = 1:3
            % 使用融合的灰度图像作为权重
            weight = fused_gray ./ (img1_gray + img2_gray + eps);
            fused_img(:,:,ch) = weight .* img1(:,:,ch) + (1-weight) .* img2(:,:,ch);
        end
    else
        fused_img = pca_fusion_gray(img1, img2);
    end
    
    fprintf('  PCA融合完成\n');
end

function fused_gray = pca_fusion_gray(img1, img2)
% 灰度图像的PCA融合
    
    % 将图像展平为向量
    [h, w] = size(img1);
    vec1 = img1(:);
    vec2 = img2(:);
    
    % 构建数据矩阵
    X = [vec1, vec2];
    
    % 计算协方差矩阵
    C = cov(X);
    
    % 计算特征值和特征向量
    [V, D] = eig(C);
    
    % 找到最大特征值对应的特征向量
    [~, idx] = max(diag(D));
    principal_vector = V(:, idx);
    
    % 归一化特征向量作为权重
    weights = abs(principal_vector) / sum(abs(principal_vector));
    
    % 加权融合
    fused_vec = weights(1) * vec1 + weights(2) * vec2;
    
    % 重塑为图像
    fused_gray = reshape(fused_vec, h, w);
    
    % 确保值在[0,1]范围内
    fused_gray = min(max(fused_gray, 0), 1);
end

3. 图像拼接核心算法

3.1 特征点检测与匹配
matlab 复制代码
function [matched_points1, matched_points2] = feature_matching(img1, img2)
% 特征点检测与匹配
    
    fprintf('  检测特征点...\n');
    
    % 转换为灰度图像
    if size(img1, 3) == 3
        gray1 = rgb2gray(img1);
        gray2 = rgb2gray(img2);
    else
        gray1 = img1;
        gray2 = img2;
    end
    
    % 使用SURF特征(需要计算机视觉工具箱)
    try
        % 检测特征点
        points1 = detectSURFFeatures(gray1);
        points2 = detectSURFFeatures(gray2);
        
        % 提取特征描述符
        [features1, valid_points1] = extractFeatures(gray1, points1);
        [features2, valid_points2] = extractFeatures(gray2, points2);
        
        % 特征匹配
        index_pairs = matchFeatures(features1, features2, 'MaxRatio', 0.6, 'Unique', true);
        
        % 获取匹配点
        matched_points1 = valid_points1(index_pairs(:, 1));
        matched_points2 = valid_points2(index_pairs(:, 2));
        
        fprintf('  找到 %d 对匹配点\n', length(matched_points1));
        
    catch
        % 如果SURF不可用,使用Harris角点
        fprintf('  SURF特征不可用,使用Harris角点\n');
        [matched_points1, matched_points2] = harris_feature_matching(gray1, gray2);
    end
    
    % 可视化匹配结果
    visualize_matches(img1, img2, matched_points1, matched_points2);
end

function [points1, points2] = harris_feature_matching(img1, img2)
% 使用Harris角点进行特征匹配
    
    % 检测Harris角点
    corners1 = detectHarrisFeatures(img1);
    corners2 = detectHarrisFeatures(img2);
    
    % 提取特征(使用HOG或简单的patch)
    [features1, valid_corners1] = extractFeatures(img1, corners1, 'Method', 'Block', 'BlockSize', 7);
    [features2, valid_corners2] = extractFeatures(img2, corners2, 'Method', 'Block', 'BlockSize', 7);
    
    % 匹配特征
    index_pairs = matchFeatures(features1, features2, 'MaxRatio', 0.7);
    
    points1 = valid_corners1(index_pairs(:, 1));
    points2 = valid_corners2(index_pairs(:, 2));
    
    fprintf('  Harris角点匹配找到 %d 对匹配点\n', length(points1));
end
3.2 RANSAC估计单应性矩阵
matlab 复制代码
function [H, inlier_idx] = estimate_homography_ransac(points1, points2, max_iterations, threshold)
% 使用RANSAC算法估计单应性矩阵
    
    fprintf('  使用RANSAC估计单应性矩阵...\n');
    
    if nargin < 3
        max_iterations = 1000;
    end
    if nargin < 4
        threshold = 2.0;  % 像素误差阈值
    end
    
    % 获取点坐标
    pts1 = points1.Location;
    pts2 = points2.Location;
    
    num_points = size(pts1, 1);
    if num_points < 4
        error('至少需要4对匹配点!');
    end
    
    best_H = [];
    best_inliers = [];
    max_inliers = 0;
    
    for iter = 1:max_iterations
        % 随机选择4对点
        rand_idx = randperm(num_points, 4);
        
        % 使用这4对点计算单应性矩阵
        try
            H_temp = fitgeotrans(pts1(rand_idx, :), pts2(rand_idx, :), 'projective');
            H_matrix = H_temp.T';
        catch
            continue;
        end
        
        % 计算所有点的投影误差
        pts1_hom = [pts1, ones(num_points, 1)];
        pts2_proj_hom = (H_matrix * pts1_hom')';
        pts2_proj = pts2_proj_hom(:, 1:2) ./ pts2_proj_hom(:, 3);
        
        errors = sqrt(sum((pts2 - pts2_proj).^2, 2));
        
        % 统计内点
        inliers = errors < threshold;
        num_inliers = sum(inliers);
        
        % 更新最佳模型
        if num_inliers > max_inliers
            max_inliers = num_inliers;
            best_inliers = inliers;
            best_H = H_temp;
        end
        
        % 提前终止条件
        if num_inliers > num_points * 0.8
            break;
        end
    end
    
    % 使用所有内点重新计算单应性矩阵
    if ~isempty(best_H) && sum(best_inliers) >= 4
        H = fitgeotrans(pts1(best_inliers, :), pts2(best_inliers, :), 'projective');
        inlier_idx = find(best_inliers);
        fprintf('  RANSAC完成: %d次迭代, 找到%d个内点 (%.1f%%)\n', ...
                iter, sum(best_inliers), sum(best_inliers)/num_points*100);
    else
        H = [];
        inlier_idx = [];
        fprintf('  RANSAC失败: 未找到足够的匹配点\n');
    end
end
3.3 图像拼接主函数
matlab 复制代码
function [panorama, panorama_info] = image_stitching(img1, img2)
% 图像拼接主函数
    
    fprintf('开始图像拼接...\n');
    
    % 特征匹配
    [matched_points1, matched_points2] = feature_matching(img1, img2);
    
    if length(matched_points1) < 4
        fprintf('匹配点不足,无法进行拼接\n');
        panorama = [];
        panorama_info = [];
        return;
    end
    
    % 估计单应性矩阵
    [H, inlier_idx] = estimate_homography_ransac(matched_points1, matched_points2);
    
    if isempty(H)
        fprintf('单应性矩阵估计失败\n');
        panorama = [];
        panorama_info = [];
        return;
    end
    
    % 计算拼接画布大小
    [h1, w1, ~] = size(img1);
    [h2, w2, ~] = size(img2);
    
    % 计算图像2在图像1坐标系中的边界
    corners = [1, 1; w2, 1; w2, h2; 1, h2];
    corners_transformed = transformPointsForward(H, corners);
    
    % 计算画布边界
    x_min = min([1, corners_transformed(:,1)']);
    x_max = max([w1, corners_transformed(:,1)']);
    y_min = min([1, corners_transformed(:,2)']);
    y_max = max([h1, corners_transformed(:,2)']);
    
    % 创建画布
    canvas_width = ceil(x_max - x_min);
    canvas_height = ceil(y_max - y_min);
    
    % 创建变换
    offset_x = -x_min + 1;
    offset_y = -y_min + 1;
    
    tform_translate = affine2d([1 0 0; 0 1 0; offset_x offset_y 1]);
    
    % 变换图像1到画布
    panorama_view = imref2d([canvas_height, canvas_width]);
    [warped_img1, ~] = imwarp(img1, tform_translate, 'OutputView', panorama_view);
    
    % 变换图像2到画布(通过单应性矩阵)
    H_composite = projective2d(H.T * tform_translate.T);
    [warped_img2, ~] = imwarp(img2, H_composite, 'OutputView', panorama_view);
    
    % 融合两幅图像
    panorama = blend_images(warped_img1, warped_img2);
    
    % 保存拼接信息
    panorama_info.H = H;
    panorama_info.canvas_size = [canvas_height, canvas_width];
    panorama_info.offset = [offset_x, offset_y];
    panorama_info.matched_points = length(inlier_idx);
    
    fprintf('图像拼接完成,画布尺寸: %dx%d\n', canvas_height, canvas_width);
end

function panorama = blend_images(img1, img2)
% 融合两幅重叠图像
    
    % 创建权重掩码
    mask1 = any(img1 > 0, 3);
    mask2 = any(img2 > 0, 3);
    
    % 重叠区域
    overlap = mask1 & mask2;
    
    % 计算距离变换作为权重
    if any(overlap(:))
        % 对于重叠区域,使用渐变权重
        [rows, cols] = find(overlap);
        if ~isempty(rows)
            % 计算到各自图像边界的距离
            [dist1, ~] = bwdist(mask1 & ~overlap);
            [dist2, ~] = bwdist(mask2 & ~overlap);
            
            % 归一化权重
            weights1 = dist1 ./ (dist1 + dist2 + eps);
            weights2 = dist2 ./ (dist1 + dist2 + eps);
            
            % 创建权重矩阵
            weight_mask1 = zeros(size(mask1));
            weight_mask2 = zeros(size(mask2));
            for i = 1:length(rows)
                weight_mask1(rows(i), cols(i)) = weights1(rows(i), cols(i));
                weight_mask2(rows(i), cols(i)) = weights2(rows(i), cols(i));
            end
        else
            weight_mask1 = mask1;
            weight_mask2 = mask2;
        end
    else
        weight_mask1 = mask1;
        weight_mask2 = mask2;
    end
    
    % 应用权重融合
    panorama = zeros(size(img1));
    for ch = 1:size(img1, 3)
        ch1 = double(img1(:,:,ch));
        ch2 = double(img2(:,:,ch));
        
        % 加权平均
        blended = weight_mask1 .* ch1 + weight_mask2 .* ch2;
        
        % 处理非重叠区域
        blended(~mask1 & mask2) = ch2(~mask1 & mask2);
        blended(mask1 & ~mask2) = ch1(mask1 & ~mask2);
        
        panorama(:,:,ch) = blended;
    end
    
    % 转换为uint8
    panorama = uint8(panorama);
end

4. 评估与可视化函数

4.1 融合质量评估
matlab 复制代码
function evaluate_fusion(img1, img2, fused_img, method_name)
% 评估图像融合质量
    
    fprintf('\n评估融合质量 (%s):\n', method_name);
    
    % 转换为灰度用于某些指标计算
    if size(img1, 3) == 3
        gray1 = rgb2gray(img1);
        gray2 = rgb2gray(img2);
        gray_fused = rgb2gray(fused_img);
    else
        gray1 = img1;
        gray2 = img2;
        gray_fused = fused_img;
    end
    
    % 1. 信息熵(越高越好)
    entropy_val = entropy(gray_fused);
    fprintf('  信息熵: %.4f\n', entropy_val);
    
    % 2. 标准差(衡量对比度)
    std_val = std(gray_fused(:));
    fprintf('  标准差: %.4f\n', std_val);
    
    % 3. 平均梯度(衡量清晰度)
    [Gx, Gy] = gradient(double(gray_fused));
    avg_gradient = mean(sqrt(Gx(:).^2 + Gy(:).^2));
    fprintf('  平均梯度: %.4f\n', avg_gradient);
    
    % 4. 互信息(衡量从源图像保留的信息)
    mi1 = mutual_information(gray1, gray_fused);
    mi2 = mutual_information(gray2, gray_fused);
    fprintf('  互信息 (与图像1): %.4f\n', mi1);
    fprintf('  互信息 (与图像2): %.4f\n', mi2);
    
    % 5. 结构相似性指数
    ssim1 = ssim(gray_fused, gray1);
    ssim2 = ssim(gray_fused, gray2);
    fprintf('  SSIM (与图像1): %.4f\n', ssim1);
    fprintf('  SSIM (与图像2): %.4f\n', ssim2);
    
    % 6. 峰值信噪比
    psnr1 = psnr(gray_fused, gray1);
    psnr2 = psnr(gray_fused, gray2);
    fprintf('  PSNR (与图像1): %.2f dB\n', psnr1);
    fprintf('  PSNR (与图像2): %.2f dB\n', psnr2);
    
    % 可视化结果
    figure('Position', [100, 100, 1400, 500]);
    
    subplot(1, 4, 1);
    if size(img1, 3) == 3
        imshow(img1);
    else
        imshow(img1, []);
    end
    title('源图像 1');
    
    subplot(1, 4, 2);
    if size(img2, 3) == 3
        imshow(img2);
    else
        imshow(img2, []);
    end
    title('源图像 2');
    
    subplot(1, 4, 3);
    if size(fused_img, 3) == 3
        imshow(fused_img);
    else
        imshow(fused_img, []);
    end
    title(sprintf('融合图像 (%s)', method_name));
    
    subplot(1, 4, 4);
    % 显示差异
    diff_img = abs(double(gray_fused) - double(gray1)) + ...
               abs(double(gray_fused) - double(gray2));
    imagesc(diff_img);
    colorbar;
    colormap('hot');
    title('融合差异图');
    axis image;
    
    sgtitle(sprintf('图像融合结果评估 - %s', method_name), 'FontSize', 14, 'FontWeight', 'bold');
end

function mi = mutual_information(img1, img2)
% 计算两幅图像的互信息
    % 联合直方图
    joint_hist = histcounts2(img1(:), img2(:), 256, 'Normalization', 'probability');
    
    % 边缘分布
    marginal1 = sum(joint_hist, 2);
    marginal2 = sum(joint_hist, 1);
    
    % 计算互信息
    mi = 0;
    for i = 1:256
        for j = 1:256
            p_joint = joint_hist(i, j);
            if p_joint > 0
                p_product = marginal1(i) * marginal2(j);
                mi = mi + p_joint * log2(p_joint / p_product + eps);
            end
        end
    end
end

5. 实用工具函数

5.1 创建示例图像
matlab 复制代码
function img = create_sample_image(type, height, width)
% 创建示例图像
    
    switch type
        case 'pattern1'
            % 条纹图案
            [X, Y] = meshgrid(1:width, 1:height);
            img = uint8(128 + 127 * sin(X/20) .* cos(Y/30));
            
        case 'pattern2'
            % 同心圆
            [X, Y] = meshgrid(1:width, 1:height);
            center_x = width/2;
            center_y = height/2;
            radius = sqrt((X-center_x).^2 + (Y-center_y).^2);
            img = uint8(128 + 127 * sin(radius/20));
            
        case 'gradient'
            % 渐变图像
            [X, ~] = meshgrid(1:width, 1:height);
            img = uint8(255 * X / width);
            
        case 'checkerboard'
            % 棋盘格
            tile_size = 32;
            img = uint8(255 * checkerboard(tile_size, ceil(height/(2*tile_size)), ceil(width/(2*tile_size))));
            
        case 'random'
            % 随机纹理
            img = uint8(255 * rand(height, width));
    end
    
    % 如果是灰度,转换为RGB
    if length(size(img)) == 2
        img = cat(3, img, img, img);
    end
end

6. 扩展功能演示

6.1 交互式融合演示
matlab 复制代码
function interactive_fusion_demo(img1, img2)
% 交互式图像融合演示
    
    fprintf('启动交互式融合演示...\n');
    
    % 创建UI界面
    fig = figure('Position', [100, 100, 1200, 600], 'Name', '交互式图像融合演示');
    
    % 创建UI控件
    uicontrol('Style', 'text', 'Position', [20, 550, 200, 30], ...
              'String', '融合方法:', 'FontSize', 12);
    
    method_popup = uicontrol('Style', 'popupmenu', 'Position', [20, 520, 200, 30], ...
                            'String', {'小波变换', '金字塔', 'PCA', '加权平均'}, ...
                            'FontSize', 12, 'Callback', @update_fusion);
    
    uicontrol('Style', 'text', 'Position', [240, 550, 200, 30], ...
              'String', '权重 (图像1):', 'FontSize', 12);
    
    weight_slider = uicontrol('Style', 'slider', 'Position', [240, 520, 200, 30], ...
                             'Min', 0, 'Max', 1, 'Value', 0.5, ...
                             'Callback', @update_fusion);
    
    uicontrol('Style', 'text', 'Position', [460, 550, 100, 30], ...
              'String', '显示差异:', 'FontSize', 12);
    
    show_diff_check = uicontrol('Style', 'checkbox', 'Position', [460, 520, 100, 30], ...
                               'Value', 0, 'Callback', @update_fusion);
    
    % 显示图像
    ax1 = subplot(2, 3, 1);
    imshow(img1);
    title('图像 1');
    
    ax2 = subplot(2, 3, 2);
    imshow(img2);
    title('图像 2');
    
    ax3 = subplot(2, 3, 3);
    fused_img = (img1 + img2) / 2;
    h_fused = imshow(fused_img);
    title('融合图像');
    
    ax4 = subplot(2, 3, [4, 5, 6]);
    diff_img = abs(img1 - img2);
    h_diff = imagesc(diff_img);
    colorbar;
    title('差异图');
    axis image;
    
    % 更新函数
    function update_fusion(~, ~)
        method_idx = method_popup.Value;
        weight = weight_slider.Value;
        
        % 根据选择的方法进行融合
        switch method_idx
            case 1  % 小波变换
                fused = wavelet_fusion_gray(img1, img2);
            case 2  % 金字塔
                fused = pyramid_fusion_gray(img1, img2);
            case 3  % PCA
                fused = pca_fusion_gray(img1, img2);
            case 4  % 加权平均
                fused = weight * img1 + (1-weight) * img2;
        end
        
        % 更新融合图像
        set(h_fused, 'CData', fused);
        
        % 更新差异图
        if show_diff_check.Value
            diff = abs(fused - img1) + abs(fused - img2);
            set(h_diff, 'CData', diff);
            title(ax4, '融合差异图');
        else
            diff = abs(img1 - img2);
            set(h_diff, 'CData', diff);
            title(ax4, '源图像差异图');
        end
        
        % 更新标题
        title(ax3, sprintf('融合图像 (权重: %.2f)', weight));
    end
    
    fprintf('交互式演示已启动。调整参数查看实时效果。\n');
end

参考代码 图像融合,图像拼接及融合的 程序可用于matlab www.3dddown.com/csb/97494.html

使用说明与建议

1. 快速开始

matlab 复制代码
% 最简单的方式 - 直接运行主程序
main_image_fusion_stitching_toolbox

% 或手动调用特定功能
img1 = imread('left.jpg');
img2 = imread('right.jpg');

% 融合
fused = wavelet_fusion(img1, img2);
imshow(fused);

% 拼接
[panorama, info] = image_stitching(img1, img2);
imshow(panorama);

2. 参数调优建议

参数 推荐值 说明
小波分解层数 3-5层 层数越多,融合越平滑但计算量越大
金字塔层数 4-6层 影响融合的尺度范围
RANSAC迭代次数 1000-5000 确保找到足够内点
特征匹配比例 0.6-0.8 控制匹配严格度

3. 常见问题解决

  1. 内存不足:减小图像尺寸或使用分块处理
  2. 拼接错位:增加RANSAC迭代次数或使用更严格的特征匹配
  3. 融合边缘伪影:使用梯度域融合或增加金字塔层数
  4. 颜色不一致:使用颜色校正预处理

4. 扩展功能

  • 实时视频拼接:将代码扩展为处理视频流
  • GPU加速 :使用gpuArray加速计算密集型操作
  • 深度学习融合:集成基于CNN的图像融合方法
  • 3D场景重建:结合多视角图像进行三维重建
相关推荐
春风不语5051 小时前
深入理解主成分分析(PCA)
算法
apollowing1 小时前
启发式算法WebApp实验室:从搜索策略到群体智能的能力进阶(二十二)
算法·启发式算法·web app
晚枫歌F1 小时前
最小堆定时器
数据结构·算法
Lumos_7772 小时前
Linux -- 线程
java·jvm·算法
七颗糖很甜2 小时前
“十五五”气象发展规划:聚焦五大核心任务
大数据·python·算法
科研前沿2 小时前
镜像视界浙江科技有限公司的关键技术突破有哪些?
大数据·人工智能·科技·算法·音视频·空间计算
嫩萝卜头儿3 小时前
2 - 复杂度收尾 + 链表经典OJ
数据结构·算法·链表·复杂度
chaofan9803 小时前
GPT-5.5 深度评测:15项基准测试全优,视觉理解精度跃升 42%
大数据·人工智能·gpt·计算机视觉·api
星马梦缘3 小时前
算法设计与分析 作业二 答案与解析
算法·图论·dfs·bfs·floyd-warshall·bellman_ford·多源最短路