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 median filtering on a single pixel of an image using a 5×5 kernel
def medianFilter5x5(x, y, image, newImage):
neighbors = []
for i in range(-2, 3):
for j in range(-2, 3):# Sort the neighbors while inputting them into a list
if (len(neighbors) == 0):
neighbors.append(image[x + i, y + j])
else:
k = 0
while k < len(neighbors) and image[x + i, y + j] > neighbors[k]:
k = k + 1if k == len(neighbors):
neighbors.append(image[x + i, y + j])
else:
neighbors.insert(k, image[x + i, y + j])newImage[x, y] = neighbors[12]
# Make sure the filename was specified
if len(sys.argv) < 2:
print “use: python Median5x5.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 “5×5 Median Filtering Image”,
# Apply median filtering on the image using a 5×5 kernel
for y in range(2, height – 2):
print “.”,
sys.stdout.flush()for x in range(2, width – 2):
medianFilter5x5(x, y, pixels, newPixels)image.show()
newImage.show()
