TExcelTAD
Home › Computer Vision: Images to Detection, Segmentation & Tracking › Morphology, Connected Components and Contours

Morphology, Connected Components and Contours

A threshold or a colour rule gives a binary mask: one bit per pixel, "object" or "not". Real masks are messy: specks of noise, holes where a highlight was, two objects joined by a thin bridge, one object split by a shadow. And a mask is still not a list of objects: to count coins, measure cells or draw boxes you need to group pixels into regions and describe each region. Mathematical morphology cleans masks with set operations, connected-component labelling turns a mask into numbered regions, and contours describe each region's outline (area, perimeter, bounding box, shape). Together they are the bridge from pixels to the objects that annotation and detection work with.

Erosion and dilation

Take a binary image AA (the set of foreground pixels) and a small structuring element BB, for example a 3×33 \times 3 square centred on the origin. Write BpB_p for BB moved to pixel pp. Then

A⊖B={ p:Bp⊆A },A⊕B={ p:Bp∩A≠∅ }A \ominus B = \{\, p : B_p \subseteq A \,\}, \qquad A \oplus B = \{\, p : B_p \cap A \ne \emptyset \,\}

Erosion (⊖\ominus) keeps a pixel only if the whole element fits inside the foreground there: objects shrink, specks and thin bridges vanish. Dilation (⊕\oplus) sets a pixel if the element touches the foreground anywhere: objects grow, holes and gaps fill. On a binary image they are a minimum and a maximum filter. Combined:

A∘B=(A⊖B)⊕B(opening),A∙B=(A⊕B)⊖B(closing)A \circ B = (A \ominus B) \oplus B \quad \text{(opening)}, \qquad A \bullet B = (A \oplus B) \ominus B \quad \text{(closing)}

Opening removes everything smaller than the element and keeps the rest at its size; closing fills holes and gaps smaller than the element. The difference (A⊕B)−(A⊖B)(A \oplus B) - (A \ominus B) is the morphological gradient, a band along the outline.

python · try it yourself
import numpy as np
import cv2
from numpy.lib.stride_tricks import sliding_window_view
cv2.setLogLevel(0)

pattern = ["............................",
           "............................",
           "..#######...................",
           "..#######...#...............",
           "..#######.....#####..#####..",
           "..###.###.....#####..#####..",
           "..#######.....#############.",
           "..#######.....#####..#####..",
           "..#######.....#####..#####..",
           "............................",
           "............................"]
A = np.array([[c == "#" for c in row] for row in pattern], np.uint8)
K = np.ones((3, 3), np.uint8)                                          # 3 x 3 square element

def erode(a, k):
    p = np.pad(a, 1, constant_values=1)            # outside counts as foreground, as OpenCV's default
    return sliding_window_view(p, k.shape)[..., k > 0].all(-1).astype(np.uint8)
def dilate(a, k):
    p = np.pad(a, 1, constant_values=0)
    return sliding_window_view(p, k.shape)[..., k > 0].any(-1).astype(np.uint8)

ops = {"original": A, "erode": erode(A, K), "dilate": dilate(A, K),
       "open": dilate(erode(A, K), K), "close": erode(dilate(A, K), K)}
ref = {"erode": cv2.erode(A, K), "dilate": cv2.dilate(A, K),
       "open": cv2.morphologyEx(A, cv2.MORPH_OPEN, K), "close": cv2.morphologyEx(A, cv2.MORPH_CLOSE, K)}
print("matches OpenCV:", {k: bool(np.array_equal(ops[k], v)) for k, v in ref.items()})
for group in [["original", "open", "close"], ["erode", "dilate"]]:
    print("   ".join(f"{n:28s}" for n in group))
    for r in range(A.shape[0]):
        print("   ".join("".join("#" if v else "." for v in ops[n][r]) for n in group))
print("pixels:", {n: int(v.sum()) for n, v in ops.items()})
print("components (8-connected):", {n: cv2.connectedComponents(v, connectivity=8)[0] - 1 for n, v in ops.items()})
matches OpenCV: {'erode': True, 'dilate': True, 'open': True, 'close': True}
original                       open                           close
............................   ............................   ............................
............................   ............................   ............................
..#######...................   ..#######...................   ..#######...................
..#######...#...............   ..#######...................   ..#######...#...............
..#######.....#####..#####..   ..#######.....#####..#####..   ..#######.....############..
..###.###.....#####..#####..   ..###.###.....#####..#####..   ..#######.....############..
..#######.....#############.   ..#######.....#####..#####..   ..#######.....##############
..#######.....#####..#####..   ..#######.....#####..#####..   ..#######.....############..
..#######.....#####..#####..   ..#######.....#####..#####..   ..#######.....############..
............................   ............................   ............................
............................   ............................   ............................
erode                          dilate
............................   ............................
............................   .#########..................
............................   .#########.###..............
...#####....................   .#########.################.
...#...#....................   .#########.################.
...#...#.......###....###...   .#########...###############
...#...#.......###....###...   .#########...###############
...#####.......###....###...   .#########...###############
............................   .#########...##############.
............................   .#########...##############.
............................   ............................
pixels: {'original': 102, 'erode': 34, 'dilate': 189, 'open': 98, 'close': 112}
components (8-connected): {'original': 3, 'erode': 3, 'dilate': 2, 'open': 3, 'close': 3}

