#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Example showing the use of a median image filter to remove 'salt and
pepper' noise. May be of particular interest for vibrometer scans. 
'''
from scipy import misc, signal
import pylab as plt

# Read in the wikipedia image
image = misc.imread('Noise_salt_and_pepper.png')

# Plot the image to show S&P noise 
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.imshow(image, cmap=plt.cm.gray)
fig1.suptitle('Original Image')

'''
Note: Can see image with very bright white or black pixels - this
is salt and pepper noise. These very large (or small) values will
massive skew the mean, so moving average filters won't work. But can
use the median to elimate these large values.
'''

# Now apply median filter of various sizes
filtered1 = signal.medfilt(image, 3) # 3x3 kernel
filtered2 = signal.medfilt(image, 15) # 15x15 kernel

# Plot the filtered images
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
ax2.imshow(filtered1, cmap=plt.cm.gray)
fig2.suptitle('3x3 Median Filter')

fig3 = plt.figure()
ax3 = fig3.add_subplot(111)
ax3.imshow(filtered2, cmap=plt.cm.gray)
fig3.suptitle('15x15 Median Filter')

plt.show()
