2

I have a function which aimed to crop a part of image and find that cropped part inside main picture by using conv2.As far as I know when using convolution on two matrix the coordinates of maximum value in resulted matrix show similar parts of matrices. My problem is that x,y doesn't show the true point.

function [  ] = cropImage( fileIn)
    im=imread(fileIn);
    [r c]=size(im);
    crop=imcrop(im);

    figure(1)
    subplot(2,2,1)
    imshow(im)
    subplot(2,2,2)
    imshow(crop)

    d=conv2(double(im),double(crop);
    m=max(d);
    m=max(m);
    [x y]=find(d==m);     

    subplot(2,2,4)
    imshow(d)

    text(x,y,'+','color','r');    
    subplot(2,2,1)

    text(x,y,'+','color','r');    
end
NewUser
  • 87
  • 12

1 Answers1

7

Convolution wont give you the point with maximal similarity, the correlation (or cross-correlation) is the operator you are looking for. More concretelly, matlab has already implemented normalized cross-correlation for 2d images:

>>> c = normxcorr2(template, image);
>>> [ypeak, xpeak] = find(c==max(c(:)));

Correlation is the 180 degree rotation of the convolution operator.

Imanol Luengo
  • 15,366
  • 2
  • 49
  • 67
  • 1
    I'd like to point out that `ypeak` and `xpeak` are the locations of where the template matched with respect to the **top-left corner** of the bounding box, not the centre as we would intuitively like. – rayryeng Apr 21 '16 at 14:13
  • @rayryeng Edited to fix that, thanks! was pretty clear in my mind, not that good putting it into words :P – Imanol Luengo Apr 21 '16 at 14:15
  • No problem at all :) You had my vote already. – rayryeng Apr 21 '16 at 14:16
  • I my code I replaced these codes but didn't work : `d=normxcorr2(crop,im); [ypeak, xpeak] = find(c==max(c(:))); subplot(2,2,1) text(xpeak,ypeak,'+','color','r');` – NewUser Apr 21 '16 at 14:17
  • 1
    @NewUser replace `c` with `d` in the `find`. Additionally, as @rayryeng mentioned. `ypeak` and `xpeak` correspond to the top left corner of the template. It is not in the center. You can shift them by adding half the size of the template to center them in the image. – Imanol Luengo Apr 21 '16 at 14:20