The pattern has a 7×77 \times 7 block with a one-pixel hole, a single-pixel speck, and two 5×55 \times 5 blocks two pixels apart, joined by a one-pixel bridge that sticks out one pixel on the right. Both implementations agree with OpenCV. Opening removes the speck, the bridge and the stub (98 of 102 pixels remain, as three regions: the holed block and the two now separate blocks); the holed block survives with its hole, because its eroded ring grows back to the original. Closing fills the hole, keeps the speck, and fills the two-pixel gap between the right-hand blocks, fusing them into one wide block: a gap narrower than the element counts as a hole. Erosion alone turns the holed block into a thin ring and the right blocks into 3×33 \times 3 cores; dilation grows everything until the speck merges with the right-hand blocks (two regions left). Each operation is idempotent once applied (opening an opened image changes nothing), and the element's size and shape are the parameters: a disc (cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k, k))) for round objects, a line for removing horizontal scratches. On grey images the same definitions become a minimum filter (erosion) and a maximum filter (dilation); the top-hat img - opening(img) with a large element removes a slowly varying background.

Connected components

A connected component is a maximal set of foreground pixels that can be reached from each other by steps to neighbouring foreground pixels. "Neighbour" has two common definitions:

4-connectedup, down, left, right 8-connecteddiagonals too touching at a corner4-conn.: 2 regions, 8-conn.: 1

Labelling is a graph search (flood fill) or a two-pass union-find over the pixels; cv2.connectedComponentsWithStats does it in one call and also returns, per component, its bounding box (x, y, w, h), its pixel area and its centroid. Label 0 is the background. The coins image is the classic test: 24 coins on a background whose brightness varies across the image.

python · try it yourself
import numpy as np
import cv2
from scipy import ndimage
from skimage import data
cv2.setLogLevel(0)

img = data.coins()                                                    # (303, 384), 24 coins
def components(bw, min_area=100):
    n, lab, st, cen = cv2.connectedComponentsWithStats(bw.astype(np.uint8), connectivity=8)
    big = [i for i in range(1, n) if st[i, cv2.CC_STAT_AREA] >= min_area]
    return n - 1, big, st

t, otsu = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
n, big, st = components(otsu)
largest = max(big, key=lambda i: st[i, cv2.CC_STAT_AREA])
x, y, w, h, a = st[largest].tolist()
print(f"Otsu t={t:.0f}: {n} components, {len(big)} with >= 100 px; largest {a} px, box {[x, y, x + w, y + h]}")

ell = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
edges = cv2.Canny(cv2.GaussianBlur(img, (5, 5), 1.5), 30, 90)       # outlines do not depend on the light level
closed = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, ell)               # close small gaps in each outline
filled = ndimage.binary_fill_holes(closed > 0).astype(np.uint8)     # fill each closed outline
opened = cv2.morphologyEx(filled, cv2.MORPH_OPEN, ell)              # remove leftover edge fragments
for name, m in [("Canny edges", edges), ("closed", closed), ("filled", filled), ("opened", opened)]:
    n, big, st = components(m)
    print(f"{name:12s} foreground {int((m > 0).sum()):6d} px, {n:3d} components, {len(big):2d} with >= 100 px")

n, lab, st, cen = cv2.connectedComponentsWithStats(opened, connectivity=8)
coins = [i for i in range(1, n) if st[i, cv2.CC_STAT_AREA] >= 100]
areas = st[coins, cv2.CC_STAT_AREA]
print("coin areas: min", int(areas.min()), "median", int(np.median(areas)), "max", int(areas.max()))
for i in sorted(coins, key=lambda i: (round(cen[i][1] / 75), cen[i][0]))[:3]:       # top row, left to right
    x, y, w, h, a = st[i].tolist()
    print(f"  label {i}: box {[x, y, x + w, y + h]}, area {a}, centroid ({cen[i][0]:.1f}, {cen[i][1]:.1f})")
