Matlab:使用矢量化进行模板匹配

发布于 2024-12-18 09:17:32 字数 677 浏览 2 评论 0原文

我正在尝试提高此代码的速度,但我无法理解如何在此处使用矢量化(而不是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梅窗月明清似水 2024-12-25 09:17:32

您将需要在图像上使用 im2col 函数,并在初始模板中使用 repmat

im_v = im2col(image,[hT wT]);
template_v = repmat(template(:),1,size(im_v,2));

im_v 将存储矩阵的每个 hT x wT 块的列向量。现在,您可以在 im_vtemplate_v 之间执行您想要的任何功能。

You're going to want to use the im2col function on the image and repmat with your initial template.

im_v = im2col(image,[hT wT]);
template_v = repmat(template(:),1,size(im_v,2));

im_v will store column vectors of every hT x wT block of your matrix. Now, you can perform any function you'd like between im_v and template_v.

萌酱 2024-12-25 09:17:32

如果您的模板尺寸为 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文