Matlab:使用矢量化进行模板匹配
我正在尝试提高此代码的速度,但我无法理解如何在此处使用矢量化(而不是 for 循环)。该函数来自我使用 SAD 的实现href="http://en.wikipedia.org/wiki/Template_matching#Template-based_matching_and_volving" rel="nofollow">模板匹配。
function [diffs,time] = search(template,image)
[hT,wT] = size(template);
[hI,wI] = size(image);
h = hI-hT+1;
w = wI-wT+1;
diffs = zeros(h,w);
tic;
for i = 1:h
for j = 1:w
t = image(i:i+hT-1,j:j+wT-1)-template(:,:); % ???
diffs(i,j) = sum(sum(abs(t)));
end
end
time = toc;
对于 640x480 的图像,此函数的工作时间约为 22-25 秒。
I'm trying to improve speed of this code, but I can't understand how to use vectorization here (instead of for-loop). The function is from my impementation of SAD using template matching.
function [diffs,time] = search(template,image)
[hT,wT] = size(template);
[hI,wI] = size(image);
h = hI-hT+1;
w = wI-wT+1;
diffs = zeros(h,w);
tic;
for i = 1:h
for j = 1:w
t = image(i:i+hT-1,j:j+wT-1)-template(:,:); % ???
diffs(i,j) = sum(sum(abs(t)));
end
end
time = toc;
For an image of 640x480 this function works about 22-25 seconds.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将需要在图像上使用
im2col
函数,并在初始模板中使用repmat
。im_v
将存储矩阵的每个hT x wT
块的列向量。现在,您可以在im_v
和template_v
之间执行您想要的任何功能。You're going to want to use the
im2col
function on the image andrepmat
with your initial template.im_v
will store column vectors of everyhT x wT
block of your matrix. Now, you can perform any function you'd like betweenim_v
andtemplate_v
.如果您的模板尺寸为 480*360,图像尺寸为 640*480,则总共需要执行 480*360*480*640=5.3084e+10 次操作。
所以,我不认为你能跑得比 22-25 秒快得多。
在您的情况下,循环内的代码非常大并且矢量化,因此您不会通过因式分解获得太多收益。
如果您的模板小得多,您可以使用函数
im2col
进行矢量化,但由于您的模板非常大,因此会占用太多 RAM 内存。If your template has size 480*360 and your image 640*480, in total you want to do 480*360*480*640=5.3084e+10 opérations.
So, I don't think you can go much faster than 22-25 seconds.
In your case, the code inside the loop is quite big and vectorized, so you would not gain much by factorizing.
If your template was much smaller, you could use the function
im2col
to vectorize, but since your template is very big, it would take too much RAM memory.