Cameras & sensorsTroubleshooting

HoughCircles detects only one circle: use grayscale input

Why HoughCircles detects only one of three circles: pass grayscale input, set minDist below the smallest center gap, and tune param1, the internal edge stage.

LumaSpec Vision11 min read Share on LinkedIn

On this page 10 sections
  1. 01The two settings that drop two circles
  2. 02What the gradient method does with your pixels
  3. 03The corrected call
  4. 04Worked example: three 30 mm parts, 45 mm apart
  5. 05Symptom, cause, fix
  6. 06Tune in this order
  7. 07The capture side sets the parameter range
  8. 08When HoughCircles is the wrong tool
  9. 09Pre-flight checklist
  10. 10Questions

Three circles sit in the frame, the call returns one, and sweeping the threshold changes nothing. The cause is almost never the transform: the image handed to HoughCircles has already been through Canny, dilate, erode and a 15×15 morphological close, so the gray-level gradients the Hough gradient method feeds on are gone before the accumulator starts. This guide gives the two settings that recover the missing circles, the order to tune the rest, a worked example in millimeters and pixels, and the capture-side numbers — focal length, working distance, exposure — that keep the parameters stable. The code is C++; the same rules apply to the Python and C# bindings.

The two settings that drop two circles

Pass the grayscale image and nothing else. HoughCircles expects an 8-bit, single-channel image, and with the gradient method it runs its own edge stage internally: param1 is the higher threshold of that stage, and the lower one is half of it. Pre-running Canny hands the function a binary edge map instead of gray levels, and the call still compiles because an edge map is also 8-bit and single-channel — it simply performs badly.

On a hard 0-to-255 step the Sobel magnitude inside the function is about 4 × 255 = 1020, while flat background reads 0. Every edge pixel then carries essentially the same magnitude, so any param1 between those extremes admits the same pixels and the knob is dead. The center accumulator floods with votes from thick, displaced edges, and a high param2 keeps only the loudest peak: one circle, sometimes two.

The second setting is minDist. The failing pattern sets it to rows/1.1, which is 436 px on a 480-row image. The function suppresses every candidate center within minDist of a stronger one, so with true centers a few hundred pixels apart, two of your three circles are deleted before you ever see them. Set minDist just under the smallest center-to-center gap you must resolve; what minDist really filters is worth reading on its own.

What the gradient method does with your pixels

The gradient method works in two stages. An internal Canny pass — upper threshold param1, lower threshold half of it — marks edge pixels and keeps each pixel's Sobel gradient direction. Then every edge pixel votes along its gradient line for candidate centers at each radius between minRadius and maxRadius; accumulator cells that reach param2 become centers, and the radius comes from the distances of the supporting edge pixels.

Each pre-processing step damages one of those stages:

  • A Canny map ahead of the call flattens the gray step, so the internal threshold has nothing meaningful to cut (the 1020-versus-0 case above).
  • Canny thins and fragments arcs; short fragments cast fewer votes and smear the radius histogram.
  • Dilate, erode and close move rims by the kernel radius, so voted centers drift and radii come back systematically wrong.
mm_per_px = field_of_view_mm / image_width_px radius_px = part_diameter_mm / (2 × mm_per_px) minDist_px ≈ 0.8 × closest_center_gap_mm / mm_per_px expected_votes ≈ 2π × radius_px # a full, clean rim

The corrected call

Keep a size-5 median blur — a size-1 kernel copies the image unchanged — drop everything that built the edge image, and set the geometry from millimeters:

// Input: bgr, a cv::Mat (CV_8UC3) read with cv::imread
cv::Mat gray;                                  // CV_8UC1 destination
cv::cvtColor(bgr, gray, cv::COLOR_BGR2GRAY);
cv::medianBlur(gray, gray, 5);                 // size 5; size 1 is a no-op

std::vector<cv::Vec3f> circles;                // one (x, y, radius) per circle
const double dp      = 1.0;    // accumulator at image resolution
const double minDist = 1200.0; // px, below the 1485 px center gap
const double param1  = 100.0;  // internal Canny upper threshold
const double param2  = 30.0;   // start low, raise toward 400 once three appear
const int minRadius  = 400;    // px
const int maxRadius  = 600;    // px

cv::HoughCircles(gray, circles, cv::HOUGH_GRADIENT,
                 dp, minDist, param1, param2, minRadius, maxRadius);

// Test on a saved frame: three circles expected
if (circles.size() != 3) return 1;   // tuning not finished
const double d01 = std::hypot(circles[1][0] - circles[0][0],
                              circles[1][1] - circles[0][1]); // px, std::hypot from <cmath>
const double gapMm = d01 * 0.0303;   // expect about 45 mm

Two naming notes: OpenCV 2.4 headers spell the method constant CV_HOUGH_GRADIENT; OpenCV 4 uses cv::HOUGH_GRADIENT. Each result is a cv::Vec3f of center x, center y and radius in pixels, and reading the result array correctly matters once the count is right. The test is the count plus the spacing: three circles whose centers sit about 1485 px apart at the scale below.

