Morphological gradient

using radial line structuring elements


In [1]:
%pylab inline 

import numpy as np
from skimage import data, morphology, draw, img_as_float, io
from matplotlib import pyplot as plt


Populating the interactive namespace from numpy and matplotlib

In [2]:
def show_images(images, titles=None, scale=None):
    """Display a list of images"""
    n_ims = len(images)
    if titles is None:
        titles = ['(%d)' % i for i in range(1,n_ims + 1)]
    fig = plt.figure()
    if scale:
        fig_inch = fig.get_size_inches()*scale
    else:
        fig_inch = fig.get_size_inches()
    n = 1
    for image,title in zip(images,titles):
        a = fig.add_subplot(1,n_ims,n) # Make subplot
        if image.ndim == 2: # Is image grayscale?
            plt.gray() # Only place in this blog you can't replace 'gray' with 'grey'
        plt.imshow(image)
        a.set_title(title)
        n += 1
    fig.set_size_inches(np.array(fig_inch) * n_ims)
    plt.show()

In [3]:
def selemline(length, theta, dtype=np.uint8):
    """Line structuring element"""
    theta_d = theta * np.pi / 180
    X = int(round((length-1)/2. * np.cos(theta_d)))
    Y = int(-round((length-1)/2. * np.sin(theta_d)))
    C, R, V = draw.line_aa(-X, -Y, X, Y)
    M = 2*max(abs(R)) + 1
    N = 2*max(abs(C)) + 1
    selem = np.zeros((M, N)).astype(dtype)
    selem[R + max(abs(R)), C + max(abs(C))] = 1
    return selem

In [4]:
def mm_gradient(img, length, angle):
    """
    Morphology gradient
    http://en.wikipedia.org/wiki/Morphological_gradient
    """
    return morphology.dilation(img, selemline(length, angle)) - morphology.erosion(img, selemline(length, angle))

In [5]:
img = img_as_float(data.camera())
show_images(images=[img]+[mm_gradient(img, 5, 45*x) for x in range(0, 4)],
            titles=['Original']+['Angle: '+str(45*x) for x in range(0, 4)])


C:\Anaconda\lib\site-packages\skimage\util\dtype.py:107: UserWarning: Possible precision loss when converting from float64 to uint8
  "%s to %s" % (dtypeobj_in, dtypeobj))

In [6]:
img = io.imread('http://breckon.eu/toby/fundipbook/materials/gallery/circuit.png')
show_images(images=[img]+[mm_gradient(img, 5, 45*x) for x in range(0, 4)],
            titles=['Original']+['Angle: '+str(45*x) for x in range(0, 4)])



In [7]:
img = io.imread('http://www.mathworks.com/help/images/hough_tut1.gif')
show_images(images=[img]+[mm_gradient(img, 5, 45*x) for x in range(0, 4)],
            titles=['Original']+['Angle: '+str(45*x) for x in range(0, 4)])



In [8]:
img = io.imread('http://thumbs.dreamstime.com/z/circuit-board-vector-computer-seamless-pattern-29487352.jpg')[:, :, 1]
show_images(images=[img]+[mm_gradient(img, 5, 30*x) for x in range(0, 4)],
            titles=['Original']+['Angle: '+str(30*x) for x in range(0, 4)])