Convolution demo

In [1]:
# Load neccessary python modules
from skimage import io, color, filter,transform # skimage is an image processing library
import matplotlib.pyplot as plt # matplotlib provides plot functions similar to MATLAB
import numpy as np # numpy provides efficient matrix implementation in python
from scipy import signal # scipy provides scientific computing functions
from IPython.html.widgets.interaction import interact 
# interact function can create an interactive interface to allow user to manipulate parameters and see the result, 
# similar to "Manipulate" in Mathematica

%matplotlib inline 
# configuration of matplotlib

$r(x,y)=\int l(x',y') k(x'-x,y'-y)dx'dy' = l*r$

1. Prepare data

Create a disk image and load a natural image for the visualization of convolution

In [2]:
# Load a natural image
im = io.imread('pic/Zebra_running_Ngorongoro.jpg');
zebraIm = color.rgb2grey(im)
# Show image
plt.figure(); io.imshow(zebraIm)

2. Make a square kernel of size 2*r+1, and use it to blur the natural image

In [3]:
def SquareKernel(r):
    w = 2*r + 1
    return np.ones((w,w)) / (w**2)

im = zebraIm
def AdjustKernelRadius(r):
    fim = signal.convolve2d(im, SquareKernel(r))
    io.imshow(fim)
interact(AdjustKernelRadius, r=(1,10))

3. Emphasize locations of intensity change by using a 3x3 kernel to approximate a second-order derivative

In [4]:
filter1 = np.array([[1,1,1], [1,-8,1], [1,1,1]])
plt.figure(); io.imshow(signal.convolve2d(zebraIm, filter1))

4. Define horizontal and vertically oriented gabor filters. Apply them to the zebra image.

In [5]:
fVertical = np.array([[-1,-1,-1], [2,2,2], [-1,-1,-1]])
fHorizontal = np.array([[-1,2,-1], [-1,2,-1], [-1,2,-1]])
plt.figure(); io.imshow(signal.convolve2d(zebraIm, fVertical))
plt.figure(); io.imshow(signal.convolve2d(zebraIm, fHorizontal))

"Zebra running Ngorongoro" by Muhammad Mahdi Karim (www.micro2macro.net)

In [8]:
type(zebraIm)
Out[8]:
numpy.ndarray
In [ ]: