How it works…

from scipy.signal import wiener, medfilt
import matplotlib.pylab as plt
plt.plot(t,signal,'k', label='The signal')
plt.plot(t,wiener(signal,mysize=55),'r',linewidth=3, label='Wiener filtered')
plt.plot(t,medfilt(signal,kernel_size=55),'b',linewidth=3, label='Medfilt filtered')
plt.legend()
plt.show()

This gives us the following graph showing the comparison of smoothing filters (Wiener, in red, is the one that has its starting point just above 0.5 and Medfilt, in blue, has its starting point just below 0.5):

Most of the filters in the scipy.signal module can be adapted to work with arrays of any dimension. In the particular case of images, we prefer to use the implementations in the scipy.ndimage module, since they are coded with these objects in mind. For instance, to perform a median filter on an image for smoothing, we use scipy.ndimage.median_filter. Let us show an example. We will start by loading lena to the array, and corrupting the image with Gaussian noise (zero mean and standard deviation of 16):

from scipy.stats import norm # Gaussian distribution
import matplotlib.pyplot as plt
import scipy.misc
import scipy.ndimage
plt.gray()
lena=scipy.misc.lena().astype(float)
plt.subplot(221);
plt.imshow(lena)
lena+=norm(loc=0,scale=16).rvs(lena.shape)
plt.subplot(222);
plt.imshow(lena)
denoised_lena = scipy.ndimage.median_filter(lena,3)
plt.subplot(224);
plt.imshow(denoised_lena)

The set of filters for images comes in two flavors—statistical and morphological. For example, among the filters of statistical nature, we have the Sobel algorithm oriented to the detection of edges (singularities along curves). Its syntax is as follows:

sobel(image, axis=-1, output=None, mode='reflect', cval=0.0)

The optional parameter, axis, indicates the dimension in which the computations are performed. By default, this is always the last axis (-1). The mode parameter, which is one of the reflectconstantnearestmirror, or wrap strings, indicates how to handle the border of the image, in the case that there is insufficient data to perform the computations there. In case mode is constant, we may indicate the value to use in the border with the cval parameter. Let's look into the following code snippet which illustrates the use of the Sobel filter:

from scipy.ndimage.filters import sobel
import numpy
lena=scipy.misc.lena()
sblX=sobel(lena,axis=0); sblY=sobel(lena,axis=1)
sbl=numpy.hypot(sblX,sblY)
plt.subplot(223);
plt.imshow(sbl)
plt.show()

The following screenshot illustrates the previous two filters in action—Lena (upper-left), noisy Lena (upper-right), edge map with Sobel (lower-left), and median filter (lower-right):

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset