Loading
0x60Lesson 7 of 16

Count objects with connected components

Group touching foreground pixels into objects, then measure and box each one.

22 min 6-question quiz 2 code exercises
By the end of this lesson you can
  • Explain 4- and 8-connectivity
  • Label objects in a mask with a flood fill
  • Compute each object’s size and bounding box

A mask says which pixels are foreground, but not how many objects there are. To count coins on a table or cells on a slide, group foreground pixels that touch each other: each group is a connected component, and each component is one object.

What does “touch” mean? With 4-connectivity, pixels touch only through a shared side (up, down, left, right). With 8-connectivity, sharing a corner counts too. The choice changes the count: a thin diagonal line is one object with 8-connectivity but a string of separate dots with 4.

Try it

Count the objects

Count the separate white objects in each mask, then check. Before guessing, decide whether pixels touching only at a corner belong together - and switch the connectivity to see how the answer changes.

Mask 1 of 3Score 0/0
Pixels touch when they share:
White pixels are foreground

How many separate objects are there?

Flood fill

The labeling algorithm is a flood fill, like the paint-bucket tool: scan the mask; when you find a foreground pixel that has no label yet, give it a new label and spread that label to every connected foreground pixel using a queue (a breadth-first search). Keep scanning until every foreground pixel is labeled. While filling, track each object’s size and its bounding box (smallest and largest row and column).

flood_fill.py
1from collections import deque
2
3mask = [
4    [1, 1, 0, 0],
5    [0, 1, 0, 1],
6    [0, 0, 0, 1],
7]
8seen = set()
9count = 0
10for row in range(len(mask)):
11    for column in range(len(mask[0])):
12        if mask[row][column] == 1 and (row, column) not in seen:
13            count += 1
14            queue = deque([(row, column)])
15            seen.add((row, column))
16            while queue:
17                current_row, current_column = queue.popleft()
18                for next_row, next_column in [(current_row + 1, current_column), (current_row - 1, current_column), (current_row, current_column + 1), (current_row, current_column - 1)]:
19                    inside = 0 <= next_row < len(mask) and 0 <= next_column < len(mask[0])
20                    if inside and mask[next_row][next_column] == 1 and (next_row, next_column) not in seen:
21                        seen.add((next_row, next_column))
22                        queue.append((next_row, next_column))
23print(count)
Output
2

Key takeaways

  • A connected component is a group of touching foreground pixels - one object.

  • 4-connectivity uses sides only; 8-connectivity adds corners, and can merge objects.

  • A flood fill (breadth-first search) labels each component and measures its size and bounding box.

Lesson quiz

6 questions · pass with 5 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: apply computer vision with Python

Use small pixel arrays to explore vision concepts, run your code against sample images, and connect each result to the larger computer vision idea.

Exercise 1

Count the objects

+25 XP

Read a JSON binary mask (0s and 1s). Print how many connected components of 1s it contains, using 4-connectivity.

  • Three blobs
  • Diagonal stays separate
  • Empty
main.py
Loading editor…

Python runs in a sandboxed browser worker with a 60 second time limit. Its runtime loads from the Pyodide CDN; your code stays in this browser.

Exercise 2

Box each object

+25 XP

Read a JSON binary mask. For each 4-connected component, in the order you first meet it scanning row by row, print size top left bottom right (bounds are inclusive row and column numbers).

  • Two objects
  • One pixel
main.py
Loading editor…

Python runs in a sandboxed browser worker with a 60 second time limit. Its runtime loads from the Pyodide CDN; your code stays in this browser.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Did you like the lesson? 😆👍
Consider a donation to support our work: