Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 46 ยท Projects

Project: Counting Objects

Count coins in a generated photo: threshold, clean the mask with morphology, label regions, filter by area, split touching coins and build a sizes table.

"How many are there, and how big is each one?" is one of the most common questions put to an image: coins on a table, cells under a microscope, screws on a belt, trees in a satellite picture. The classical recipe has five steps, and you know all of them: threshold, clean up the mask, label the connected regions, filter by area, and measure what is left.

In this project you will run that recipe on a generated photo of twelve coins in three sizes, with uneven lighting, dust, sensor noise and one pair of coins that touch. The touching pair is the interesting part, because plain labeling counts it as a single object. You will fix that with a distance transform and finish with a table of sizes and a total value.

flowchart LR
    A["photo"] --> B["Otsu threshold"]
    B --> C["fill holes,<br/>remove specks"]
    C --> D["label regions"]
    D --> E["filter by area"]
    E --> F["split touching<br/>objects"]
    F --> G["sizes table<br/>and count"]

The whole project in one line. Each box is a tool from an earlier lesson.

Step 1: The photo and a first mask

The generator below draws coins as dark discs on a bright table whose brightness changes smoothly across the picture. Each coin has a bright reflection in the middle (value 165, brighter than the cutoff will be), which will matter in a moment. There are 4 small coins (radius 9), 6 medium (radius 12) and 2 large (radius 15), plus four specks of dust and Gaussian noise. The two medium coins at the bottom right touch.

Since coins are darker than the table, the mask is img < t, where t comes from Otsu's method. Then ndimage.label numbers the connected regions (see Connected Components and Labeling).

Python Photo, Otsu threshold and a raw count

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Fifteen regions, not twelve. The mask shows why: the bright reflection in each coin's centre is brighter than the threshold, so every coin is a ring with a hole in it, and the four dust specks count as regions of their own (area 9). The area list also reveals something useful: it is clustered, with a gap between the dust (9 pixels) and the smallest coin ring (204).

Step 2: Fill holes and filter by area

Two operations repair the mask. ndimage.binary_fill_holes fills every background region that is completely enclosed by foreground, which turns each ring back into a disc. Then an area filter throws away regions that are too small to be coins. The sizes table is the tool for choosing the minimum: you sort the areas, find the gap, and put the limit inside it.

Python A sizes table with pandas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The dust specks (area 9) disappear at MIN_AREA = 60. What remains is easy to read: four regions of area 253, four of 441, two of 709 and one of 871. A disc of radius 9 has an area of about 254, radius 12 about 452 and radius 15 about 707, so the first three groups are the small, medium and large coins. The "radius" column is the radius of a disc with the same area, so 9.0, 11.8 and 15.0 match the true sizes closely (pixel counting loses a little at the rim).

The odd one out is the region of area 871, centered between two coins. That is the touching pair, counted as one object. If you reported the number of regions you would say 11 and be wrong by one; if you reported the total area divided by the typical coin area you would get a number closer to the truth but still not an integer count. We need a method that separates the pair.

Note: An opening (ndimage.binary_opening with a small disc) is the other classic way to remove specks, and it also smooths ragged edges. An area filter is more controllable because the limit is a number you can read from the table. In noisy photos use both: opening first, then the filter.

Step 3: Split touching coins with the distance transform

The Euclidean distance transform replaces each foreground pixel by its distance to the nearest background pixel. Inside a disc, the result is a cone whose peak is at the centre and whose height equals the disc's radius. Two touching discs give two peaks joined by a narrow saddle. Counting peaks therefore counts the coins even when their masks have merged, and the peak heights are the radii.

To find the peaks, keep the pixels that are equal to the maximum of their own neighbourhood (a maximum filter with a disc footprint of radius 5) and are at least 5 pixels deep. Then label those peaks and read each one's height from the distance map.

Python Peaks of the distance map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Twelve peaks, one per coin. The rows at (92, 98) and (92, 120) are the touching pair, with radius 12.0 each, which equals the true size. The centres are found to the exact pixel here because the discs are perfect; real coins are less regular, so expect a pixel or two of error.

Step 4: Classify and total

With radii in hand, the last step assigns each coin to the nearest of the known sizes and sums their values. Suppose small coins are worth 5, medium 10 and large 25. The function below packages the whole pipeline, so you can test it under noise: we add extra Gaussian noise of growing strength to the photo, blur it slightly before thresholding (a Gaussian blur trades detail for noise suppression), and check that the count and total stay right.

Python The complete counter under noise

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The truth is 4 small, 6 medium and 2 large coins, worth 4 x 5 + 6 x 10 + 2 x 25 = 130, and the pipeline reports exactly that at every noise level shown, even though the largest noise makes the raw photo grainy. At extreme noise it will eventually fail; the usual fixes are a larger blur, a flat-field correction (dividing by a heavily smoothed copy, as in the Document Scanner project) and a stricter area filter.

Where to go next

  • Overlapping, not just touching. The distance transform needs a visible neck between objects. For heavy overlap, use the watershed method from Segmentation by Clustering and Watershed, which grows regions from the markers you found.
  • More measurements. Add perimeter, circularity and orientation from Contours and Shape Measurements to separate coins from other objects such as keys or screws.
  • Scale. To report sizes in millimetres, put an object of known size in the scene and compute the pixels-per-millimetre ratio.
  • Check by eye. Always overlay the result on the photo, as in the last figure. A count that looks plausible can still hide a missed object.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Each coin has a bright reflection in its middle, so thresholding leaves a ring. Which operation turns the rings back into solid discs?

    binary_fill_holes fills background regions that are completely enclosed by foreground. Dilation would also fill them but would grow the coins and merge neighbours.
  2. 2. How do you choose a good minimum area for the area filter?

    A sizes table makes the gap visible: here dust is 9 pixels and the smallest coin is above 200, so anything between them works.
  3. 3. Two coins touch, and ndimage.label reports one region. Why does the distance transform help?

    The distance to the nearest background pixel is largest at a disc's centre. Two touching discs give two peaks separated by a narrow neck, so counting peaks counts the objects.
  4. 4. In the sizes table, what is the 'radius' computed as sqrt(area / pi)?

    It is the equivalent radius: if the region were a perfect disc with the measured area, this would be its radius. It is a quick size measure that works for any shape.
  5. 5. Why blur the noisy photo slightly before Otsu thresholding?

    Averaging neighbouring pixels cancels random noise, so the histogram has cleaner peaks and the mask has fewer speckles. The price is slightly softer edges.

Summary

  • Counting objects is a pipeline: threshold, clean the mask, label, filter by area, measure.
  • Bright spots inside objects turn them into rings. binary_fill_holes repairs them, and an area filter (limit chosen from the sorted sizes table) removes dust.
  • A pandas table of area, centroid and equivalent radius turns labels into measurements you can read and filter.
  • Plain labeling merges touching objects. Peaks of the distance transform count them, and the peak heights give their radii.
  • Pre-blurring helps against noise. Always overlay the result on the photo and compare with a known truth where you can.

Next project: Image Search by Similarity.