Skip to content

Instantly share code, notes, and snippets.

@olooney
Created September 27, 2011 21:14
Show Gist options
  • Save olooney/1246268 to your computer and use it in GitHub Desktop.
Save olooney/1246268 to your computer and use it in GitHub Desktop.
Average Image Color
from PIL import Image
def average_image_color(filename):
i = Image.open(filename)
h = i.histogram()
# split into red, green, blue
r = h[0:256]
g = h[256:256*2]
b = h[256*2: 256*3]
# perform the weighted average of each channel:
# the *index* is the channel value, and the *value* is its weight
return (
sum( i*w for i, w in enumerate(r) ) / sum(r),
sum( i*w for i, w in enumerate(g) ) / sum(g),
sum( i*w for i, w in enumerate(b) ) / sum(b)
)
if __name__ == '__main__':
import sys
if len(sys.argv) > 1:
print average_image_color(sys.argv[1])
else:
print 'usage: average_image_color.py FILENAME'
print 'prints the average color of the image as (R,G,B) where R,G,B are between 0 and 255.'
@dyspop
Copy link

dyspop commented Mar 27, 2017

Hi! I liked this very much. While I understand most images are RGB, some are not. I wanted to write it in a way that could work with any image color mode: https://gist.github.com/dyspop/77b220a38e4309326bdf802ac9ac1b64

The above returns { 'R': 100, 'G': 101, 'B': 12 }

I'd like it to really return { 'RGB' : (100, 101, 12) } but I couldn't figure out how to do that and support producing tuples of unknown length

@dyspop
Copy link

dyspop commented Mar 31, 2017

Are you sure this does what you think it does? I'm thinking it actually takes the full histogram and cuts it up into four parts... I tested this on a single color image and the histograms don't look right to me. I could be wrong.

# split into red, green, blue
	r = h[0:256]
	g = h[256:256*2]
	b = h[256*2: 256*3]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment