This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.

11.2. Applying filters on an image

  1. Let's import the packages.
In [ ]:
import numpy as np
import matplotlib.pyplot as plt
import skimage
import skimage.filter as skif
import skimage.data as skid
import matplotlib as mpl
%matplotlib inline
  1. We create a function that displays a grayscale image.
In [ ]:
def show(img):
    plt.figure(figsize=(4,2));
    plt.imshow(img, cmap=plt.cm.gray);
    plt.axis('off')
    plt.show();
  1. Now, we load the Lena image (bundled in scikit-image). We select a single RGB component to get a grayscale image.
In [ ]:
img = skimage.img_as_float(skid.lena())[...,0]
In [ ]:
show(img)
  1. Let's apply a blurring Gaussian filter to the image.
In [ ]:
show(skif.gaussian_filter(img, 5.))
  1. We now apply a Sobel filter that enhances the edges in the image.
In [ ]:
sobimg = skif.sobel(img)
show(sobimg)
  1. We can threshold the filtered image to get a sketch effect. We obtain a binary image that only contains the edges. We use a notebook widget to find an adequate thresholding value.
In [ ]:
from IPython.html import widgets
@widgets.interact(x=(0.01, .4, .005))
def edge(x):
    show(sobimg<x)
  1. Finally, we add some noise to the image to illustrate the effect of a denoising filter.
In [ ]:
img = skimage.img_as_float(skid.lena())
# We take a portion of the image to show the details.
img = img[200:-100, 200:-150]
# We add Gaussian noise.
img = np.clip(img + .3 * np.random.rand(*img.shape), 0, 1)
In [ ]:
show(img)
  1. The denoise_tv_bregman function implements total-variation denoising using split-Bregman optimization.
In [ ]:
show(skimage.restoration.denoise_tv_bregman(img, 5.))

You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).

IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).