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 packagesimport osfrom PIL import Image, ImageFilterimport numpy as npimport scipy as spimport matplotlib.pyplot as pltfrom scipy.ndimage import filtersfrom scipy import signalfrom scipy import misc# Ensure plots embeded in notebook%matplotlib inline
In [2]:
# Open original imageimg = 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 graydef rgb2gray(rgb):    r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b    return grayim = rgb2gray(img)plt.imshow(im, cmap='gray')plt.show()
In [3]:
# Add noise to the imagenoise_sigma = 50s_vs_p = 0.5amount = 0.04noisy_im = im# Generate Salt '1' noisenum_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' noisenum_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] = 0plt.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 oddplt.imshow(repaired_im, cmap='gray', vmin=0, vmax=255)plt.show()# Looks Better!
In [5]:
# Sharpen immagealpha = 6filter_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!

Published: September 09 2016

• category:
• tags: