简体   繁体   中英

detect the position of an object in the image using matlab

I am trying to implement the 2D correlation algorithm to detect the position of an object in the image, i don't want to use any built in function estimates 2d correlation.

Here is my code:

I=imread('image.tif');      % image is a black image contains white letters.
h=imread('template.tif');   %template is a small image taken from the original image, it contains one white letter.
I=double(I);
h=double(h);
[nrows ncolumns]=size(I);
[nrows2 ncolumns2]=size(h);
C=zeros(nrows,ncolumns);

for u=1:(nrows-nrows2+1)
   for v=1:(ncolumns-ncolumns2+1)
       for x=1:nrows2
           for y=1:ncolumns2
               C(u,v)=C(u,v)+(h(x,y)*I(u+x-1,v+y-1));
           end
       end
  end
end

[maxC,ind] = max(C(:));
[m,n] = ind2sub(size(C),ind)   % the index represents the position of the letter.

output_image=(3.55/4).*C./100000;
imshow(uint8(output_image));

I think it is working! but it is very slow.

How can i replace the following code by a better code to speed up the algorithm?

   for x=1:nrows2
       for y=1:ncolumns2
           C(u,v)=C(u,v)+(h(x,y)*I(u+x-1,v+y-1));
       end
   end

I am thinking that in every time i have the following two matrices

h(1:nrows2,1:ncolumns2) and I(u:u+nrows2-1,v:v+ncolumns2-1)

another question, are there any improvements?

thanks.

Whenever you can, try to use matrix ops. So try something like:

rowInds = (1:nrows2)-1;
colInds = (1:ncolumns2)-1;

temp = h.*I(u+rowInds,v+colInds);
C(u,v) = sum(temp(:));

Instead of:

for x=1:nrows2
    for y=1:ncolumns2
        C(u,v)=C(u,v)+(h(x,y)*I(u+x-1,v+y-1));
    end
end

Yes there are many improvements. You don't need a for loop at all. Since you do not want to use matlab's xcorr2 function, you can use conv2 . See the answer I gave here .

How about determining the cross correlation in the Fourier domain, following the cross-correlation theorem ? That should guarantee a dramatic speed increase.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM