QuiddityML

Morphological operations: erosion, dilation, opening, closing, and connected components

How erosion and dilation test a small shape against a binary mask, how opening and closing remove specks and fill holes, how labeling counts the objects in a cleaned mask, and the SciPy code for each.

Computer VisionBy · 4 December 2026 · 10 min read

Morphological operations change the shape of a black-and-white mask. They slide a small shape over the mask and keep, add or remove each pixel depending on whether that shape fits the white region around it. Masks from thresholding, from a segmentation model or from a person drawing them often come out rough. They have stray specks, pinholes and jagged borders. Morphology cleans those up before anything gets counted or measured.

Binary masks and morphology

A binary mask has two values per pixel: 1 for the foreground, the pixels that belong to an object, and 0 for the background. A mask can mark the cells in a microscope image, the text on a scanned page or a road in a satellite photo.

A blur or an edge filter is a linear filter: it multiplies a window of pixel values by weights and adds them up. A morphological operation works differently. It places a small shape at each pixel and asks a yes-or-no question, such as whether the shape fits entirely inside the foreground there. The answer decides whether that pixel is 1 or 0 in the output.

A white blob on a dark background with a small cross-shaped probe at its border and the question whether the probe shape fits the foreground there.

The structuring element

The small shape is called the structuring element. Like a kernel in a convolution, it is a small grid centered on the current pixel, but it holds a shape instead of weights. The two common 3 by 3 shapes are a square and a cross:

$$\text{square: } \begin{bmatrix} 1 & 1 & 1 \\ 1 & 1 & 1 \\ 1 & 1 & 1 \end{bmatrix}$$

$$\text{cross: } \begin{bmatrix} 0 & 1 & 0 \\ 1 & 1 & 1 \\ 0 & 1 & 0 \end{bmatrix}$$

The 1 entries are the cells that are part of the shape. Disks and straight lines are other common shapes.

A 3 by 3 square, a 3 by 3 cross, a 5 by 5 disk and a 1 by 5 line as grids of 0s and 1s, next to a 3 by 3 blur kernel of 1/9 weights for comparison.

Each shape assumes something

A square treats all directions the same. A horizontal line affects only horizontal structure, which makes it useful for removing thin vertical scan lines while keeping wide horizontal shapes. A disk keeps rounded objects rounded. So the shape you pick is a statement about which structures in the mask are real and should survive.

A square removing specks from a blob, a horizontal line removing vertical scan lines from a bar, and a disk keeping a round cell round where a large square gives it flat sides.

What morphology cannot do

Morphology fixes the shape of a mask you already have. It removes speckle from a scanned document, closes gaps in a medical segmentation and tidies a model's mask before anything gets measured. It cannot decide what an object is or find one in a mask that does not contain it.

A rough mask with speckles and a nick turned into a cleaner mask of the same object, and a mask of scattered dots that morphology cannot turn into an object.

Erosion

Erosion keeps a foreground pixel only if the structuring element, centered there, fits entirely inside the foreground. Pixels near the border of a region fail this test, because part of the shape hangs out over the background. So every region shrinks inward by about the radius of the shape.

Two other things happen. A speck smaller than the structuring element vanishes completely, because the shape fits nowhere inside it. And a bridge thinner than the shape breaks, which splits one region into two.

A 5 by 5 probe that fits deep inside a blob (kept) and one that hangs out at its border (removed), and a whole mask after erosion: the blob is 2 pixels thinner, the speck is gone and the thin bridge between two rectangles is broken.

Erosion traced with a cross

Take a small binary image where 1 is foreground, and the 3 by 3 cross as the structuring element:

$$\begin{bmatrix} 0 & 1 & 1 & 1 & 0 \\ 1 & 1 & 1 & 1 & 1 \\ 1 & 1 & 1 & 1 & 1 \\ 0 & 1 & 1 & 1 & 0 \end{bmatrix}$$

A foreground pixel stays 1 only if all five cells of the cross, the pixel and its four edge neighbors, are foreground. Rows and columns count from 0. Pixels outside the image count as background.

  • The pixel at row 1, column 2 has foreground on all four sides, so it stays 1.
  • The pixel at row 1, column 0 has background above it, so it becomes 0.

Every pixel on the border of the region fails on at least one side, so the result keeps only the 2 by 3 block in the middle:

$$\begin{bmatrix} 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 1 & 1 & 0 \\ 0 & 1 & 1 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 \end{bmatrix}$$

The 4 by 5 input with the cross placed on two pixels, one kept and one removed, and the output where the region shrinks inward by one pixel all around.

Dilation

Dilation does the opposite. It sets a pixel to foreground if the structuring element, centered there, touches any foreground at all. Regions grow outward by about the radius of the shape.

Small holes inside a region get filled, and two blobs closer together than the size of the shape merge into one. Dilation is a way to close a small gap in a boundary or to thicken a thin line.

