01.25

I’ve learned much snake-speak since starting at Green Grass. Now that I’ve spent almost 2 years developing some proprietary software for the studio, I felt I could start providing some quick little Python examples for people wanting to do crazy and silly things. The first is using Python and the Python Imaging Library (PIL) to get the average color of an image. I used this to add some extra GUI flare to our project management software and, in a more advanced state, used it to perform color blending as a neat animated trick.
An extra note is that this script also takes into account images with an alpha. If you have an image with, say, a drop shadow and only 50% of the image has an alpha of 255 (opaque), you risk muddying up the average color with unnecessary values of 0,0,0. While it is a true average of the ‘pixel colors’, aesthetically, it’s not very pleasing. Code below!
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
from PIL import Image
image = "image.jpg"
def analyze():
###Open the image with PIL
img = Image.open(image)
###Grab the width, height, and build a list of each pixel in the image.
width, height = img.size
pixels = img.load()
data = []
for x in range(width):
for y in range(height):
cpixel = pixels[x, y]
data.append(cpixel)
###Setup our R, G, and B variables for some math!
r = 0
g = 0
b = 0
avgCount = 0
###Run through every single pixel in the image, grab the r, g, and b value.
###Then test if the image has an alpha. If so, only average pixels with an
###alpha value of 200 or greater (out of 255).
for x in range(len(data)):
try:
if data[x][3] > 200:
r+=data[x][0]
g+=data[x][1]
b+=data[x][2]
except:
r+=data[x][0]
g+=data[x][1]
b+=data[x][2]
avgCount+=1
###Get the averages, and return!
rAvg = r/avgCount
gAvg = g/avgCount
bAvg = b/avgCount
return (rAvg, gAvg, bAvg)
r, g, b = analyze()
print r, g, b |

.png)