Skip to content
Tactiverge

Finding objects

Turn a binary mask into a list of objects: group connected pixels into regions, then measure each region's area, centroid and bounding box.

Lesson 4 of 6 · 35 min · Self-paced · Free

From pixels to things

After thresholding, a robot has a mask of 1s and 0s. But a gripper cannot reach for "pixels". It needs answers to questions like: How many objects are there? Where is the middle of each one? How big is it? This lesson turns a mask into exactly that: a list of objects, each with a size and a position.

The method has two parts. First, group pixels that touch into connected regions. Second, measure each region.

Which pixels count as touching?

Two pixels are neighbours if they share an edge: up, down, left or right. This is called 4-connectivity. Some systems also count the four diagonal neighbours, which is 8-connectivity. The choice matters. Two blobs that touch only at a corner are one object under 8-connectivity and two objects under 4-connectivity. Neither is "correct"; you choose based on what your objects look like, and you say which you used.

Labelling connected regions

The algorithm is a flood fill, closely related to the breadth-first search used for path planning on grids. Scan the mask row by row. When you meet a 1 you have not seen before, it is the start of a new region. Collect it, then repeatedly collect any unseen neighbours that are also 1, until the region stops growing. Then carry on scanning.

mask = [
    [0, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 1, 0, 0, 0, 0, 0],
    [0, 1, 1, 1, 0, 0, 1, 0],
    [0, 0, 1, 1, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 1, 1, 0],
    [0, 0, 0, 0, 0, 1, 1, 0],
    [0, 0, 0, 0, 0, 1, 1, 0],
]

def find_regions(mask):
    """Return a list of regions; each region is a list of (row, col) pixels."""
    rows, cols = len(mask), len(mask[0])
    seen = [[False] * cols for _ in range(rows)]
    regions = []
    for r in range(rows):
        for c in range(cols):
            if mask[r][c] == 1 and not seen[r][c]:
                region = []
                to_visit = [(r, c)]
                seen[r][c] = True
                while to_visit:
                    pr, pc = to_visit.pop()
                    region.append((pr, pc))
                    for nr, nc in [(pr - 1, pc), (pr + 1, pc), (pr, pc - 1), (pr, pc + 1)]:
                        if 0 <= nr < rows and 0 <= nc < cols:
                            if mask[nr][nc] == 1 and not seen[nr][nc]:
                                seen[nr][nc] = True
                                to_visit.append((nr, nc))
                regions.append(region)
    return regions

Three details make this work. The seen grid ensures no pixel is counted twice, which also guarantees the loop finishes. The bounds check 0 <= nr < rows stops the code from reading outside the image. And a pixel is marked as seen when it is added to to_visit, not when it is taken off, so it can never be queued twice.

Measuring each region

Once you have a region's pixels, three measurements are easy and very useful:

  • Area: the number of pixels. It tells you roughly how big the object looks.
  • Centroid: the average row and average column of the region's pixels. It is the object's "centre of mass" in the image, and it is often the point a robot aims for.
  • Bounding box: the smallest upright rectangle that contains the region, given by the top, left, bottom and right pixel positions.
def describe(region):
    area = len(region)
    row_c = sum(p[0] for p in region) / area
    col_c = sum(p[1] for p in region) / area
    top = min(p[0] for p in region)
    bottom = max(p[0] for p in region)
    left = min(p[1] for p in region)
    right = max(p[1] for p in region)
    return area, (row_c, col_c), (top, left, bottom, right)

for i, region in enumerate(find_regions(mask)):
    area, (rc, cc), box = describe(region)
    print(f"Region {i}: area {area}, centroid (row {rc:.2f}, col {cc:.2f}), box {box}")

Output:

Region 0: area 7, centroid (row 2.00, col 2.00), box (1, 1, 3, 3)
Region 1: area 1, centroid (row 2.00, col 6.00), box (2, 6, 2, 6)
Region 2: area 6, centroid (row 5.00, col 5.50), box (4, 5, 6, 6)

Check Region 0 by hand. Its pixels are at rows 1, 1, 2, 2, 2, 3, 3, which add to 14, and 14 ÷ 7 = 2. Its columns are 1, 2, 1, 2, 3, 2, 3, which also add to 14, so the centroid is (2, 2). Region 2 is a 3-row by 2-column rectangle; its centroid falls at column 5.5, exactly between two pixel columns. Centroids do not have to land on a pixel, which is useful: averaging many pixels gives a position more precise than any single pixel.

Rejecting noise

Region 1 is a single isolated pixel. In a real image, tiny regions like this are usually noise: a reflection, a speck of dust or a pixel that only just crossed the threshold. The simplest fix is a minimum area:

MIN_AREA = 3
objects = [r for r in find_regions(mask) if len(r) >= MIN_AREA]
print(f"{len(objects)} objects kept")

Output:

2 objects kept

The minimum area is a design decision, just like the threshold. Set it too low and noise becomes "objects"; set it too high and small or distant real objects are thrown away. Write down the value you chose and why.

What these numbers can and cannot tell you

The centroid and bounding box are in pixel coordinates. They tell the robot where the object appears in the image, not where it is in the room. Turning a pixel position into a real position needs a camera model, which is the subject of the next lesson. Area in pixels also depends on distance: the same object looks four times smaller in area when it is twice as far away.

Some useful extras are easy to compute from the same data. The bounding box's fill ratio (area ÷ box area) separates compact shapes from thin or ragged ones: Region 2 fills its box completely (6 ÷ 6 = 1.0), while Region 0 fills 7 ÷ 9 ≈ 0.78. The box's width-to-height ratio separates long objects from square ones.

Recap

  • Connected-component labelling groups touching mask pixels into regions with a flood fill.
  • 4-connectivity and 8-connectivity can give different object counts; choose deliberately.
  • Area, centroid and bounding box summarise each region; centroids can be more precise than one pixel.
  • A minimum-area filter removes specks of noise, at the risk of discarding small real objects.

Project

Programming project: count the coins

  1. Draw a 12 × 10 binary mask in Python containing four "coins" of different sizes, plus two single-pixel specks of noise. Make two of the coins touch only at one diagonal corner.
  2. Run find_regions and describe and print a table of regions.
  3. Change the neighbour list to use 8-connectivity (add the four diagonals). How many regions do you find now? Explain the difference.
  4. Choose a minimum area that removes the noise but keeps every coin. Then sort the remaining objects from largest to smallest area.
  5. Add a fill-ratio calculation and use it to tell round-ish blobs from thin lines.

Deliverables

  • A Python file with your mask, both connectivity versions and the filtering step
  • Printed results for 4- and 8-connectivity
  • A short explanation of your chosen minimum area

Knowledge check

Check your understanding

  1. 1. Two blobs touch only at one diagonal corner. How many regions does each rule find?
  2. 2. A region contains the pixels (0, 0), (0, 1), (1, 0) and (1, 1) as (row, col). What is its centroid?
  3. 3. In find_regions, why is each pixel marked as seen when it is added to to_visit?
  4. 4. You raise the minimum area from 3 to 50 pixels. What is the most likely risk?
  5. 5. An object's centroid is at pixel column 400. What does that tell the robot on its own?

Go further