使用归一化互相关性配准图像
R2026b此示例说明如何使用归一化互相关性确定对齐两个图像所需的平移。
读取图像
读取并显示两个图像。对于此示例,图像大小不同。
onion = imread("onion.png");
imshow(onion)
peppers = imread("peppers.png");
imshow(peppers)
选择每个图像的子区域
选择每个图像的子区域,使互相关矩阵的峰值易于识别。选择相似区域很重要。图像 sub_onion 将作为模板,且它必须小于图像 sub_peppers。您可以使用以下命令获取这些子区域。
rect_onion = [111 33 65 58]; rect_peppers = [163 47 143 151]; sub_onion = imcrop(onion,rect_onion); sub_peppers = imcrop(peppers,rect_peppers);
如果您要以交互方式选择子区域,则可以使用以下命令。
[sub_onion,rect_onion] = imcrop(onion); % Choose the pepper below the onion [sub_peppers,rect_peppers] = imcrop(peppers); % Choose the whole onion
显示子区域。
imshow(sub_onion)

imshow(sub_peppers)

计算归一化互相关性并找到峰值的坐标
计算归一化互相关性并将其显示为曲面图。互相关性矩阵的峰值出现在子图像最相关的位置。normxcorr2 仅适用于灰度图像,因此向其传递每个子图像的第一个通道。
c = normxcorr2(sub_onion(:,:,1),sub_peppers(:,:,1));
surf(c)
shading flat
找到峰值的坐标。
[max_c,imax] = max(abs(c(:))); [ypeak,xpeak] = ind2sub(size(c),imax(1));
找到图像之间的总偏移
图像之间的总偏移或平移取决于互相关性矩阵中峰值的位置,以及子图像的大小和位置。
% Offset found by correlation corr_offset = [(xpeak-size(sub_onion,2)) (ypeak-size(sub_onion,1))]; % Relative offset of position of subimages rect_offset = [(rect_peppers(1)-rect_onion(1)) (rect_peppers(2)-rect_onion(2))]; % Total offset offset = corr_offset + rect_offset; xoffset = offset(1); yoffset = offset(2);
配准图像并验证结果
确定 onion 落在 peppers 内的位置。
xbegin = round(xoffset + 1); xend = round(xoffset + size(onion,2)); ybegin = round(yoffset + 1); yend = round(yoffset + size(onion,1)); % Extract region from peppers and compare to onion extracted_onion = peppers(ybegin:yend,xbegin:xend,:); if isequal(onion,extracted_onion) disp("onion.png was extracted from peppers.png") end
onion.png was extracted from peppers.png
使用上述确定的偏移填充 onion 图像以叠加在 peppers 上。
recovered_onion = uint8(zeros(size(peppers))); recovered_onion(ybegin:yend,xbegin:xend,:) = onion; imshow(recovered_onion)

使用 alpha 混合将 peppers 图像的一个平面与 recovered_onion 图像一起显示,以确认配准。
imshowpair(peppers(:,:,1),recovered_onion,"blend")