In [1]:
%matplotlib inline
from skimage import data, io, morphology
from skimage.color import rgb2hsv, hsv2rgb, rgb2gray
from pylab import *
from skimage.io import Image
from skimage.morphology import square
import skimage as si
import numpy as np
from numpy import array
import matplotlib.pyplot as pl

def show(*args):
    "Show multiple images in a row"
    pl.figure(figsize=(20,12))
    for i,img in enumerate(args):
        pl.subplot(1, len(args), i+1)
        io.imshow(img)
In [2]:
figure(figsize=(15,4))
io.imshow(io.imread('img/morphology.png'))
Out[2]:
<matplotlib.image.AxesImage at 0x10c2071d0>
In [3]:
arr = zeros([7,7],dtype='uint8')
arr[1:6,1:6]=255
arr
Out[3]:
array([[  0,   0,   0,   0,   0,   0,   0],
       [  0, 255, 255, 255, 255, 255,   0],
       [  0, 255, 255, 255, 255, 255,   0],
       [  0, 255, 255, 255, 255, 255,   0],
       [  0, 255, 255, 255, 255, 255,   0],
       [  0, 255, 255, 255, 255, 255,   0],
       [  0,   0,   0,   0,   0,   0,   0]], dtype=uint8)
In [4]:
eroded = morphology.erosion(arr, square(3))
eroded
Out[4]:
array([[  0,   0,   0,   0,   0,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0],
       [  0,   0, 255, 255, 255,   0,   0],
       [  0,   0, 255, 255, 255,   0,   0],
       [  0,   0, 255, 255, 255,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0],
       [  0,   0,   0,   0,   0,   0,   0]], dtype=uint8)
In [5]:
morphology.dilation(eroded, square(3))
Out[5]:
array([[  0,   0,   0,   0,   0,   0,   0],
       [  0, 255, 255, 255, 255, 255,   0],
       [  0, 255, 255, 255, 255, 255,   0],
       [  0, 255, 255, 255, 255, 255,   0],
       [  0, 255, 255, 255, 255, 255,   0],
       [  0, 255, 255, 255, 255, 255,   0],
       [  0,   0,   0,   0,   0,   0,   0]], dtype=uint8)
In [6]:
# Threshold
coins = data.coins()
binary = coins > 150
show(coins, binary)
In [7]:
# Erosion
eroded = Image(morphology.erosion(binary, square(3)))
show(binary, eroded)
In [8]:
# Dilatation
dilated = Image(morphology.dilation(binary, square(3)))
show(binary, dilated)
In [9]:
# Closing (small dark spots were removed)
dilated = Image(morphology.dilation(binary, square(5)))
eroded = Image(morphology.erosion(dilated, square(5)))
show(binary, dilated, eroded)
result = eroded
In [10]:
opened = morphology.opening(result, square(2))
show(result, opened)
In [11]:
horse = rgb2gray(255 - data.horse()) > 0.5

count = 3
eroded = horse
for i in range(count):
    eroded = morphology.erosion(eroded, square(5))

dilated = eroded
for i in range(count):
    dilated = morphology.dilation(dilated, square(5))

show(horse, eroded, dilated)
In [12]:
horse = rgb2gray(255 - data.horse()) > 0.5

count = 3
dilated = horse
for i in range(count):
    dilated = morphology.dilation(dilated, square(5))

eroded = dilated
for i in range(count):
    eroded = morphology.erosion(eroded, square(5))

show(horse, dilated, eroded)