I am trying to create a 5x5 mean filter to remove some salt and pepper noise from an image. I read the image into a numpy array. And tried making some changes to calculate the average value of a pixel's neighbors. The result I got is quite bad and I can't seem to figure out why there are gaps in my image result.
from PIL import Image
import numpy
image1 = 'noisy.jpg'
save1 = 'filtered.jpg'
def average(path, name):
temp=Image.open(path)
image_array = numpy.array(temp)
new_image = []
for i in range(0, len(image_array)):
new_image.append([])
n = 0
average_sum = 0
for i in range(0, len(image_array)):
for j in range(0, len(image_array[i])):
for k in range(-2, 3):
for l in range(-2, 3):
if (len(image_array) > (i + k) >= 0) and (len(image_array[i]) > (j + l) >= 0):
average_sum += image_array[i+k][j+l]
n += 1
new_image[i].append(int(round(average_sum/n)))
average_sum = 0
n = 0
x = Image.fromarray(numpy.array(new_image), 'L')
x.save(name)
print("done")
average(image1, save1)
---------------------Input image-----------------
---------------------Output image-----------------
Instead of creating a list for the new image, just make a copy of the original image (or create an array with the same size as of the original image) and change its value with the new averaged pixel values. Like this
def average(path, name):
temp=Image.open(path)
image_array = numpy.array(temp)
new_image = image_array.copy()
n = 0
average_sum = 0
for i in range(0, len(image_array)):
for j in range(0, len(image_array[i])):
for k in range(-2, 3):
for l in range(-2, 3):
if (len(image_array) > (i + k) >= 0) and (len(image_array[i]) > (j + l) >= 0):
average_sum += image_array[i+k][j+l]
n += 1
new_image[i][j] = (int(round(average_sum/n)))
average_sum = 0
n = 0
x = Image.fromarray(numpy.array(new_image), 'L')
x.save(name)
print("done")
This gave me the following output: