Question

I am having some trouble manually creating a histogram of intensity values from a grayscale image. Below is the code that I am using the create the bins for the plot that I want to create. The code works fine for every bin except for the last two. For some reason if the intensity is 254 or 255 it puts both values into the 254 bin and no values are accumulated in the 255 bin.

bins= zeros(1,256);
[x,y]=size(grayImg);
for i = 1:x
    for j = 1:y
        current = grayImg(i,j);
        bins(current+1) = bins(current+1) + 1;
    end
end
plot(bins);

I do not understand why this behavior is happening. I have printed out the count of 254 intensities and 255 intensities and they are both correct. However, when using the above code to accumulate the intensity values it does not work correctly.

Edit: Added the image I am using, the incorrect graph(the one I get with above code), and the correct one

grayscale image

Incorrect graph

Correct graph

Was it helpful?

Solution

A. The first problem with your code is the initial definition of bins. It seems that you come from C or somthing like that, but the definition should be- bins=zeros(1,256);

B. The second point is that you don't need the nested loop, you have a matlab function especially for that:

bins=hist(grayImg(:),1:256);     % now, you don't need the pre-definition for 'bins'.
plot(bins);

C. Try to use functions like bar or imhist or hist(grayImg(:)), it may save you all this, and give a nice plot.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top