Reputation: 1964
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.
Upvotes: 1
Views: 5371
Reputation: 2114
How about determining the cross correlation in the Fourier domain, following the cross-correlation theorem? That should guarantee a dramatic speed increase.
Upvotes: 0
Reputation: 2344
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
Upvotes: 2
Reputation: 13081
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.
Upvotes: 0