import os
import sys
import Image
import numpy

print "Averaging images  1.jpg 2.jpg ... 9.jpg"

im1 = Image.open('1.jpg')
a1 = numpy.asarray(im1).astype(numpy.uint16)
im2 = Image.open('2.jpg')
a2 = numpy.asarray(im2).astype(numpy.uint16)
im3 = Image.open('3.jpg')
a3 = numpy.asarray(im3).astype(numpy.uint16)
im4 = Image.open('4.jpg')
a4 = numpy.asarray(im4).astype(numpy.uint16)
im5 = Image.open('5.jpg')
a5 = numpy.asarray(im5).astype(numpy.uint16)
im6 = Image.open('6.jpg')
a6 = numpy.asarray(im6).astype(numpy.uint16)
im7 = Image.open('7.jpg')
a7 = numpy.asarray(im7).astype(numpy.uint16)
im8 = Image.open('8.jpg')
a8 = numpy.asarray(im8).astype(numpy.uint16)
im9 = Image.open('9.jpg')
a9 = numpy.asarray(im9).astype(numpy.uint16)
new = (a1+a2+a3+a4+a5+a6+a7+a8+a9)/9

print new.size, "pixels in a array shape of ",numpy.shape(new)," of type ", new.dtype
# so array order is [ iy, ix, iz ]

# interpolate across bad pixels

#Find average RGB value around bad pixels

red   = (new[180,94,0] + new[180,95,0] + new[180,96,0] + new[180,97,0] + new[189,94,0] + new[189,95,0] + new[189,96,0] + new[189,97
,0])/8

green = (new[180,94,1] + new[180,95,1] + new[180,96,1] + new[180,97,1] + new[189,94,1] + new[189,95,1] + new[189,96,1] + new[189,97
,1])/8

blue  = (new[180,94,2] + new[180,95,2] + new[180,96,2] + new[180,97,2] + new[189,94,2] + new[189,95,2] + new[189,96,2] + new[189,97
,2])/8

print "Botch region with an RGB of ", red, green, blue

for ix in range(93,98):
    for iy in range(182,187):
        new[iy,ix,0] = red
        new[iy,ix,1] = green
        new[iy,ix,2] = blue

mean = new.astype(numpy.uint8)
out = Image.fromarray(mean)

out.save("average.jpg","JPEG",quality=95)
