Source Code
Note: Indentation was lost when copying to the webpage. If it is unbearable view the actual source.
#!/usr/bin/python
import sys
import PIL
from PIL import Image# Applies extremum filtering on a single pixel of an image using a 5×5 kernel
def exFilter5x5(x, y, image, newImage):
neighborSum = 0
maxValue = image[x, y]
minValue = image[x, y]
for i in range(-2, 3):
for j in range(-2, 3):
curPixel = image[x + i, y + j]
neighborSum = neighborSum + curPixelif curPixel > maxValue:
maxValue = curPixel
if curPixel < minValue:
minValue = curPixelmean = neighborSum / 25
if (abs(mean – minValue) < abs(maxValue – mean)):
newImage[x, y] = minValue
else:
newImage[x, y] = maxValue# Make sure the filename was specified
if len(sys.argv) < 2:
print “use: python Extremum5x5.py [image filename]”
sys.exit()# Open the file and load an array of all its pixels
image = Image.open(sys.argv[1])
newImage = Image.open(sys.argv[1])
pixels = image.load()
newPixels = newImage.load()print “5×5 Extremum Filtering Image”,
# Apply extremum filtering on the image using a 5×5 kernel
width,height = image.size
for y in range(2, height – 2):
print “.”,
sys.stdout.flush()for x in range(2, width – 2):
exFilter5x5(x, y, pixels, newPixels)image.show()
newImage.show()
