[Image-SIG] Averaging each pixel over sequential images

toru toru@oldriver.org
Mon, 24 Jun 2002 14:32:26 -0700


I am trying to obtain the average brightness of each pixel over a set of 
grayscale images, using PIL.

The following code works correctly but looks a little tedious.  I would
like to know if any common idiom exists for this solution.

---- BEGINS ----
import Image
import struct
import string

# Obtain image size, assuming all are in the same size
img = Image.open(files[0])
width, height = img.size

# Sum brightness of every pixel
sum = [0 for i in xrange(width*height)]
for file in files:
    img = Image.open(file)
    img.convert("L")
    str = img.tostring()
    for i in xrange(width*height):
        p = struct.unpack("B", str[i])[0]
        sum[i] += p

# Devide sum of each pixel by the number of images
avg = []
for x in sum:
    avg.append(struct.pack("B", x/len(files)))
avg_str = string.join(avg, "")
avg_img = Image.fromstring("L", (width, height), avg_str)
---- ENDS ----

Toru Furukawa
toru@oldriver.org