Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 54 ยท Edges, Contours and Shapes

Blob Detection: Counting Dots, Circles and Ellipses

Find and count blobs with SimpleBlobDetector and connectedComponentsWithStats: filter by area, circularity, convexity and inertia, detect circles and ellipses, with runnable NumPy models.

A blob is a group of connected pixels that share a property, such as being brighter or darker than the background. Coins on a table, cells under a microscope, stars in the night sky, holes in a metal plate and dots on a dice are all blobs. Counting them, measuring their size and picking out the round ones is one of the most common jobs in industrial and scientific vision.

OpenCV gives you two routes. cv2.SimpleBlobDetector is a ready-made detector with filters for area, circularity, convexity and inertia, and it returns keypoints with a position and size. The second route builds the pipeline yourself from thresholding, cv2.connectedComponentsWithStats and the contour measurements from Contour Features. This lesson covers both, explains each filter with its formula, and shows how to find circles and ellipses. The OpenCV calls are read-only; NumPy models let you run the logic.

SimpleBlobDetector

The detector works in these steps: it thresholds the image at many levels between minThreshold and maxThreshold, finds the connected components in each binary image, merges blobs whose centers are close across levels, and keeps the ones that pass your filters. A blob that survives at many thresholds is stable, which makes the detector robust to lighting.

Python
import cv2

img = cv2.imread("dots.png", cv2.IMREAD_GRAYSCALE)

params = cv2.SimpleBlobDetector_Params()
params.filterByArea = True
params.minArea = 80
params.maxArea = 5000

detector = cv2.SimpleBlobDetector_create(params)
keypoints = detector.detect(img)

print("blobs found:", len(keypoints))
for kp in keypoints:
    print(kp.pt, kp.size)              # center (x, y) and diameter

vis = cv2.drawKeypoints(
    img, keypoints, None, (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS
)

kp.pt is the blob's center as floats, kp.size its diameter, and the "rich" draw flag draws a circle of that size around each keypoint. The detector gives you centers and sizes, not outlines; if you need the shape, use contours.

The filters

All filters are off or at defaults until you switch them on with the matching filterBy... flag.

Filter Parameters What it keeps
Color filterByColor, blobColor 0 finds dark blobs, 255 finds bright blobs. This is on by default with blobColor = 0, so bright dots are missed unless you set 255.
Area minArea, maxArea Blobs whose pixel area is in the range. Removes specks and huge regions.
Circularity minCircularity, maxCircularity 4 * pi * area / perimeter**2. A perfect circle is 1.0, a square about 0.785, a thin line near 0.
Convexity minConvexity, maxConvexity area / convex hull area. 1.0 for a convex shape, lower for shapes with dents.
Inertia minInertiaRatio, maxInertiaRatio Ratio of the minor to the major axis of the best-fit ellipse. 1.0 for a circle, near 0 for an elongated blob.

Other settings: minThreshold, maxThreshold and thresholdStep set the range of thresholds, minDistBetweenBlobs merges blobs that are too close, and minRepeatability says in how many threshold levels a blob must appear.

Python
params = cv2.SimpleBlobDetector_Params()
params.filterByColor = True
params.blobColor = 255                 # bright blobs on a dark background
params.filterByArea = True
params.minArea = 50
params.filterByCircularity = True
params.minCircularity = 0.8            # nearly round
params.filterByConvexity = True
params.minConvexity = 0.9
params.filterByInertia = True
params.minInertiaRatio = 0.6           # not too elongated

A good way to learn the filters is to turn them on one at a time while looking at the drawn keypoints, or to adjust them live with trackbars. Tips: for dark dots on a bright page use blobColor = 0; blur the image slightly first to avoid noisy blobs (Blurring and Noise Reduction); and if nothing is found, loosen the filters before suspecting the image.

Typical uses: counting objects, detecting white or black dots (like a dot pattern for calibration), finding circular holes, tracking round markers, and counting cells.

The do-it-yourself route: connected components

cv2.connectedComponentsWithStats labels each group of connected foreground pixels in a binary image and gives you statistics for free:

Python
_, binary = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
count, labels, stats, centroids = cv2.connectedComponentsWithStats(binary, connectivity=8)

for i in range(1, count):                       # label 0 is the background
    x, y, w, h, area = stats[i]
    cx, cy = centroids[i]
    if area >= 80:
        print(f"blob {i}: area={area} box=({x},{y},{w},{h}) center=({cx:.1f},{cy:.1f})")

stats[i] holds [x, y, width, height, area] (the constants are cv2.CC_STAT_LEFT, TOP, WIDTH, HEIGHT, AREA). connectivity is 4 or 8: with 8, pixels touching at a corner belong to the same blob. This route is quick and exact for filtering by area and position, and you can compute circularity from contours when needed. Use SimpleBlobDetector when you want its multi-threshold robustness and ready filters.

Circles and ellipses

For round objects there are three tools:

  • cv2.HoughCircles finds circles directly in a gray image and returns centers and radii, but is sensitive to its parameters. See Detecting Lines, Circles and Shapes.
  • cv2.minEnclosingCircle(contour) returns the smallest circle that contains a contour. Compare the contour's area with the circle's area (pi * r**2) to test "roundness".
  • cv2.fitEllipse(contour) fits a rotated ellipse to a contour of at least five points, returning ((cx, cy), (major_axis, minor_axis), angle). The ratio of the axes is the same as the inertia ratio above.
Python
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
    if len(c) >= 5 and cv2.contourArea(c) > 200:
        (cx, cy), (d1, d2), angle = cv2.fitEllipse(c)
        cv2.ellipse(vis, ((cx, cy), (d1, d2), angle), (0, 255, 0), 2)

Try it: label blobs and filter by area

This stand-in implements connected-component labeling with a flood fill (8-connectivity), computes the same area, bounding box and centroid that connectedComponentsWithStats returns, and then filters by area.

Python Connected components with stats

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.

Four blobs are found with 8-connectivity: the 2x2 square (area 4), the five-pixel cluster whose pieces touch at corners, the lone right-hand pixel (area 1) and the 4x2 rectangle (area 8). Filtering by area removes the single pixel.

Try it: circularity, convexity-like and inertia filters

This model computes the same shape descriptors the detector filters by, from nothing but a binary mask: area, perimeter (counted as exposed pixel edges), circularity, and the axis ratio from the covariance of pixel coordinates. A disc, a square and a thin bar show how the numbers separate them.

Python Shape descriptors for blob filters

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 circ* column uses pixel-edge counting, so it is lower than the smooth-contour value 4piarea/perimeter squared that OpenCV computes, but the ordering is the same: disc and square are chunky, the bar is not.) The inertia ratio separates the elongated bar (about 0.15) from the disc and square (close to 1).

