Most of our measurement projects are not won by a bigger model. They are won by getting a trustworthy edge position out of a few pixels. A part that must be checked to ±0.05 mm, imaged at 0.04 mm per pixel, leaves you roughly one pixel of tolerance. Whole-pixel contours cannot do that. Sub-pixel gauging can, if you treat it as a measurement problem and not a drawing problem.
This tutorial builds a classical gauging pipeline in OpenCV: stable pre-processing, sub-pixel edge location along profiles, robust line and circle fitting, conversion to millimetres, and an uncertainty figure you can put in a report.
1. Fix the image before you measure it
Sub-pixel methods amplify every flaw in the input. Before writing any gauging code:
- Lock exposure, gain and white balance. Auto-exposure moves edges.
- Use backlighting for silhouettes where the part allows it. A backlit edge is much steeper than a front-lit one.
- Undistort with your calibration (
cv2.undistortor a precomputedinitUndistortRectifyMapandremap). Lens distortion of even 0.3% is several pixels at the image edge. - Do not JPEG-compress. Capture PNG or raw.
2. Find the coarse edge, then refine it
Use a coarse pass to place the gauge, then a fine pass to measure it. The coarse pass can be an Otsu threshold and findContours. The fine pass should never rely on the threshold, because a threshold edge is only accurate to a whole pixel and depends on brightness.
import cv2, numpy as np
img = cv2.imread("part.png", cv2.IMREAD_GRAYSCALE)
blur = cv2.GaussianBlur(img, (0, 0), 1.0)
_, bw = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
contours, _ = cv2.findContours(bw, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
part = max(contours, key=cv2.contourArea)
3. Sub-pixel edge along a profile
Sample the intensity along a line perpendicular to the expected edge, with bilinear interpolation. Then locate the maximum of the gradient with a parabolic fit through the peak and its two neighbours.
def edge_along(img, p0, p1, n=64):
xs = np.linspace(p0[0], p1[0], n).astype(np.float32)
ys = np.linspace(p0[1], p1[1], n).astype(np.float32)
prof = cv2.remap(img.astype(np.float32), xs.reshape(1, -1), ys.reshape(1, -1),
cv2.INTER_LINEAR).ravel()
g = np.gradient(cv2.GaussianBlur(prof.reshape(1, -1), (0, 0), 1.2).ravel())
k = int(np.argmax(np.abs(g)))
if 0 < k < n - 1:
a, b, c = np.abs(g[k - 1]), np.abs(g[k]), np.abs(g[k + 1])
denom = a - 2 * b + c
k = k + (0.5 * (a - c) / denom if denom != 0 else 0.0)
t = k / (n - 1)
return (p0[0] + t * (p1[0] - p0[0]), p0[1] + t * (p1[1] - p0[1]))
Run this at many positions along the contour (30 to 100 profiles per feature). One profile is noisy; fifty averaged by a fit are not.
4. Fit geometry robustly
Fit primitives to the edge points instead of reading coordinates off them. Use a robust loss so that dust, burrs and a few bad profiles do not drag the result.
pts = np.array(edge_points, np.float32)
# straight edge
vx, vy, x0, y0 = cv2.fitLine(pts, cv2.DIST_HUBER, 0, 0.01, 0.01).ravel()
# hole / circular feature
(cx, cy), (w, h), ang = cv2.fitEllipse(pts)
cv2.fitEllipse needs at least five points but behaves well with dozens spread around the whole circumference. A hole seen by a tilted camera is an ellipse, and the fit handles that where minEnclosingCircle would not. Check the residuals: compute point-to-model distances and reject points beyond 3 times the median absolute deviation, then refit once.
5. Convert to millimetres
Use the scale from your calibration. For a camera looking straight at a plane, a ChArUco or dot-grid target gives millimetres per pixel at the working distance. For a width measured between two fitted lines, compute the perpendicular distance between the lines, not the distance between two edge points. Then multiply by the scale.
6. Quote an uncertainty, not just a number
A measurement without uncertainty cannot be accepted or rejected honestly. A practical budget has four terms:
- Repeatability. Measure the same stationary part 30 times and take the standard deviation.
- Scale error. Taken from your calibration reprojection error and target tolerance.
- Edge bias. Measure a certified gauge block or pin, and compare. The difference is your bias, which you can subtract.
- Temperature and mechanics. Fixture movement and thermal drift. Measure these over a shift.
Combine the independent terms in quadrature. A common rule is that the expanded uncertainty (k = 2) should be no more than a quarter to a tenth of the tolerance band. If it is not, the fix is optical (more pixels, a telecentric lens, better lighting), and no algorithm change will rescue it.
7. Failure modes we see repeatedly
- Threshold-derived edges that move with lamp ageing. Use gradient-based edges.
- Averaging contour pixels instead of fitting. This biases results toward noise.
- Mixed units between calibration (mm) and the measurement code (pixels).
- Gauging at the image border, where distortion and vignetting are worst.
- Validating on the same parts used to tune the pipeline. Hold out a set of parts measured on a CMM.
8. Ship it with a gauge study
Before handing over, run a gauge repeatability and reproducibility (R&R) study: several parts, several operators or placements, repeated readings. Keep the golden images and results in version control so a later change to OpenCV or your pipeline can be compared against them.
If you need a measurement system built to a stated tolerance, or a second pair of eyes on an existing one, get in touch and one of our senior OpenCV developers will respond.