Matlab - 移动窗口,避免嵌套循环

时间:2011-03-10 16:24:51

标签: matlab for-loop

我正在尝试编写一个没有嵌套循环的“加权移动窗口”来提高速度。 我已经尝试过使用arrayfun而没有得到令人兴奋的结果,但也许我是以错误的方式做到的。

窗口在每个位置具有不同的权重(存储在B中)并且应该叠加在矩阵A上,返回位于窗口内的矩阵A的值,乘以窗口在该位置的权重(从中读取) B)。 此外,窗口可以相互重叠,在这种情况下,应保持最大值。 最后,窗口的尺寸和移位应该是函数的参数。

它实际上看起来更难,所以我向您展示了我想要改进的代码:

A = reshape([1:35],7,5)';   % values matrix
B = [1:3;4:6];              % window s weight matrix

% matrices size
[m n] = size(A);
[a b] = size(B);

% window s parameters
shift = 2;                  % window s movement at each iteration
zone = 3;                   % window s size (zone x zone)

% preallocation
C = ones(m,n);              % to store the right weight to be applied in each position

% loop through positions and find the best weight when they overlap
for i=1:m
    for j=1:n
       C(i,j) = max(max(B( max(round((i-zone)/shift)+1,1) : min(ceil(i/shift),a) , max(round((j-zone)/shift)+1,1) : min(ceil(j/shift),b))));
    end
end

% find the output of the windows
result = C.*A;

我希望自己明确表达,但如果您需要更多细节,请询问。 提前感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

如果您有权访问图像处理工具箱,则需要查看perform sliding neighborhood operations的方法。特别是,我认为函数NLFILTER可用于实现您想要的结果:

A = reshape([1:35],7,5)';  %'# Matrix to be filtered
B = [1:3;4:6];              %# Window weights
result = nlfilter(A,[2 3],@(M) max(M(:).*B(:)));

答案 1 :(得分:1)

我会使用im2col.假设你的图像是j x k,你的窗口是m x n,你将得到一个mn x(j-m + 1)*(k-n + 1)的矩阵。然后,您可以采取其他所有列。

示例代码:

%A = your_image
B = im2col(A, [m n],'sliding');
C = B(:,1:2:end);

你的滑动窗口是“shift 2”。

答案 2 :(得分:1)

尝试filter

例如,要做一个窗口平均值,超过5个元素:

outdata = filter([ 0.2 0.2 0.2 0.2 0.2 ], 1, indata);