Mean Filtering using a 5×5 Kernel

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 mean filtering on a single pixel of an image using a 5×5 kernel
def meanFilter5x5(x, y, image, newImage):
neighborSum = 0
for i in range(-2, 3):
for j in range(-2, 3):
neighborSum = neighborSum + image[x + i, y + j]

newImage[x, y] = neighborSum / 25

# Make sure the filename was specified
if len(sys.argv) < 2:
print “use: python Mean5x5.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 Mean Filtering Image”,

# Apply mean 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):
meanFilter5x5(x, y, pixels, newPixels)

image.show()
newImage.show()

Sample Image

5x5 Mean Filtering

5×5 Mean Filtering

Leave a comment