Created
September 27, 2011 21:14
-
-
Save olooney/1246268 to your computer and use it in GitHub Desktop.
Average Image Color
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.