简体   繁体   English

矢量化MATLAB循环

[英]Vectorize MATLAB loop

I have the following MATLAB code : 我有以下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

The above fragment is part of a program that, from an RGB image, segments an object or color from a few points marked by the user. 上述片段是程序的一部分,该程序从RGB图像中分割出来自用户标记的几个点的对象或颜色。 The segmentation is achived by means of the euclidean distance to the mean of the points marked by the user. 通过欧氏距离与用户标记的点的平均值来实现分割。 For each pixel if the distance is less than a given threshold then that pixel is white in the segmented image. 对于每个像素,如果距离小于给定阈值,则该像素在分割图像中是白色的。 Otherwise, black. 否则,黑色。

The code works well, but it's a bit slow. 代码运行良好,但有点慢。 How can I take advantage of the fact that MATLAB is much faster with vectors and matrices than using loops? 我如何利用MATLAB比使用循环更快地使用向量和矩阵这一事实? In other words, how can this code be vectorized ? 换句话说,这个代码如何被矢量化

Approach #1 With bsxfun - 方法#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)

Approach #2 With matrix-multiplication based euclidean distance calculations - 方法#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)

Quick runtime tests: Running the codes on a random 512 x 512 x 3 image: image_rgb = randi(255,512,512,3) , the runtimes were - 快速运行时测试:在随机的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.

More reasons to go for vectorization ! 更多理由去vectorization

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM