最高效的需要信号处理工具箱。然后你可以简单地使用xcorr2()
. 按照您的示例,以下内容应该有效:
C = xcorr2 (A, B);
[Row, Col] = find (C == max (C(:)));
%% these are not the coordinates for the center of the best match, you will
%% have to find where those really are
%% The best way to understand this is to strip the "padding"
row_shift = (size (B, 1) - 1)/2;
col_shift = (size (B, 2) - 1)/2;
C = C(1+row_shift:end-row_shift, 1+col_shift:end-col_shift)
[Row, Col] = find (C == max (C(:)));
if (B == A(Row-row_shift:Row+row_shift, Col-col_shift:Col+col_shift))
disp ("B shows up in A");
endif
上面的代码看起来有点复杂,因为我试图覆盖任何大小的输入(仍然只有奇数大小),但应该可以工作。
如果你没有这个工具箱,我认为你可以使用Octave 代码,这应该只需要小的调整。基本上,重要的只有三行(注意代码在 GPL 下):
[ma,na] = size(a);
[mb,nb] = size(b);
c = conv2 (a, conj (b (mb:-1:1, nb:-1:1)));
在 Octave 中,如果您至少使用信号包 1.2.0,xcorr2 还可以采用额外的选项“coeff”来计算归一化互相关。当匹配完美时,它的值为 1,因此您可以通过以下方式简化它:
C = xcorr2 (A, B, "coeff");
if (any (C(:) == 1)
display ("B shows up in A");
endif