Worked example: three 30 mm parts, 45 mm apart

Example inputs: three circular parts 30 mm across, centers 45 mm apart, on a tray; a 1/1.7" class sensor about 7.5 mm wide behind 4000 × 3000 pixels; a 35 mm lens.

Lens first. Magnification m = f / (WD − f) = 35 / (600 − 35) = 0.0619 at 600 mm working distance, so the field of view is sensor width over m = 7.5 / 0.0619 = 121 mm. Pixel scale: 121 mm / 4000 px = 0.0303 mm per pixel, which puts the pixel pitch near 1.9 µm.

Part geometry in pixels: diameter 30 / 0.0303 = 990 px, radius 495 px, so the radius band is 400 to 600 px, ±20 percent around the measured value. The center gap is 45 / 0.0303 = 1485 px, so minDist = 1200 px, about 80 percent of it.

Votes: a complete rim carries roughly 2π × 495 = 3,110 edge pixels, and the winning center accumulator reaches that order of magnitude. param2 = 400 still keeps a rim that is 85 percent intact (0.85 × 3,110 ≈ 2,640) while discarding texture that gathers a few dozen votes; start at 30, confirm three circles, then raise.

Edge threshold: read the gray step across a rim in the live image. A backlit silhouette here steps about 140 gray levels, so param1 = 100 sits inside the step with margin; below roughly 70 the part's interior texture starts voting, above 140 the rim itself drops out.

Motion and aperture: at 100 mm/s, one pixel of blur takes 0.0303 / 100 = 0.0003 s, so fix the exposure at 300 µs or freeze the part with a strobed light. At f/4 the Airy disc is 2.44 × 0.55 µm × 4 = 5.4 µm, about 2.9 of these pixels; at f/8 it is 10.7 µm, near 5.7 pixels — hold f/4 to f/5.6 and buy depth of field with light, not stops. The Airy disk and diffraction limit guide scales this to any pixel size.

The camera resolution calculator works from the other end: the pixels required for a field of view and a smallest feature.

Camera resolution for the smallest feature
Units
Pixels needed
–
Sensor size
– MP
Smallest sensor that fits
–
Pixel on the part
– mm
Pixels across the feature, that sensor
–

Pixels needed = field / feature × pixels per feature on each axis (field incl. margin). The lens must resolve the pixels too: Nyquist = 1000 / (2 × pixel µm) lp/mm.

Find cameras with enough pixels Open the full calculator

Decision for this case: 35 mm lens at 600 mm, grayscale in, dp 1, minDist 1200 px, radius band 400–600 px, param1 100, param2 30 rising to 400.

Symptom, cause, fix

Symptom Most likely cause Fix
One of three circles returned minDist above the center gap Set minDist to 0.8 × the gap in pixels
Zero circles param2 above the vote ceiling, or radii outside the band Lower param2 in steps of 10; widen the band to ±20 percent
Same part returned twice, different radii Radius band too wide, or binary input Grayscale in; narrow the band
Radius off by the same few pixels every time Blur or morphology moved the rim Drop dilate, erode and close; median blur 5 at most
Centers appearing on flat texture param1 below the real gray step Raise param1 toward the measured step
Works on one shift, fails on the next Auto exposure shrank the gray step Fix exposure and gain; control the light

Tune in this order

  1. Compute mm_per_px from the field of view and image width; convert part diameter and center gap to pixels.
  2. Set dp = 1 and the radius band to ±20 percent of the expected radius.
  3. Set minDist to 0.8 × the closest center gap.
  4. Sweep param1 from 50 to 150 on a saved image; keep the lowest value at which interior texture stops producing centers.
  5. Start param2 at 30, confirm every real circle appears, then raise it while false centers persist.
  6. Freeze exposure, gain and light, then re-run on a batch of saved frames — 20 is enough to expose drift — before calling the set tuned.

When the count holds, wiring the grab loop for live circle detection is the next step.

The capture side sets the parameter range

param1 is only as good as the gray step it cuts. A rim with a 140-count step gives a wide working band; the same rim under drifting ambient light with auto exposure can shrink to a 40-count step and the whole parameter set stops holding. Backlight for a silhouette, or light a bright rim on a dark part with a diffuse front light, then fix exposure and gain.

A camera that keeps the radius in the hundreds of pixels makes every parameter comfortable:

Area scan cameras12 MP USB3 area scan camera, IMX226, 1/1.7" rolling shutter, 30 fps, 4000 × 3000 resolution (LS-CMR-0166)LS-CMR-0166
Sensor format
1/1.7"
Interface
USB3
Resolution
12 MP
Shutter
Rolling
$560.00View partBuild a system with it

The LS-CMR-0166 is a 12 MP USB3 area scan camera with a 1/1.7" rolling-shutter sensor, 4000 × 3000 resolution and 30 fps. On a stopped tray the rolling shutter costs nothing; on a moving conveyor, pair it with the strobe or choose a global-shutter sensor in the area scan cameras finder, or start at the camera step of the configurator.

The lens from the worked example:

