An elegant way to get the output of `normxcorr2` in a manner similar to 'conv2' - (removing the unwanted edges)

柔情痞子 提交于 2019-11-28 14:19:49

Here's a variant that has a few extra features relative to the other answers:

  • It allows you to omit the shape argument (default is 'full').
  • It only calls normxcorr2 when shape is a valid string.
  • It performs the indexing in one line using logical indexing. The sizes of the lead padding and desired center region is used to create index vectors of true and false values. The trailing padding doesn't need to be specified since a logical index that is shorter than the dimension it indexes will simply be padded with false values.

And here's the code:

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

This would be much more concise. I hope it's what you're looking for:

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);

There is not much elegance here - you run the correlation, then you remove what you can't use. But it works.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!