Thursday, September 8, 2016

Using Median Filter to Fix Noisy Image

Median Filter

Apply Median Filter To Remove Salt & Pepper Noise

Median filter is a nonlinear filter. It is usually a preprocessor to prepare image to remove noise and be ready for later process.

The advantage of median filter is that it preserves the edges of original image

In [1]:
# Load packages
import os
from PIL import Image, ImageFilter
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from scipy.ndimage import filters
from scipy import signal
from scipy import misc

# Ensure plots embeded in notebook
%matplotlib inline
In [2]:
# Open original image
img = misc.face()

# We cannot simply apply median filter to RGB image
# In this example, we only handles gray scaled image

#define a function to convert rgb to gray
def rgb2gray(rgb):

    r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b

    return gray

im = rgb2gray(img)
plt.imshow(im, cmap='gray')
plt.show()
In [3]:
# Add noise to the image
noise_sigma = 50

s_vs_p = 0.5
amount = 0.04
noisy_im = im
# Generate Salt '1' noise
num_salt = np.ceil(amount * im.size * s_vs_p)
coords = [np.random.randint(0, i - 1, int(num_salt))
     for i in im.shape]
noisy_im[coords] = 255

# Generate Pepper '0' noise
num_pepper = np.ceil(amount* im.size * (1. - s_vs_p))
coords = [np.random.randint(0, i - 1, int(num_pepper))
  for i in im.shape]
noisy_im[coords] = 0

plt.imshow(noisy_im, cmap='gray', vmin=0, vmax=255)
plt.show()

#poor guy!
In [4]:
# Apply Gaussian to smooth the image (remove noise)
repaired_im = sp.signal.medfilt(noisy_im, 9) # kernel size must be odd
plt.imshow(repaired_im, cmap='gray', vmin=0, vmax=255)
plt.show()
# Looks Better!
In [5]:
# Sharpen immage
alpha = 6
filter_blurred_image = filters.gaussian_filter(repaired_im, 2)
#sharp_image = repaired_im * (1 - alpha) + alpha * (repaired_im - filter_blurred_image)
sharp_image = repaired_im + alpha * (repaired_im - filter_blurred_image)
plt.imshow(sharp_image, cmap='gray', vmin=0, vmax=255)
plt.show()
# Even Better!

No comments:

Post a Comment