在Matlab中是否存在优雅方式,以使normxcorr2
的输出裁剪为图像大小或仅裁剪到不使用零填充边的矩阵部分在计算?
要理解我的意思,请考虑conv2
命令。有一个名为shape
的可选参数,可以设置为same
或valid
。
C = conv2(A,B,'same');
C = conv2(A,B,'valid');
例如:
size( conv2( rand(50,50) , rand(6,6), 'valid') )
ans =
45 45
size( conv2( rand(50,50) , rand(6,6), 'same') )
ans =
50 50
size( conv2( rand(50,50) , rand(6,6)) )
ans =
55 55
目前我编写了自己的函数,它的功能如下:
function I = normxcorr2e(template,im,shape)
switch shape
case 'same'
I = normxcorr2(template,im);
r = size(I,1)-size(im,1);
c = size(I,2)-size(im,2);
m1=floor(r/2);
n1=floor(c/2);
m2=ceil(r/2);
n2=ceil(c/2);
I(1:m2,:) = [];
I(end-m1+1:end,:) = [];
I(:,1:n2) = [];
I(:,end-n1+1:end) = [];
case 'full'
%Do nothing
case 'valid'
%TODO - write this case...
otherwise
throw(Mexception('normxcorr2e:BadInput','shape %s is not recognized',shape));
end
end
你有更好的主意吗?成功回答的主要标准是建议解决方案的优雅。
编辑(1)首先,感谢您的所有答案。所有这些都是好的,并由我赞成。我还没有决定哪个是最好的。顺便说一句,我最近想到的是模板与图像相比较大的情况。在这种情况下,通过在运行image
之前裁剪normxcorr2
参数来加速计算是有意义的。
答案 0 :(得分:2)
这将更加简洁。我希望这就是你要找的东西:
function I = normxcorr2e(template,im,shape)
args={'full','same','valid'};
cropSize=(find(strcmp(shape,args))-1)*size(template);
crop=@(x,r) x(1+floor(r(1)/2):end-ceil(r(1)/2),1+floor(r(2)/2):end-ceil(r(2)/2))
I=crop(normxcorr2(template,im),cropSize);
答案 1 :(得分:2)
这是一个与其他答案相比具有一些额外功能的变体:
'full'
)。shape
是有效字符串时,它只会调用normxcorr2
。这是代码:
function I = normxcorr2e(template, im, shape)
if (nargin == 2) || strcmp(shape,'full')
I = normxcorr2(template, im);
return
end
switch shape
case 'same'
pad = floor(size(template)./2);
center = size(im);
case 'valid'
pad = size(template) - 1;
center = size(im) - pad;
otherwise
throw(Mexception('normxcorr2e:BadInput',...
'SHAPE must be ''full'', ''same'', or ''valid''.'));
end
I = normxcorr2(template, im);
I = I([false(1,pad(1)) true(1,center(1))], ...
[false(1,pad(2)) true(1,center(2))]);
end
答案 2 :(得分:1)
这里没有太多的优雅 - 你运行相关性,然后你删除你不能使用的东西。但它的确有效。
function I = normxcorr2e(template,im,shape)
%# perform cross correlation with automated zero-padding
I = normxcorr2(template,im);
switch shape
case 'same'
%# if we were guaranteed to have odd-sized templates only
%# we would only need padLow
templateSize = size(template);
padLow = floor(templateSize/2);
padHigh = templateSize - padLow - 1;
I = I( (1+padLow(1)):(end-padHigh(1)), (1+padLow(2)):(end-padHigh(2)) );
case 'full'
%Do nothing
case 'valid'
%# with even size, we need to remove the larger of the two pad sizes
%# i.e. padLow, on all sides
templateSize = size(template);
padLow = templateSize/2;
I = I( (2*padLow(1)):(end-2*padLow(1)+1), (2*padLow(2)):(end-2*padLow(2)+1) );
otherwise
throw(Mexception('normxcorr2e:BadInput','shape %s is not recognized',shape));
end