A Comprehensive Guide to Morphological Operations in Image Processing

Gab Alenton
5 min readJun 18, 2023

--

Now we’re going to delve into the fascinating realm of image processing, specifically focusing on a critical technique known as morphological operations. These operations allow us to manipulate the structure or shape of the objects within an image, making them an essential tool in various industries. Whether you’re new to image processing or looking to expand your knowledge, this tutorial will guide you through the basic morphological operations.

What Are Morphological Operations?

Morphological operations manipulate an image based on its shape and structure. They work by convolving a structuring element (also known as a kernel) over the image and applying an operation at each location.

The most fundamental morphological operations include erosion, dilation, opening, and closing. To better understand morphological operations, let’s use a simple binary image of a circle. We will illustrate how the circle image changes with different operations.

import numpy as np
from skimage.draw import disk
import matplotlib.pyplot as plt
from skimage.io import imread, imshow

selem_circ = np.array([[0,1,0],
[1,1,1],
[0,1,0]])
shape = (25, 25)
circ_img = np.zeros(shape, dtype=np.uint8)
rr,cc =disk((12,12),10,shape=shape)
circ_img[rr,cc]=1

First, let’s visualize our original image and the structuring element:

plt.figure(figsize=(10, 10))

plt.subplot(1, 2, 1)
plt.imshow(circ_img, cmap='gray')
plt.title("Original Image")

plt.subplot(1, 2, 2)
plt.imshow(selem_circ, cmap='gray')
plt.title("Structuring Element")

plt.show()

Now, let’s dive into each of these operations and apply them on the circle image to visualize the results:

1. Erosion

Erosion shrinks the foreground objects in an image. The intensity of the erosion depends on the size of the structuring element used. The function for erosion is as follows:

from skimage.morphology import erosion
from skimage.draw import disk

def im_erosion(image, selem, n):
for i in range(n):
image = erosion(image, selem)
return image

2. Dilation

Dilation, the opposite of erosion, enlarges the foreground objects in an image. It is defined as follows:

from skimage.morphology import dilation

def im_dilation(image, selem, n):
for i in range(n):
image = dilation(image, selem)
return image

3. Opening

Opening is an operation that involves erosion followed by dilation. It is useful in removing noise:

from skimage.morphology import opening

def im_opening(image, selem, n):
for i in range(n):
image = opening(image, selem)
return image

4. Closing

Closing is the reverse of opening: it involves dilation followed by erosion. It is useful in closing small holes in the foreground:

from skimage.morphology import closing

def im_closing(image, selem, n):
for i in range(n):
image = closing(image, selem)
return image

Now let us see how these operations work.

from skimage.morphology import erosion, dilation, opening, closing

# Perform morphological operations
image_erosion = im_erosion(circ_img, selem, 5)
image_dilation = im_dilation(circ_img, selem, 5)
image_opening = im_opening(circ_img, selem, 5)
image_closing = im_closing(circ_img, selem, 5)

# Visualize the results
plt.figure(figsize=(15, 15))

plt.subplot(2, 2, 1)
plt.imshow(image_erosion, cmap='gray')
plt.title("Erosion")

plt.subplot(2, 2, 2)
plt.imshow(image_dilation, cmap='gray')
plt.title("Dilation")

plt.subplot(2, 2, 3)
plt.imshow(image_opening, cmap='gray')
plt.title("Opening")

plt.subplot(2, 2, 4)
plt.imshow(image_closing, cmap='gray')
plt.title("Closing")

plt.show()

As you can see, each morphological operation has a distinct effect on the image:

  • Erosion shrinks the circle, removing pixels from its border.
  • Dilation enlarges the circle, adding pixels to its border.
  • Opening (erosion followed by dilation) removes small-scale details from the circle’s border.
  • Closing (dilation followed by erosion) fills small holes in the circle’s body.

By combining these operations in different sequences, we can perform complex image transformations and isolate specific features of interest. For a much interesting example, let us see how we can extract road networks from a map.

Application: Filtering Out Maps for Business Insights

For businesses dealing with logistics, delivery services, or transportation, understanding and analyzing road networks is critical. Here, we will demonstrate how morphological operations can help such businesses by focusing on the road networks in maps. Let us use the map below:

We start with a grayscale version of the map image, then apply a manual threshold to binarize it:

from skimage.color import rgb2gray
from skimage.io import imshow
image_raw = io.imread('map2.PNG')
im = rgb2gray(image_raw[:, :, :3])
im_bw = im > 0.973
imshow(im_bw)

To filter out the roads, we apply a series of morphological operations. We first perform opening to remove small patches of white that are not part of the roads. Then, we apply closing to fill in gaps within the roads:

selem_temp = np.array([[-1, -1, -1, -1],
[-1, 8.5, 8.5, -1],
[-1, 8.5, 8.5, -1],
[-1, -1, -1, -1]])

map1 = im_closing(im_opening(im_bw, selem_temp, 1), selem_temp, 1)
imshow(map1)

The map now has an isolated representation of the road network. However, some roads are still not adequately represented. To refine this, we apply a sequence of erosion and dilation to further disconnect unrelated roads and widen the main roads:

map2 = im_dilation((im_erosion(map1, selem_temp, 2)), selem_temp, 4)
imshow(map2)

Finally, we skeletonize the image to get a single-pixel wide representation of each road, which can help businesses quantify the total length of the road network:

skeleton = skeletonize(map2)
imshow(skeleton)

skel_count = np.sum(skeleton)
print(f'Pixel length of all roads = {skel_count} pixels')

n conclusion, morphological operations form an essential cornerstone of image processing, providing capabilities to extract and emphasize various features within an image. These operations — erosion, dilation, opening, and closing — each serve unique roles and have distinctive effects on the images.

By applying these methods strategically, we can eliminate noise, isolate specific components, and enhance the structures of interest within the image. This forms a critical foundation in applications such as object recognition, edge detection, and feature extraction.

For businesses dealing with image-based data, leveraging these morphological operations can help enhance data analysis, enabling a more targeted approach towards information extraction. For instance, the detailed road network extraction we walked through in this tutorial could greatly benefit industries such as logistics, real estate, and urban planning, amongst others.

Remember, the power of these operations is in their combination and sequence of application. With a solid understanding of morphological operations, businesses can elevate their image processing capabilities, enabling better strategic decision-making.

As always, we encourage you to experiment with these techniques, and happy coding! Stay tuned for more image processing tutorials that guide you towards mastery in this domain.

--

--

Gab Alenton

Entrepreneur turned data enthusiast. Merging business acumen with data science passion 💡