Morphological image processing

Also known as: mathematical morphology · erosion and dilation

On this page 7

Morphological image processing is a family of nonlinear, shape-based operations that modify an image by probing it with a small reference shape called a structuring element. In computer vision, and in the wider field of artificial intelligence, it is the standard toolkit for cleaning segmentation masks, separating touching objects, extracting boundaries and measuring shapes.

The approach comes from mathematical morphology, a theory built on set theory and lattice algebra. Its two primitive operators, erosion and dilation, combine into higher-level operators such as opening, closing, the morphological gradient and the top-hat transform. Unlike convolution filters, morphological operators preserve sharp edges because they rely on minimum, maximum and logical operations rather than weighted averages.

How erosion and dilation transform an image

Every morphological operation slides a structuring element across the image and decides each output pixel from the pixels the element covers. The element is a small binary pattern, commonly a 3×3 square, a disk or a line, with a defined origin, usually its center.

In a binary image, erosion keeps a foreground pixel only when the whole structuring element fits inside the foreground, so objects shrink and thin protrusions vanish. Dilation sets a pixel to foreground when the element touches any foreground pixel, so objects grow and small gaps close. In grayscale morphology, erosion becomes a local minimum filter and dilation becomes a local maximum filter.

The table below summarizes the primitive and derived operators that practitioners use most often.

OperatorDefinitionMain effect
ErosionLocal minimum under the elementShrinks objects, removes small specks
DilationLocal maximum under the elementGrows objects, fills small holes
OpeningErosion followed by dilationRemoves noise smaller than the element
ClosingDilation followed by erosionBridges gaps and fills small holes
Morphological gradientDilation minus erosionHighlights object boundaries
Top-hat transformImage minus its openingExtracts small bright details
Black-hat transformClosing minus imageExtracts small dark details
Core morphological operators and their effects

Opening and closing are idempotent: applying the same opening twice gives the same result as applying it once. This property makes them predictable filters, because the outcome depends on the size and shape of the element, not on the number of passes.

Choosing the structuring element

The structuring element is the most important design decision in any morphological pipeline, because it encodes prior knowledge about the shapes to keep or remove. A rule of thumb is that an opening removes every bright structure into which the element cannot fit entirely.

The following table compares common element shapes and the situations in which each one performs well.

Element shapeTypical sizeBest suited for
Square3×3 to 7×7 pixelsFast generic cleanup, axis-aligned structures
Disk or ellipseRadius 2 to 15 pixelsIsotropic filtering of rounded objects
Cross3×3 pixelsFour-connected thinning and gentle smoothing
LineLength 5 to 50 pixelsDetecting or removing oriented strokes
Flat versus non-flatSame footprint, added height valuesGrayscale shaping with weighted profiles
Structuring element shapes and typical uses

Size must be matched to image resolution and object scale. An element that is too small leaves noise behind, while one that is too large merges neighboring objects or deletes thin but meaningful structures such as cracks or blood vessels. Large square and line elements can be decomposed into smaller elements, which keeps processing time nearly constant as the element grows.

Morphological processing sits between low-level filtering and high-level analysis. It usually runs after image thresholding or segmentation and before connected-component labeling or measurement, and it often complements rather than replaces linear filters.

TechniqueOperating principleKey difference from morphology
Image filteringWeighted sums such as Gaussian blurLinear, blurs edges instead of preserving them
Edge detectionIntensity derivatives such as SobelResponds to gradients, not to shape fit
Watershed algorithmFlooding of a topographic surfaceBuilt on morphology, used for splitting objects
Connected-component labelingGrouping of touching pixelsCounts objects that morphology has cleaned
Learned segmentationNeural network pixel classificationData-driven, often refined by morphology
Morphology versus neighboring techniques

Modern deep learning pipelines still rely on morphology for post-processing of predicted masks. A small opening removes isolated false positives, a closing fills pinholes, and a distance transform with watershed separates touching cells or grains that a neural network has labeled as one region.

Advanced operators built on morphology

Beyond the basic four operators, mathematical morphology provides a rich set of reconstruction and skeleton tools. These operators answer questions about connectivity and shape rather than simply growing or shrinking regions.

  • Morphological reconstruction restores whole objects from markers, which allows removal of objects touching the border without distorting the others.
  • Skeletonization reduces shapes to one-pixel-wide center lines that preserve topology, useful for road, fiber and vessel networks.
  • Hit-or-miss transform detects exact pixel patterns such as line ends, junctions or isolated points.
  • Granulometry applies openings of increasing size to estimate the size distribution of particles.
  • Hole filling uses reconstruction from the image border to close interior holes of any size.

Most of these operators are available in OpenCV, scikit-image and MATLAB, and GPU implementations make them practical for real-time video at high resolutions.

Limitations and common mistakes

Morphological operators are fast and transparent, but they are sensitive to scale, orientation and noise type. They assume that shape is the relevant cue, so they perform poorly when objects of interest and noise share the same size.

SymptomLikely causeCorrection
Objects merge togetherElement too large or closing applied firstReduce size or apply opening first
Thin structures disappearOpening with a square elementUse line elements or reconstruction
Shapes become blockySquare element on rounded objectsSwitch to a disk element
Results change across imagesFixed size with varying resolutionScale the element to pixel spacing
Border objects are distortedPadding assumptions at image edgesChoose padding explicitly or crop
Frequent problems and how to correct them

A frequent misconception is that erosion and dilation are inverse operations. They are not: dilation after erosion does not restore the original image, and that information loss is exactly what makes opening a useful filter.

A plain-language summary

Imagine pressing a small coin over every part of a drawing. Where the coin fits fully inside a shape, the shape survives. Where it does not fit, that part is removed. This is the core idea of morphological image processing.

Shrinking shapes is called erosion. Growing them is called dilation. Used together, they remove small specks, fill tiny holes and smooth outlines. The key takeaway is simple: the size and shape of the coin decide what stays in the picture.

An example from practice

A quality-control team in an electronics plant inspects printed circuit boards with a camera at about 20 micrometers per pixel. After thresholding, the copper traces appear white, but dust creates small white specks and scratches open tiny breaks in the traces.

The engineers apply an opening with a 3×3 element to remove specks smaller than about 60 micrometers. They then apply a closing with a short line element aligned with the traces to bridge acceptable hairline gaps. Connected-component labeling counts the traces, and any board with an unexpected count or a trace narrower than its specified width is rejected.

The pipeline runs in a few milliseconds per board and cuts false rejections substantially, because noise no longer looks like a defect while genuine breaks wider than the line element remain visible.