Minimum Filtering using a 3×3 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 minimum filtering on a single pixel of an image using a 3×3 kernel
def minFilter3x3(x, y, image, newImage):
minValue = image[x, y]
for i in range(-1, 2):
for j in range(-1, 2):
if image[x + i, y + j] < minValue:
minValue = image[x + i, y + j]

newImage[x, y] = minValue

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

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

image.show()
newImage.show()

Sample Image

3x3 Minumum Filtering

3×3 Minumum Filtering

Leave a comment