Connected components
A mask says which pixels are white. Connected components say which white pixels belong to the same piece: pixels that touch are one piece, and each piece gets a number. It is how you count objects in a picture, measure them and find where they are.
import os
import libstb as stb
os.makedirs("out", exist_ok=True)
camera = stb.Image.open("camera.png")
# A mask, with the specks removed.
mask = stb.threshold(camera, stb.otsu_threshold(camera))
mask = stb.morph_open(mask, stb.structuring_element("ellipse", 5))
# Pieces of white that touch (four neighbours: up, down, left, right) are one piece.
pieces = stb.connected_components(mask)
print("pieces:", pieces.count)
# stats has one row per piece: area, x, y, width, height, and the center of mass. Row i is the piece labelled i + 1.
rows = pieces.stats
areas = [int(row[0]) for row in rows]
print("largest piece:", max(areas), "pixels")
# A box around every piece of at least 2000 pixels, on the photograph.
canvas = stb.Canvas(camera.convert(stb.PixelFormat.RGB))
boxes = 0
for area, x, y, width, height, cx, cy in rows:
if area >= 2000:
canvas.add_rect(int(x), int(y), int(width), int(height)).no_fill().stroke(3, "#e63946")
boxes += 1
canvas.finish().write("out/boxes.png")
print("boxes drawn:", boxes)
mask.write("out/mask.png")
pieces: 21
largest piece: 134455 pixels
boxes drawn: 4


The result
connected_components(mask) returns the number of pieces, a label map the size of the picture (0 for the background and 1 to count for the pieces), and one record of statistics for each piece:
- the area, the number of pixels;
- the bounding box, as the x and y of the top-left pixel, the width and the height;
- the center of mass, the mean of the positions of its pixels.
stats and labels are NumPy arrays, so they need pip install "libstb[numpy]". Each row of stats is area, x, y, width, height, cx, cy, and row i describes the piece labelled i + 1. count needs nothing.
Connectivity
With four-connectivity (four, the default) two white pixels are in one piece only if they share a side. With eight (eight) they are also in one piece when they touch at a corner. Eight joins thin diagonal lines into one piece, and four keeps them apart.
Clean the mask first
A mask straight from a threshold has specks and holes, and every speck is a piece of its own. The example removes them with a morphological opening before it counts. Filtering the pieces by area, as the last step does, is the other half of the same job.
API at a glance
| Find the pieces | stb.connected_components(mask, connectivity="four") |
|---|---|
| How many | pieces.count |
| Statistics | pieces.stats, a NumPy array |
| The label map | pieces.labels, a NumPy array |