使用matlab检测图像中对象的位置

时间:2012-11-24 16:17:18

标签: image matlab optimization image-processing computer-vision

我正在尝试实现2D相关算法来检测图像中对象的位置,我不想使用任何内置函数估计2d相关性。

这是我的代码:

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

我认为它有效!但它很慢。

如何用更好的代码替换以下代码以加速算法?

   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

我想每次我都有以下两个矩阵

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

另一个问题,有什么改进吗?

感谢。

3 个答案:

答案 0 :(得分:2)

只要你可以,尝试使用矩阵操作。所以尝试类似的事情:

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

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

而不是:

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

答案 1 :(得分:0)

是的,有很多改进。你根本不需要for循环。由于您不想使用matlab的xcorr2函数,因此可以使用conv2。请参阅我给出的答案here

答案 2 :(得分:0)

如何在cross-correlation theorem之后确定傅里叶域中的互相关?这应该保证速度的显着提高。