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 mode filtering on a single pixel of an image using a 3×3 kernel
def modeFilter3x3(x, y, image, newImage):
neighbors = []
neighborSum = 0
for i in range(-1, 2):
for j in range(-1, 2):curPixel = image[x + i, y + j]
neighborSum = neighborSum + curPixel# Sort the neighbors while inputting them into a list
if (len(neighbors) == 0):
neighbors.append(curPixel)
else:
k = 0
while k < len(neighbors) and curPixel > neighbors[k]:
k = k + 1if k == len(neighbors):
neighbors.append(curPixel)
else:
neighbors.insert(k, curPixel)mean = neighborSum / 9
# Remove the 2 largest outliers in the group of neighbors
while len(neighbors) > 7:
lastPosition = len(neighbors) – 1
if abs(neighbors[lastPosition] – mean) > abs(neighbors[0] – mean):
neighbors.pop(lastPosition)
else:
neighbors.pop(0)newImage[x, y] = neighbors[3]
# Make sure the filename was specified
if len(sys.argv) < 2:
print “use: python Mode3x3.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])
width,height = image.size
pixels = image.load()
newPixels = newImage.load()print “3×3 Mode Filtering Image”,
# Apply mode filtering on the image using a 3×3 kernel
for y in range(1, height – 1):
print “.”,
sys.stdout.flush()for x in range(1, width – 1):
modeFilter3x3(x, y, pixels, newPixels)image.show()
newImage.show()
