一. 定义
首先看Matlab help 里normxcorr2函数中关于归一化二维互相关矩阵的定义:
核心就是模板template 二维矩阵使用(u,v)的位移和fixed 矩阵做点乘求和.
其中template 比 fixed 要小. 假设template矩阵是m∗n的, fixed矩阵是M∗N的.
二. 计算过程
下面的坐标系都是以matlab的矩阵坐标系来说明的.也就是左上角是坐标原点, 竖直方向往下是x正方向,
水平方向往右是y的正方向.
u=0,v=0时, 两矩阵左上角(1,1)位置对齐.
显然,
1. 当u>0,v>0时, template 相对于fixed 是往右下角移动了. x轴移动了u单位, y轴移动了
2. 当u>0,v<0时, template 相对于fixed 是往左下角移动了. x轴移动了u单位, y轴移动了
3. 当u<0,v<0 时, template 相对于fixed 是往左上角移动了. x轴移动了u单位, y轴移动了
4. 当u<0,v>0 时, template 相对于fixed 是往右上角移动了. x轴移动了u单位, y轴移动了
当然, u,v的取值是有限的, 因为必须要保证template和fixed矩阵是有相交部分的.
否则相关系数都是0. 没有计算意义.
所以,
u的取值是[−(m−1),M−1], 共M+m−1点,
v的取值是[−(n−1),N−1], 共N+n−1点.
所以,
最后的相关系数矩阵是(M+m−1)∗(N+n−1)大小的.
因为matlab是从(1,1)索引开始存储数据的.
所以,
(1,1)索引处, u=−(m−1)=1−m,v=−(n−1)=1−n.
所以,
已知相关系数矩阵索引(i, j), 对应公式中:
通过这个公式, 就可以把mat索引和相关矩阵的偏移量联系起来了.
下面是matlab自带的example:
通过normxcorr2函数求template和fixed的偏移量.
这种方法在图像模板匹配中是常用的方法.
注意: imshow输出的figure坐标是图像坐标, 和mat坐标是不同的.
template = .2*ones(11); % Make light gray plus on dark gray background
template(6,3:9) = .6;
template(3:9,6) = .6;
BW = template > 0.5; % Make white plus on black background
figure, imshow(BW), figure, imshow(template)
% Make new image that offsets the template
offsetTemplate = .2*ones(21);
offset = [3 5]; % Shift by 3 rows, 5 columns
offsetTemplate( (1:size(template,1))+offset(1),...
(1:size(template,2))+offset(2) ) = template;
figure, imshow(offsetTemplate)
% Cross-correlate BW and offsetTemplate to recover offset
cc = normxcorr2(BW,offsetTemplate);
[max_cc, imax] = max(abs(cc(:)));
[ypeak, xpeak] = ind2sub(size(cc),imax(1));
corr_offset = [ (ypeak-size(template,1)) (xpeak-size(template,2)) ];
isequal(corr_offset,offset) % 1 means offset was recovered