Tuesday, September 22, 2009

Python - find the average rgb color for an image

#   iterate through each pixel in an image and
# determine the average rgb color

# you will need to install the PIL module

from PIL import Image

class PixelCounter(object):
''' loop through each pixel and average rgb '''
def __init__(self, imageName):
self.pic = Image.open(imageName)
# load image data
self.imgData = self.pic.load()
def averagePixels(self):
r, g, b = 0, 0, 0
count = 0
for x in xrange(self.pic.size[0]):
for y in xrange(self.pic.size[1]):
tempr,tempg,tempb = self.imgData[x,y]
r += tempr
g += tempg
b += tempb
count += 1
# calculate averages
return (r/count), (g/count), (b/count), count

if __name__ == '__main__':
# assumes you have a test.jpg in the working directory!
pc = PixelCounter('test.jpg')
print "(red, green, blue, total_pixel_count)"
print pc.averagePixels()

# for my picture the ouput rgb values are:
# (red, green, blue, total_pixel_count)
# (135, 122, 107, 10077696)
# you can see that my image had 10,077,696 pixels and python/PIL
# still churned right through it!


  1. PNG files have an extra alpha layer, so loading test.png instead of test.jpg with this script throws an error. But with a little change this is fixed:

    clrs = self.imgData[x,y]
    r += clrs[0]
    g += clrs[1]
    b += clrs[2]

  2. I made some experiments to improve performance that might be interesting: https://github.com/bigben87/ColorAverage

  3. You can also use scipy and get average in just one line:

    from scipy import misc