Sanbron Liong
Sanbron Liong

Reputation: 63

Decrease Matlab for loop

% read image
I = imread(im);
H = zeros(256,1);
% m = width, n = height
[m,n] = size(I);

% loop for checking values
for GrayValue = 0:255
    for i = 1:m
        for j = 1:n
            if I(i,j) == GrayValue % read each pixel coordinate
                H(GrayValue+1) = H(GrayValue+1)+1;
            end
        end
    end
end

This function it go get image file as im and will show a histogram of values count in the image. How can i reduce the time taken to execute this MATLAB function. It is similar to imhist() . But I want to make a similar imhist() function. I cannot figure out to remove which loop.

Upvotes: 0

Views: 216

Answers (2)

David
David

Reputation: 8459

Obligatory bsxfun solution:

H=sum(bsxfun(@eq,I(:),0:255))

And a method that might be easier to understand. This just replaces your two inner loops with a search.

I=randi(256,50,50)-1;
H=zeros(256,1);

G=zeros(256,1);
for GrayValue=0:255
    [ii,jj]=find(I==GrayValue);
    G(GrayValue+1)=length(ii);
end

Upvotes: 2

Divakar
Divakar

Reputation: 221754

Assuming I to be a grayscale image, you can use histc to get H -

H = sum(histc(I,0:255),2)

Thus, the complete code would be -

% read image
I = imread(im);
H = sum(histc(I,0:255),2)

If you were looking for a little less-advanced code, you can avoid one nested loop -

% read image
I = imread(im);
H = zeros(256,1);

% loop for checking values
for GrayValue = 0:255
    for i = 1:numel(I)
        if I(i) == GrayValue % read each pixel coordinate
            H(GrayValue+1) = H(GrayValue+1)+1;
        end
    end
end

Upvotes: 1

Related Questions