MATLAB loop vectorization

I have the following MATLAB code:

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

      

This fragment is a part of a program that separates an object or color from an RGB image from several points marked by the user. Segmentation is achieved using 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 is a little slow. How can I take advantage of the fact that MATLAB is much faster with vectors and matrices than using loops? In other words, how can this vector be vectorized?

+3


source to share


1 answer


Approach # 1 C 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 C 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: Executing codes on a random 512 x 512 x 3

image:, image_rgb = randi(255,512,512,3)

runtime -

---------------------------------- 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.

      

Additional reasons for vectorization

!

+4


source







All Articles