Count each histogram in ascending order

Hello,
I am trying to count the histogram value of an image, like aaa = [0:20 1:4 2:0 3:0 4:0 5:0 6:12... 255:9] which includes those pixel value which generates 'zero' as well.
First I used 'unique' function to keep the pixel values in increasing order and then used 'histc' to count the histogram bins. But, while using 'unique' function, the pixels whose values are zeroes are not showing in 'aaa' as I likely to get in the example above. In my output its like aaa = [0:20 1:4 6:12... 255:9] displaying only those pixels which has certain bins and removing pixels which count zero in numbers.
How to include the counting of those pixels whose values are zeroes and get the output 'aaa' as shown at first?

Answers (2)

Do not bother using unique() . Just use
bins = 0 : 255;
counts = histc(TheData, bins);
t = sprintf('%d:%d ', [bins; counts]);
a = [ '[', t(1:end-1), ']' ]; %add the [] and get rid of the trailing space
It took me a while to understand your example (that you meant that 20 was the histogram count for bin 0) because 0:20 has a very special meaning in matlab, it is the vector [0 1 2 ... 19 20].
If you want the histogram count for all bins from 0 to 255, then simply pass those bins to histc. So:
h = histc(yourimage(:), 0:255);
Note that since R2014b, matlab recommends to use histcounts instead of histc. In that case:
h = histcounts(yourimage(:), 'BinMethod', 'integers', 'BinLimits', [0 255])

1 Comment

@Guillaume, Yes you are right. 0:20 is '0' bins occurring 20 times. I will follow your advice of not using unique() as this function is not useful to include all bins from 0-255 which has zero value as well.

Sign in to comment.

Asked:

on 15 Jul 2016

Commented:

on 15 Jul 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!