Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding histogram() in Pillow

From the docs:

im.histogram() => list

Returns a histogram for the image. The histogram is returned as a list of pixel counts, one for each pixel value in the source image. If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an “RGB” image contains 768 values).

I understand that there are 256 values for Red, 256 for Green and 256 for Blue (256 * 3 = 768).

for i, value in enumerate(im.histogram()):
    print i, value

Produces:

0 329
1 145
... (skipping some)
256 460
... (skipping some)
767 3953

My question is: does that mean that there were:
329 pixels that had a value of R = 0, G = 0, B = 0 and
145 pixels that had a value of R = 1, G = 0, B = 0 and
460 pixels that had a value of R = 256, G = 1, B = 0 and
3953 pixels that had a value of R = 256, G = 256, B = 256 etc. ?

Is that how I should read the output?

like image 975
e h Avatar asked Dec 12 '22 07:12

e h


2 Answers

I haven't tested, but from the documentation, the wording seems to indicate that the histogram only applies to each channel (e.g. Red, Green, Blue) individually.

If the image has more than one band, the histograms for all bands are concatenated (for example, the histogram for an “RGB” image contains 768 values).

So, no, the examples you gave aren't really correct. 768 values is just 256 * 3, which is the number of possible red values, plus the number of possible green values, plus the number of possible blue values independently. It does not represent all possible combinations of red, green, and blue, which would instead be 256 ^ 3 == 16777216.

From what I can see, the interpretation of your example histogram values should be:

329  pixels with value of R = 0, G = ?, B = ? and
145  pixels with value of R = 1, G = ?, B = ? and
...
460  pixels with value of R = ?, G = 1, B = ? and
...
3953 pixels with value of R = ?, G = ?, B = 256
like image 122
voithos Avatar answered Feb 28 '23 03:02

voithos


No, you don't know how many pixels had (e.g.) R=0, G=0, B=0. That would require a histogram with something like 16 million entries.

You only know how many had R=0, how many had G=0, and how many had B=0, taken independently.

It would be entirely possible for the R=0 pixels to have a great many different amounts of G and B.

like image 36
scav Avatar answered Feb 28 '23 02:02

scav