What is real: the detector's thresholding steps, the five filters with their formulas, connectedComponentsWithStats output and the ellipse and circle fitting calls follow OpenCV 4. What is the stand-in: OpenCV is not available in the browser, so the NumPy code recreates labeling and the shape descriptors on tiny arrays; the pixel-edge perimeter is a simplification.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You want SimpleBlobDetector to find bright dots on a dark background. What must you set?

    The default blobColor is 0, which finds dark blobs. Bright blobs need blobColor = 255.
  2. 2. What is the circularity of a perfect circle?

    Circularity is 4piarea / perimeter squared. For a circle it equals exactly 1, and less for other shapes.
  3. 3. What does the inertia ratio measure?

    The inertia ratio compares the two axes of the best-fit ellipse, so thin streaks have values near 0.
  4. 4. In connectedComponentsWithStats, what does label 0 represent?

    Label 0 is the background, so real blobs are numbered from 1.
  5. 5. What does SimpleBlobDetector return for each blob?

    Each blob is a cv2.KeyPoint with .pt (center) and .size (diameter). Use contours if you need the outline.

Summary

  • A blob is a connected group of similar pixels. cv2.SimpleBlobDetector thresholds at many levels, groups components and keeps those that pass its filters, returning keypoints with a center and a diameter.
  • Filters: color (blobColor 0 = dark, 255 = bright), area, circularity (4*pi*A/P^2), convexity (area over hull area) and inertia ratio (minor over major axis).
  • connectedComponentsWithStats gives labels, bounding boxes, areas and centroids of a binary image; label 0 is the background.
  • Use minEnclosingCircle, fitEllipse or HoughCircles for round objects. Pre-blur and tune filters one at a time.

Next: describe distinctive points of an image in Corners and Keypoints or look for a known pattern in Template Matching.