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 3×3 kernel
def exFilter3x3(x, y, image, newImage):
neighborSum = 0
maxValue = image[x, y]
minValue = image[x, y]
for i in range(-1, 2):
for j in range(-1, 2):
curPixel = image[x + i, y + j]
neighborSum = neighborSum + curPixelif curPixel > maxValue:
maxValue = curPixel
if curPixel < minValue:
minValue = curPixelmean = neighborSum / 9
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 Extremum3x3.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 “3×3 Extremum Filtering Image”,
# Apply extremum filtering on the image using a 3×3 kernel
width,height = image.size
for y in range(1, height – 1):
print “.”,
sys.stdout.flush()for x in range(1, width – 1):
exFilter3x3(x, y, pixels, newPixels)image.show()
newImage.show()