A blocky blob with a square probe touching its border from outside, and the blob after dilation, larger all around with the original outline drawn inside it.

Erosion and dilation in code

SciPy's scipy.ndimage module has both operations for boolean arrays. generate_binary_structure(2, 1) builds the 3 by 3 cross:

import numpy as np
from scipy.ndimage import (
    binary_erosion, binary_dilation,
    generate_binary_structure)

mask = np.zeros((7, 7), dtype=bool)
# a 3x3 block of foreground
mask[2:5, 2:5] = True

# plus-shaped, 3x3
cross = generate_binary_structure(2, 1)

# 1  (only the center survives)
print(binary_erosion(mask, cross).sum())
# 21 (3x3 block grows a plus-shaped halo)
print(binary_dilation(mask, cross).sum())

Eroding the 3 by 3 block leaves only its center, because at every other cell one arm of the cross hangs into the background. Dilation adds every pixel where the cross touches the block. That adds a row of 3 pixels on each of the four sides, so the 9-pixel block grows to 21 pixels.

The 7 by 7 input with a 3 by 3 block of 1s, the eroded result with a single 1 in the center and the dilated result with 21 ones in a plus-like shape.

Erosion and dilation change labels

A mask is a label: it says which pixels belong to which objects. Erosion can delete a small object that was real. Dilation can merge two objects that should stay separate, or grow a mask past the true border of an object. The bigger the structuring element, the bigger these effects.

So these edits change the areas and counts you measure from the mask. Use the smallest operation that fixes the specific problem, and compare the result with the original.

One mask with 4 cells and 1811 pixels: erosion with a 5 by 5 square deletes the small real cell, leaving 3 objects and 1162 pixels, and dilation merges the two lower cells, leaving 3 objects and 2570 pixels.

Opening and closing

Erosion removes specks, but it also shrinks every real region. Dilation fills holes, but it also grows every region. Running them one after the other, with the same structuring element, keeps the cleanup and undoes most of the change in size.

Opening erodes first and then dilates. The erosion removes specks, thin protrusions and small blobs, and those do not come back in the dilation because there is no foreground left there to grow from. Larger regions shrink and then grow back to roughly their original size.

A blob surrounded by small specks, the eroded blob with the specks gone, and the dilated blob back at its original size with no specks.

Closing dilates first and then erodes. The dilation fills pinholes, hairline cracks and narrow gaps inside an object. The erosion then pulls the outer border back to roughly where it was, and the filled holes stay filled because they are now surrounded by foreground.

A blob with an interior hole and a notch, the dilated blob with both filled, and the eroded result at about the original size with the hole and notch still filled.

Opening and closing on one mask

Take a rough mask: a solid 20 by 20 blob, a stray 2 by 2 speck 10 pixels away and a 3-pixel hole in the middle of the blob. The structuring element is a 5 by 5 square.

Opening, which erodes and then dilates:

  • The erosion removes the 2 by 2 speck completely, since the 5 by 5 square never fits inside it. It also shrinks the blob to 16 by 16.
  • The dilation grows the blob back to 20 by 20, and the speck does not return.

Closing the opened result, which dilates and then erodes:

  • The dilation fills the 3-pixel hole and expands the blob to 24 by 24.
  • The erosion pulls the outer edge back to 20 by 20, and the hole stays filled.

Opening removed the speck, closing filled the hole and the blob kept its size.

The input with a blob, a speck and a small hole, the result after opening with the speck gone, and the result after closing with the hole filled.

Opening and closing in code

import numpy as np
from scipy.ndimage import binary_opening, binary_closing

m = np.zeros((14, 14), dtype=bool)
m[3:10, 3:10] = True     # 7x7 blob
m[6, 6] = False          # a 1-pixel hole
m[2, 12] = True          # a 1-pixel speck

box = np.ones((3, 3), dtype=bool)

opened = binary_opening(m, box)
closed = binary_closing(m, box)
cleaned = binary_closing(opened, box)
print(opened[2, 12], opened[6, 6])    # False False
print(closed[2, 12], closed[6, 6])    # True  True
print(cleaned[2, 12], cleaned[6, 6])  # False True

Each line prints whether the speck pixel and the hole pixel are foreground. Opening removes the speck and leaves the hole open. Closing fills the hole and keeps the speck. Running opening and then closing clears both.

The 14 by 14 grid as input, opened, closed, and opened then closed, with the speck and the hole cell outlined in each.

The size of the shape is a claim about the mask

A common first pass on a rough mask is to open it to remove specks and then close it to fill holes. The size of the structuring element decides what counts as a speck and what counts as a hole. Opening with a shape larger than a real small object deletes that object. Closing across a real thin gap merges two objects that should stay apart.

