如何加速这种for循环?
我想计算沿给定轴方向平移图像的最大值。我知道 ordfilt2
,但是我想避免使用图像处理工具箱。
这是我到目前为止的代码:
imInput = imread('tire.tif');
n = 10;
imMax = imInput(:, n:end);
for i = 1:(n-1)
imMax = max(imMax, imInput(:, i:end-(n-i)));
end
是否可以避免使用 for 循环来加快计算速度,如果可以,如何避免?
第一次编辑:使用 Octave 的 im2col
代码实际上慢了 50%。
第二次编辑:预分配似乎不足以改善结果。
sz = [size(imInput,1), size(imInput,2)-n+1];
range_j = 1:size(imInput, 2)-sz(2)+1;
range_i = 1:size(imInput, 1)-sz(1)+1;
B = zeros(prod(sz), length(range_j)*length(range_i));
counter = 0;
for j = range_j % left to right
for i = range_i % up to bottom
counter = counter + 1;
v = imInput(i:i+sz(1)-1, j:j+sz(2)-1);
B(:, counter) = v(:);
end
end
imMax = reshape(max(B, [], 2), sz);
第三次编辑:我将显示时间安排。
I would like to compute the maximum of translated images along the direction of a given axis. I know about ordfilt2
, however I would like to avoid using the Image Processing Toolbox.
So here is the code I have so far:
imInput = imread('tire.tif');
n = 10;
imMax = imInput(:, n:end);
for i = 1:(n-1)
imMax = max(imMax, imInput(:, i:end-(n-i)));
end
Is it possible to avoid using a for-loop in order to speed the computation up, and, if so, how?
First edit: Using Octave's code for im2col
is actually 50% slower.
Second edit: Pre-allocating did not appear to improve the result enough.
sz = [size(imInput,1), size(imInput,2)-n+1];
range_j = 1:size(imInput, 2)-sz(2)+1;
range_i = 1:size(imInput, 1)-sz(1)+1;
B = zeros(prod(sz), length(range_j)*length(range_i));
counter = 0;
for j = range_j % left to right
for i = range_i % up to bottom
counter = counter + 1;
v = imInput(i:i+sz(1)-1, j:j+sz(2)-1);
B(:, counter) = v(:);
end
end
imMax = reshape(max(B, [], 2), sz);
Third edit: I shall show the timings.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就其价值而言,这是使用 IM2COL 函数的矢量化解决方案从图像处理工具箱:
您也许可以编写自己的 IM2COL 版本,因为它只是由精心设计的索引组成,或者甚至看看 Octave 实现它。
For what it's worth, here's a vectorized solution using IM2COL function from the Image Processing Toolbox:
You could perhaps write your own version of IM2COL as it simply consists of well crafted indexing, or even look at how Octave implements it.
查看有关在 c 中进行滚动中位数的问题的答案。我已经成功地将它变成了 mex 函数,它甚至比 ordfilt2 还要快。达到最大值需要一些工作,但我确信这是可能的。
C 中的滚动中位数 - Turlach 实现
Check out the answer to this question about doing a rolling median in c. I've successfully made it into a mex function and it is way faster than even ordfilt2. It will take some work to do a max, but I'm sure it's possible.
Rolling median in C - Turlach implementation