"""This program executes edge detection by finding the difference
in color value between a pixel and the average of the eight surrounding
pixels. For example, given pixel at location [i,j], the neighbors are
at locations:
[i-1,j-1], [i-1,j], [i-1,j+1], [i,j-1], [i,j+1],
[i+1,j-1], [i+1,j], [i+1, j+]
Note that pixels are stored in a special datatype that requires indexing
as above.
A pixel is a three tuple of red, green, blue values.
"""
import Image
[docs]def diff_color(colorList, curcolor):
"""Finds the difference between the average value of the pixels
in a list of colors and a given color. It then converts the value
to gray scale by taking the average of the pixel values and returns
a color in gray scale. Gray scale colors have the same value for the
red, green and blue channels.
Note: By subtracting a color from 256, we change from black to white.
"""
avg = [0,0,0]
(r,g,b) = curcolor
for item in colorList:
avg[0] += item[0]
avg[1] += item[1]
avg[2] += item[2]
avg[0] /= len(colorList)
avg[1] /= len(colorList)
avg[2] /= len(colorList)
grayval = (256 -abs(avg[0]-r) +\
256 - abs(avg[1]-g) +\
256 - abs(avg[2]-b))/3
return (grayval, grayval, grayval)
if __name__ == '__main__':
im = Image.open("bolt.jpg")
(w,h) = im.size
newim = Image.new("RGB",(w,h),"white")
pix = im.load()
newpix = newim.load()
for i in range(1,w-1):
for j in range(1,h-1):
colorlist = [ pix[i-1,j-1], \
pix[i-1,j],\
pix[i-1,j+1],\
pix[i,j-1],\
pix[i,j+1],\
pix[i+1,j-1],\
pix[i+1,j],\
pix[i+1, j+1] ]
newcolor = diff_color(colorlist, pix[i,j])
newpix[i,j] = newcolor
newim.show()