The operation cannot tell a real small feature from an artifact. So pick the size from what you know about the images, such as the smallest real object you expect to see.

Opening with a large shape deletes a real small object between two larger ones, and closing with a large shape merges two objects across a real gap.

Connected components

A cleaned mask is still one image of 0s and 1s, and it does not say how many objects it holds. A connected component is a largest possible group of foreground pixels that are all linked to each other through neighboring foreground pixels.

Labeling gives each component its own number. The binary mask becomes an image of component numbers, with 0 for the background and a separate number from 1 upward for each region.

A binary mask with a ring-shaped region, a single pixel and a small irregular region, and its labeled version with the regions numbered 1, 2 and 3.

Four neighbors or eight neighbors

"Linked through neighbors" needs a definition of neighbor. It can mean only the pixels that share an edge, which gives four neighbors. It can also include the pixels that share a corner, which gives eight. This choice is called 4-connectivity or 8-connectivity.

With four neighbors, two blobs that touch only at a corner are separate. With eight neighbors they are one blob, so the choice changes the count.

Two 2 by 2 blocks that touch at a corner: two components with four neighbors and one component with eight neighbors.

Labeling one mask both ways

Take two 2 by 2 blocks that meet at a diagonal in the center:

$$\begin{bmatrix} 1 & 1 & 0 & 0 \\ 1 & 1 & 0 & 0 \\ 0 & 0 & 1 & 1 \\ 0 & 0 & 1 & 1 \end{bmatrix}$$

With four neighbors, two pixels link only if they share an edge. The two blocks touch only at the corner between the pixel at row 1, column 1 and the pixel at row 2, column 2. So they stay separate and the count is 2. With eight neighbors a corner touch also links, so the two blocks become one component and the count is 1.

The same 4 by 4 mask labeled with 4-connectivity, giving 2 components, and with 8-connectivity, giving 1.

Connected components in code

scipy.ndimage.label returns the labeled image and the number of components:

import numpy as np
from scipy.ndimage import label

mask = np.array([[1, 1, 0, 0],
                 [1, 1, 0, 0],
                 [0, 0, 1, 1],
                 [0, 0, 1, 1]], dtype=np.uint8)

# default: 4-connectivity
labels4, n4 = label(mask)
# 8-connectivity
labels8, n8 = label(mask, structure=np.ones((3, 3)))
print(n4, n8)          # 2 1
# [4 4]  pixels per component
print(np.bincount(labels4.ravel())[1:])

By default label links only pixels that share an edge, so the two blocks stay separate. Passing a 3 by 3 structure of ones also allows the corner link and merges them. np.bincount counts how many pixels carry each number. Dropping the first count, which belongs to the background label 0, leaves the pixel count of each component. The same step as a function:

def component_sizes(labels):
    flat = labels.ravel()
    counts = np.bincount(flat)
    return counts[1:]

The mask, its 4-connectivity labels 1 and 2 with 2 components, and its 8-connectivity labels with 1 component.

Counting and filtering objects

The number of components is the number of separate objects in the mask. Counting cells under a microscope, items on a conveyor or characters on a page all come down to thresholding an image and then counting components.

Once each component has a number, you can measure its area, its bounding box and its center. Then keep only the components above a size, or inside a region of interest, and drop the rest.

A mask with 8 cells and 5 tiny specks labeled as 13 components, and the same mask after keeping only components of 30 pixels or more: 8 cells, each with its bounding box and its area in pixels.

When to use morphology, and common mistakes

Use morphology on a mask that is roughly right and needs cleanup: specks from noise, small holes, jagged borders or thin gaps. Open to remove specks, close to fill holes and label to count. If the mask is wrong in a bigger way, such as missing half an object, fix the threshold or the model that produced it.

  • Using a structuring element larger than the smallest real object. Opening deletes that object, and the count drops without any error.
  • Opening when you meant closing. Opening removes small foreground and closing removes small background. A mask with holes needs closing.
  • Forgetting that erosion and dilation change areas. Erosion alone shrinks every region and dilation alone grows it. If you report areas, use opening or closing, which keep sizes roughly the same, and compare with the original mask.
  • Counting with the wrong connectivity. Objects that touch at a corner count once with eight neighbors and twice with four. Pick the definition that matches what an object is in your images.
  • Counting specks as objects. Labeling counts every foreground group, including 1-pixel noise. Filter by area before reporting a count.

Masks often come from thresholding a grayscale image, which Classical image processing covers along with brightness and contrast. A structuring element slides over the image like a convolution kernel, and Image convolution explained covers that sliding window, padding and stride. Contours, the ordered boundary points of a region, are in Edge detection explained.

QuiddityML teaches morphological operations and connected components in the classical image processing unit of its Computer Vision track. The exercises there include writing component_sizes from scratch and predicting what an opening with too large a shape does to a small real object (QuiddityML).