【问题标题】:Vectorize MATLAB loop向量化 MATLAB 循环
【发布时间】:2015-07-06 10:19:25
【问题描述】:

我有以下 MATLAB 代码:

meanv = [rmean,gmean,bmean];
for i = 1:1:image_info.Height
    for j = 1:1:image_info.Width      % for every pixel
        x = image_rgb(i,j,1:3);
        pix_color = [x(:,:,1),x(:,:,2),x(:,:,3)];
        d = dist(meanv,pix_color');
        if d <= threshold
            S(i,j) = 1;
        end
    end
end

上述片段是一个程序的一部分,该程序从 RGB 图像中根据用户标记的几个点分割对象或颜色。分割是通过到用户标记的点的平均值的欧几里德距离来实现的。对于每个像素,如果距离小于给定阈值,则该像素在分割图像中为白色。否则,黑色。

代码运行良好,但速度有点慢。我如何利用 MATLAB 使用向量和矩阵比使用循环快得多的事实? 换句话说,这段代码如何矢量化

【问题讨论】:

  • 为了将来参考,最好用简单的语言描述您的代码实现的目标。
  • @Setsu 是的,我现在正在阅读它,你是对的。帖子已编辑。

标签: performance matlab image-processing vectorization


【解决方案1】:

方法 #1 使用 bsxfun -

%// Get image size
[m,n,r] = size(image_rgb)

%// Calculate squared distances 
M = sum(bsxfun(@minus,reshape(image_rgb,[],3),meanv).^2,2)

%// Check if sq-ed distance satisfy threshold criteria & reshape back to img size
S = reshape(M <= threshold^2 ,m,n)

方法 #2 使用 matrix-multiplication based euclidean distance calculations -

%// Get image size
[m,n,r] = size(image_rgb)

%// Calculate squared distances 
A = reshape(image_rgb,[],3);
Bt = meanv(:);
M = [A.^2 ones(size(A)) -2*A ]*[ones(size(Bt)) ; Bt.^2 ; Bt]

%// Check if sq-ed distance satisfy threshold criteria & reshape back to img size
S = reshape(M<= threshold^2,m,n)

快速运行时测试:在随机512 x 512 x 3 图像上运行代码:image_rgb = randi(255,512,512,3),运行时是 -

---------------------------------- With Original Approach
Elapsed time is 5.850163 seconds.
---------------------------------- With BSXFUN
Elapsed time is 0.006737 seconds.
-------------------------- With Matrix-multiplication based Eucl. dist
Elapsed time is 0.015704 seconds.

更多理由选择vectorization

【讨论】:

  • 哇。简单、简洁、优雅!谢谢迪瓦卡。
猜你喜欢
  • 2013-02-18
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-02
  • 2016-03-11
相关资源
最近更新 更多