def ascii(mask, rows=20, cols=64):
    H, W = mask.shape
    for r in range(rows):
        print("".join("#" if mask[r * H // rows:(r + 1) * H // rows, c * W // cols:(c + 1) * W // cols].mean() > 0.4 else "." for c in range(cols)))
print("Otsu mask:"); ascii(otsu > 0)
print("edges, closed, filled, opened:"); ascii(opened > 0)
Otsu t=107: 96 components, 24 with >= 100 px; largest 8792 px, box [0, 0, 296, 76]
Canny edges  foreground   9671 px, 176 components, 34 with >= 100 px
closed       foreground  20259 px,  28 components, 24 with >= 100 px
filled       foreground  41155 px,  25 components, 24 with >= 100 px
opened       foreground  41081 px,  25 components, 24 with >= 100 px
coin areas: min 1144 median 1573 max 3257
  label 5: box [22, 34, 68, 75], area 1431, centroid (44.2, 54.5)
  label 6: box [81, 39, 121, 75], area 1166, centroid (100.3, 56.2)
  label 2: box [131, 28, 180, 74], area 1747, centroid (155.3, 50.9)
Otsu mask:
#################################################...............
#######################...#..###....................#######.....
#################......######....######.....####...##########...
###########...######..########..########...######..##########...
#...######....######...######....######.....####.....######.....
................................................................
...........................................#####................
.....######....#####....####....#####....########....######.....
....#######...######..#######..######....########....######.....
.....####......###......####.....##..........##........###......
........................................................#####...
..................................####.......##......##########.
....######....#######..######...#######...#######....##########.
....######....######...######...#######...#######.....#########.
................................................................
......####......................................................
...#########.....####....########.....######...#######....####..
...#########...########.#########....########.########..#######.
....#######.....######...#######......######...######...#######.
................................................................
edges, closed, filled, opened:
................................................................
....................................................########....
......####.............######....######.....#####..##########...
....#######...######..########..########...#######.##########...
....######....######...######....######.....#####....######.....
................................................................
...........................................#####................
.....######....#####...#####...######....########....######.....
....#######...######..#######..#######...########....######.....
.....####......####.....####.....###........###........###......
.......................................................######...
................##...............#####......###......##########.
....######...########..######..########...#######...###########.
....######...########..######...#######...#######....##########.
................................................................
.....#####......................................................
...#########.....#####..#########....#######...#######....####..
...#########...########.##########...########.########..########
....#######.....######...########.....######..########..########
................................................................

The Otsu mask also has 24 regions of at least 100 pixels, but that is a coincidence. The largest of them, 8,792 pixels with the box [0, 0, 296, 76], is the bright upper part of the background with the top row of coins fused into it (the top rows of the ASCII preview), and other regions are fragments of coins. Edges do not care about the absolute brightness, only about change, so the second pipeline starts from Canny outlines: closing seals small gaps in each ring (176 edge fragments become 28 regions), hole filling turns each closed ring into a solid disc (the foreground doubles from 20,259 to 41,155 pixels), and opening smooths the outlines; one fragment below 100 pixels is left, and the area filter drops it. The result is 24 regions, one per coin as the second preview shows, with areas from 1,144 to 3,257 pixels and a box and centroid each. When objects touch, no amount of opening separates them cleanly; that needs the distance transform and the watershed (instance segmentation).

Contours: outlines and shape measurements

A contour is the boundary of a region as a list of pixel coordinates. cv2.findContours traces them (Suzuki and Abe's border-following algorithm); RETR_EXTERNAL returns only outer boundaries, RETR_TREE also the holes and their nesting, and CHAIN_APPROX_SIMPLE stores only the corner points of straight runs. From a contour come the usual shape measurements:

Measurement OpenCV Note
area cv2.contourArea(c) polygon area through the boundary pixel centres: smaller than the pixel count
perimeter cv2.arcLength(c, True) length of that polygon
bounding box cv2.boundingRect(c) → (x, y, w, h) [x, y, x + w, y + h] in this course's exclusive format
rotated box cv2.minAreaRect(c) centre, size, angle
polygon cv2.approxPolyDP(c, eps, True) Douglas–Peucker simplification with tolerance eps
circularity 4πA/P24\pi A / P^2 1 for a circle, π/4≈0.785\pi/4 \approx 0.785 for a square, about 0.6 for an equilateral triangle

The next example runs this on 40 generated scenes (the course's make_scene: squares, circles and triangles on a noisy background, with ground-truth boxes, labels and masks). It takes the union of the objects' masks as "a segmentation", finds the outer contours, and checks two things: whether the contour boxes reproduce the ground-truth boxes, and whether shape measurements alone can tell the three classes apart.

python · try it yourself
import numpy as np
import cv2
cv2.setLogLevel(0)

CLASSES = ["square", "circle", "triangle"]

def make_scene(rng, size=64, max_objects=3):
    """Noisy grey background with 1..max_objects shapes that do not touch.
    Returns RGB uint8 image, boxes (n, 4) as [x1, y1, x2, y2] with x2, y2 exclusive,
    labels (n,) indices into CLASSES, masks (n, size, size) bool."""
    img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
    n = int(rng.integers(1, max_objects + 1))
    boxes, labels, masks = [], [], []
    for _ in range(100):
        if len(boxes) == n:
            break
        s = int(rng.integers(12, 25)); x = int(rng.integers(0, size - s)); y = int(rng.integers(0, size - s))
        if any(x < b[2] + 2 and b[0] < x + s + 2 and y < b[3] + 2 and b[1] < y + s + 2 for b in boxes):
            continue
        c = int(rng.integers(0, 3)); m = np.zeros((size, size), np.uint8)
        if c == 0:
            cv2.rectangle(m, (x, y), (x + s - 1, y + s - 1), 1, -1)
        elif c == 1:
            cv2.circle(m, (x + s // 2, y + s // 2), s // 2, 1, -1)
        else:
            cv2.fillPoly(m, [np.array([[x + s // 2, y], [x, y + s - 1], [x + s - 1, y + s - 1]], np.int32)], 1)
        img[m > 0] = rng.integers(0, 256, 3)
        ys, xs = np.nonzero(m)
        boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
        labels.append(c); masks.append(m > 0)
    return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)

rng = np.random.default_rng(0)
rows = []
for i in range(40):
    img, boxes, labels, masks = make_scene(rng)
    union = masks.any(0).astype(np.uint8)                              # a segmentation mask
    contours, _ = cv2.findContours(union, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for cnt in contours:
        x, y, w, h = cv2.boundingRect(cnt)
        box = [x, y, x + w, y + h]                                     # exclusive x2, y2
        j = [k for k, b in enumerate(boxes.tolist()) if b == box]
        area, per = cv2.contourArea(cnt), cv2.arcLength(cnt, True)
        pix = int(union[y:y + h, x:x + w].sum())
        rows.append((i, box, j[0] if j else -1, labels[j[0]] if j else -1, area, pix, per, 4 * np.pi * area / per ** 2,
                     len(cv2.approxPolyDP(cnt, 0.04 * per, True))))
print("objects:", len(rows), "| contour box == ground-truth box:", sum(r[2] >= 0 for r in rows))
for r in rows[:4]:
    print(f"scene {r[0]} box {r[1]} {CLASSES[r[3]]:8s} contourArea {r[4]:6.1f} pixels {r[5]:4d} perimeter {r[6]:6.1f} circularity {r[7]:.3f} vertices {r[8]}")
for c in range(3):
    sel = [r for r in rows if r[3] == c]
    ci = np.array([r[7] for r in sel]); v = sorted(set(int(r[8]) for r in sel))
    print(f"{CLASSES[c]:8s} n={len(sel):2d} circularity {ci.min():.3f}..{ci.max():.3f} | polygon vertices {v} | contourArea / pixels {np.mean([r[4] / r[5] for r in sel]):.3f}")

def by_vertices(r):
    return 2 if r[8] == 3 else (0 if r[8] == 4 else 1)
def by_circularity(r):
    return 1 if r[7] >= 0.795 else (0 if r[7] >= 0.66 else 2)
for name, rule in [("vertex count", by_vertices), ("circularity", by_circularity)]:
    print(f"rule '{name}': {sum(rule(r) == r[3] for r in rows)} / {len(rows)} correct")
objects: 73 | contour box == ground-truth box: 73
scene 0 box [32, 9, 56, 33] square   contourArea  529.0 pixels  576 perimeter   92.0 circularity 0.785 vertices 4
scene 1 box [49, 8, 63, 22] square   contourArea  169.0 pixels  196 perimeter   52.0 circularity 0.785 vertices 4
scene 1 box [28, 1, 41, 14] circle   contourArea   96.0 pixels  113 perimeter   38.6 circularity 0.809 vertices 4
scene 2 box [34, 35, 48, 49] square   contourArea  169.0 pixels  196 perimeter   52.0 circularity 0.785 vertices 4
square   n=25 circularity 0.785..0.785 | polygon vertices [4] | contourArea / pixels 0.887
circle   n=20 circularity 0.800..0.859 | polygon vertices [4, 8] | contourArea / pixels 0.888
triangle n=28 circularity 0.539..0.539 | polygon vertices [3] | contourArea / pixels 0.828
rule 'vertex count': 59 / 73 correct
rule 'circularity': 73 / 73 correct

Every one of the 73 contour boxes equals the ground-truth box exactly: boundingRect returns (x, y, w, h) and [x, y, x + w, y + h] is the same exclusive format the generator uses. This is how polygon and mask annotations become box annotations, and how a segmentation model's output becomes detections.

The measurements need care. contourArea is 11–17 % smaller than the pixel count (ratios 0.887, 0.888 and 0.828), because the polygon runs through the centres of the boundary pixels and cuts off half a pixel all around; for small objects that is a large error, so count pixels when you need the area. Shape descriptors separate the classes here, but with thin margins. The vertex count of the simplified polygon gets 59 of 73 right: triangles always give 3 and squares 4, but small digital circles simplify to 4 or 8 vertices. Circularity gets all 73, because axis-aligned squares score exactly π/4=0.785\pi/4 = 0.785, triangles 0.539 and the circles 0.800–0.859; the gap between squares and circles is 0.015, and a rotated or noisy square would close it. Hand-made shape rules work on controlled images (parts on a conveyor belt); for anything less controlled, the classes are learned (image classification).

Pitfalls

  • Polarity. OpenCV's morphology and contour functions treat non-zero as foreground. If the objects are dark on a bright background, invert the mask first, or "erosion" will grow them.
  • Connectivity. 4- and 8-connectivity give different counts when objects touch at corners; state which one you use, and use the same one in labelling and evaluation.
  • Element size. Opening with an element larger than the smallest real object deletes it; closing with one larger than the gap between two objects merges them.
  • Border effects. OpenCV's erosion treats the outside as foreground (objects touching the border are not eroded from that side), dilation treats it as background. Pad explicitly if you need something else.
  • Contour area versus pixel count. They differ by about half a pixel along the whole outline; use pixel counts for small objects and say which one you report.
  • Touching objects. Connected components merge touching objects into one region; morphology alone rarely separates them reliably.

Practice

  1. A mask has 1-pixel noise specks and objects at least 10 pixels wide. Which operation and which element remove the specks without changing the objects' size?
Answer

An opening with a small element, for example 3×33 \times 3: the erosion deletes anything narrower than 3 pixels, the dilation restores the objects that survived to their original size (up to the element's shape at sharp corners).

  1. Two coins touch along a short arc. Why does a closing make the problem worse, and what would you try instead?
Answer

Closing fills gaps narrower than the element, so it widens the bridge between the coins. Try an erosion to separate them (then label, then dilate each label back), or the distance transform and watershed, which split regions at their narrowest point.

  1. cv2.boundingRect returns (12, 30, 25, 18). Give the box in [x1, y1, x2, y2] form and the slice that crops it.
Answer

[12, 30, 37, 48], cropped with img[30:48, 12:37].

  1. Compute the circularity of a 10×1010 \times 10 square contour through the pixel centres (side 9) and of a circle of radius 5.
Answer

Square: A=81A = 81, P=36P = 36, 4π⋅81/362=π/4≈0.7854\pi \cdot 81 / 36^2 = \pi/4 \approx 0.785 (independent of the size). Circle: 4π⋅πr2/(2πr)2=14\pi \cdot \pi r^2 / (2\pi r)^2 = 1 for an ideal circle; digital circles score lower, 0.80–0.86 in the lesson.

Test yourself

What does a morphological opening do to a binary mask?

  1. Fills holes smaller than the element
  2. Removes objects and protrusions smaller than the element and keeps the rest at its size
  3. Grows all objects by the element
  4. Finds the outlines of objects

Two foreground pixels touch only at a corner. How many connected components are they?

  1. One, with either connectivity
  2. Two with 4-connectivity, one with 8-connectivity
  3. One with 4-connectivity, two with 8-connectivity
  4. Two, with either connectivity

Why did the edge-based pipeline count the 24 coins when the Otsu mask did not?

  1. Canny is a learned detector
  2. Edges respond to local changes in brightness, so the uneven background light does not merge coins with the background
  3. Otsu cannot handle 8-bit images
  4. Hole filling separates touching coins

cv2.contourArea of a filled 24 x 24 square gave 529, while the square has 576 pixels. Why?

  1. A bug in OpenCV
  2. The contour polygon runs through the centres of the boundary pixels, so its side is 23 and its area 232=52923^2 = 529
  3. The square is not filled
  4. contourArea counts only interior pixels with 4-connectivity