Machine vision lenses35 mm, 2/3", 6 MP, C-mount machine vision lens (LS-FFL-0679)LS-FFL-0679
Type
Machine vision fixed
Sensor format
2/3"
Mount
C-mount
Resolution
6-10 MP
$219.00View partBuild a system with it

The LS-FFL-0679 is a 35 mm, 2/3", 6 MP C-mount machine vision lens in the 8-11 mm image-circle class. A 1/1.7" sensor has a diagonal near 9.4 mm, so the circle covers it with margin; the lens finder lists the other working distances.

If the inspection should run without a PC, the smart cameras class puts the whole pipeline on the device. The LS-SMC-0017 is an 8.8 MP global-shutter smart camera on an x86 platform with a C-mount, so the same grayscale-and-HoughCircles code runs there:

Smart cameras & vision sensorsSC / SC smart camera (X86 platform), 8.8 MP, USB3, Color/Mono, global shutter (LS-SMC-0017)LS-SMC-0017
Interface
USB 2.0
Resolution
6-10 MP
Sensor format
1"
Shutter
Global
$1,359.00View part

When HoughCircles is the wrong tool

Filled discs on a plain background do not need a vote accumulator. Threshold the image — automatic threshold methods settle the choice when the light is steady — and take the centroid, which reaches sub-pixel accuracy on a filled shape; the grayscale centroid of a dark circle shows the inversion step. Where a clean binary mask is reachable, contours return centers and radii in one pass, and note that Canny before findContours leaves open contours — threshold, do not edge. A live binary preview settles the mask-versus-Hough question in minutes.

Keep HoughCircles for rims and rings — washer holes, flanges, bores — and for cluttered scenes where thresholding cannot isolate the part. For rims that are only partly visible, fit circles to contour arcs instead of voting. Once a center is stable, anchor a coordinate system to the circle center for robot guidance, or measure color at the center for sorting.

Decision by case: plain-background filled discs — threshold plus centroid; clean mask reachable — contours; rims, rings, clutter, unknown count — HoughCircles on grayscale; partially hidden arcs — arc fitting.

Pre-flight checklist

  • Grayscale 8-bit into the call; no Canny, dilate, erode or close ahead of it.
  • minDist under the smallest center gap, in pixels.
  • Radius band within ±20 percent of the measured radius.
  • The param1 sweep changes the count — if not, the input is already binary.
  • Exposure short enough for under one pixel of motion blur at line speed.
  • Detected center distances match the known millimeter gaps through mm_per_px.
  • The parameter set holds over a batch of saved frames, not one image.

Questions

Why does HoughCircles accept my Canny image without an error?

The function requires an 8-bit, single-channel input, and a Canny output is exactly that, so the type check passes. Nothing checks that the pixels carry gray levels: the gradient stage receives an image whose every edge has the same Sobel magnitude, about 4 × 255 = 1020 on a hard step, over flat regions of 0. Any param1 between those extremes selects the same pixels, so tuning appears dead while the accumulator floods. The failure is silent.

How small should minDist be for circles close together?

Measure the closest two centers in pixels and set minDist to about 80 percent of that distance. The parameter suppresses every detected center within minDist of a stronger one, so any value above your true gap deletes a neighbor, and a value near zero lets one physical circle return several centers at different radii. Between roughly half and 90 percent of the gap the count is stable; 80 percent is the usual landing point.

How do I choose param2 with numbers instead of guessing?

Estimate the vote ceiling: a complete circle of radius r carries about 2πr edge pixels, so at r = 495 px the winning center accumulates on the order of 3,100 votes. Set param2 as a fraction of that ceiling, matched to how much rim must stay visible: 400 keeps a rim that is 85 percent intact (0.85 × 3,100 ≈ 2,640) and rejects texture that draws a few dozen votes. Treat the number as an estimate and confirm on saved frames.

Should I blur the image before HoughCircles?

A size-5 median or a 3×3 Gaussian removes salt noise and speckle that would otherwise vote in the accumulator, and either is worth keeping on textured surfaces. Two limits: a kernel of size 1 is a no-op that copies input to output — a common leftover in copied code — and heavy blur rounds the rim so the radius estimate drifts small by a pixel or two. Blur mildly, after converting to grayscale.

My parts are filled discs on a plain background. Is HoughCircles the right tool?

Usually not. A filled disc on a clean background is measured better by thresholding and centroid: the centroid of a binarized disc is sub-pixel accurate and needs no radius or vote parameters. HoughCircles earns its keep on rims, rings and cluttered scenes where thresholding cannot separate part from background. If you keep it anyway, invert the image so the rim still presents a gray step to the gradient stage.

Do the same parameters survive a change of working distance?

No. Every geometric parameter scales with pixel size: halve the working distance and the radius in pixels roughly doubles while the field of view halves. Recompute minRadius, maxRadius and minDist from the new millimeters-per-pixel figure before reusing anything. Only dp, param1 and param2 can carry over, and param1 only if lighting and exposure are unchanged, because it depends on the gray-level step at the rim.