Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 54 ยท Image Processing

Morphological Operations

Learn erosion, dilation, opening, closing, gradient and top-hat in OpenCV, how structuring elements work, and run binary morphology written in numpy.

After thresholding, a binary image is rarely clean. Objects have small holes, the background has isolated specks, and two shapes that should be separate touch each other by a thin bridge. Morphological operations fix these problems by probing the image with a small shape, the structuring element, and deciding each output pixel from what the probe finds beneath it.

Two operations form the basis: erosion shrinks white regions and dilation grows them. Every other operation in this lesson is a combination of those two. As elsewhere in this track, cv2 cannot run here, so the OpenCV calls are read-only and each idea has a numpy version you can run and edit.

Erosion and dilation

Think of the structuring element as a stamp. For erosion, the output pixel is white only if the stamp, centered on it, fits entirely inside white pixels. The effect: white regions lose a layer of pixels around their edges, thin lines disappear, and tiny specks vanish. For dilation, the output is white if the stamp touches at least one white pixel. White regions grow, small holes fill in, and nearby shapes may merge.

Python
import cv2
import numpy as np

kernel = np.ones((3, 3), np.uint8)

eroded  = cv2.erode(binary, kernel, iterations=1)
dilated = cv2.dilate(binary, kernel, iterations=1)

For a binary image, erosion takes the minimum of the pixels under the kernel's ones and dilation takes the maximum. That formulation also works for grayscale images, which is how OpenCV handles them: erode darkens bright details and dilate expands them. iterations repeats the operation. The foreground must be white (255) on black (0); if your objects are dark, invert the threshold first.

Two basic moves

Erode Shrinks white. Removes specks and thin lines.
Dilate Grows white. Fills holes and joins gaps.

Erosion and dilation are opposites, but not exact inverses.

1 / 2

Opening and closing

Erosion followed by dilation is opening: the erosion deletes specks and thin whiskers, and the dilation then restores the surviving shapes to about their original size. Dilation followed by erosion is closing: the dilation fills small holes and narrow cracks, and the erosion brings the outline back. Neither is an exact undo of the other, so results differ from the original only where small features existed, and that is the whole point.

Python
opened = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)
closed = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)

A good rule: use opening to remove white noise on a black background, and closing to remove black noise inside white objects.

Here the operations are written in numpy, using the same minimum and maximum definitions. The helper treats pixels outside the image as neutral (white for erosion and black for dilation), matching OpenCV's default border handling, so shapes touching the edge are not eroded away.

Python Erode, dilate, open and close a binary shape

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Opening removes the two specks and the one-pixel-thin whisker, but leaves the blob and its hole, since the hole is black and opening only removes white details. Closing fills the hole and keeps the specks, which are white and cannot be removed by dilating and eroding. Running both, opening first, cleans both kinds of noise. In practice you combine them: open to remove specks, then close to repair the objects.

Structuring elements

You choose the stamp's shape and size with cv2.getStructuringElement:

Python
rect    = cv2.getStructuringElement(cv2.MORPH_RECT,    (5, 5))
cross   = cv2.getStructuringElement(cv2.MORPH_CROSS,   (5, 5))
ellipse = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))

The ellipse for (5, 5) is the following 0/1 matrix:

Python
[[0, 0, 1, 0, 0],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [0, 0, 1, 0, 0]]

The shape sets the shape of the growth: a rectangle makes dilated shapes squarer, a cross grows only horizontally and vertically, an ellipse gives rounder, more natural results. A wider kernel removes bigger specks, and a non-square kernel such as (15, 1) preserves only horizontal structures, which is a classic way to find long horizontal lines such as table rules.

Gradient, top-hat and black-hat

Subtracting the basic results gives more tools:

  • Morphological gradient: dilate - erode. On a binary shape it leaves a band of roughly one kernel width along the boundary, an outline of the object.
  • Top-hat: original - opening. Opening removes bright details smaller than the kernel, so the difference is exactly those small bright details. It also flattens uneven lighting.
  • Black-hat: closing - original. The same idea for small dark details on a bright background.
Python
grad  = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel)
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
blackhat = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel)

The following example builds a grayscale image with a sloping background and two small bright spots, a setup where plain thresholding fails because the background itself varies. The top-hat ignores the slope, because it is wider than the kernel, and keeps the spots.

Python Gradient outline and top-hat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The gradient prints a ring two pixels thick, one pixel outside the original edge and one inside, because it is the dilated square minus the eroded square. In the grayscale part, the opening follows the slope but cuts off the spots, so the top-hat is 60 at the first spot and zero elsewhere along that row (the printed row samples every third column). The top-hat is also nonzero at columns 20, 28 and 29: the second spot, plus a small residue of 8 where the slope meets the right border, because erosion and dilation treat outside pixels as neutral and cut the end of a ramp. The first spot has value 104, below the brightest background pixel (136), so no single global threshold finds both spots, while the top-hat makes them stand out against a nearly zero background.

Iterations versus kernel size

iterations=2 with a 3 by 3 rectangle gives the same result as one pass with a 5 by 5 rectangle, since each pass extends the reach by one pixel on every side. Several small passes are often cheaper and give you finer control than one big kernel. The check below confirms the equivalence for a rectangle, and shows how the footprint changes with the kernel shape when you dilate a single pixel.

Python Footprints of kernels, and iterations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The three footprints show the shape of each kernel, and the final line prints True.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You thresholded a photo and the white objects are covered with tiny white specks on a black background. Which operation removes them?

    Opening erodes first, which deletes small white specks, and then dilates to restore the objects that survived.
  2. 2. What does a pixel's output become in erosion with a 3x3 kernel of ones?

    Erosion takes the minimum under the kernel, so a pixel stays white only if every pixel under the kernel is white.
  3. 3. How is the morphological gradient computed?

    Dilate grows the shape and erode shrinks it, so their difference is a band along the boundary. Original minus opening is the top-hat.
  4. 4. A binary image has small black holes inside white objects. Which operation closes them?

    Closing dilates first, which fills small black regions, then erodes to bring the object boundaries back.
  5. 5. Which kernel preserves only long horizontal structures when used for opening?

    In OpenCV the size tuple is (width, height), so (15, 1) is a row of 15 pixels. Only structures at least that wide survive the opening.

Summary

  • Morphology probes a binary or grayscale image with a structuring element; erosion takes the minimum and dilation the maximum under it.
  • Opening (erode, dilate) removes small white specks; closing (dilate, erode) fills small black holes.
  • Gradient is dilate minus erode (an outline), top-hat is image minus opening (small bright details), black-hat is closing minus image.
  • cv2.getStructuringElement builds rectangle, cross or ellipse kernels; the size is (width, height).
  • Repeating a 3 by 3 rectangle n times equals one rectangle of size 2n + 1.

Next up: Arithmetic, Bitwise Ops and Masking.