26 min read · Machine vision

A high-resolution camera can tell you which pixel an edge of the part sits on. It cannot tell you how many millimeters one pixel is, and that number is not the same across the image, because the lens bends the picture, especially near the edges. Turning pixels into millimeters therefore needs a step called calibration, and it needs a second step that checks the result is good enough to judge real parts, not just good to look at.
This article uses plain Python with numpy only, no OpenCV. It simulates one camera, finds its parameters from a dot-grid target, corrects distortion, and then checks the measuring system with a gauge block. You get code to run yourself, real output and a test suite. A manager can follow the explanations and tables; an engineer can run the code.
The real problem: the center of the image looks fine, the edge is off by half a millimeter
The following are hypothetical scenarios to make the point. They are not projects of any BT San customer.
- Plastic parts factory (hypothetical): a camera measures part width, with the scale set at the center of the image using a gauge. It passes every time, but a part placed near the edge of the image is measured wrong by almost half a millimeter, because the lens squeezes the edge of the image inward.
- Assembly line (hypothetical): someone bumps the camera stand. The image is still sharp and the program runs normally, but every reading shifts, because the camera has rotated and the working distance has changed slightly. Nobody notices until the customer sends parts back.
- Quality inspection room (hypothetical): the lens is changed to get a wider view, and the old calibration values are kept. The readings are wrong in both scale and distortion, but reports still come out complete as before.
These three cases need two different jobs. The first is calibration: find the relationship between pixels and millimeters and correct distortion. The second is validation: confirm, using a reference part of known value, that the measuring system is accurate and repeatable enough compared with the tolerance, and repeat the check every time conditions change.
Facts from the sources we checked
| Topic | What the source says | Effect on this example |
|---|---|---|
| Calibration with a flat target | Zhang (2000) uses a flat patterned target photographed in at least two poses. You can move either the camera or the target, without knowing the motion. The paper simulates radial distortion and solves in closed form first, then refines by maximum likelihood. | Our example is much simpler (one pose, no perspective). A real setup should use several poses. |
| Gauge R&R | NIST states that a Gauge R&R study looks at how a gauge behaves in one particular environment, and has four main topics: repeatability, reproducibility, stability and bias. | We measure the gauge repeatedly to see repeatability, and compare with the reference value to see bias. |
| Resolution | NIST states that studying a gauge whose resolution is insufficient for the measurement need yields no useful information. | Always compare the size of 1 pixel in millimeters against the tolerance first. |
| Bias and the reference part | NIST explains that the ideal is to take the difference between the measured value of a test part and the measured value of a reference part. But if the assumption that the reference part is stable over time does not hold (for example, the instrument drifts), this method does not remove all of the bias. | Measure the reference part again at intervals, not just once at installation. |
| P/T ratio | The Wikipedia page on Gauge R&R defines the P/T ratio as the ratio of the precision of the measuring system to the total tolerance. It states that below 0.1 the system can judge pass/fail reliably, and above 0.3 a bad part may be measured as good. | We use 0.1 and 0.3 as a screening guide. The formula using 6 times the standard deviation is our own rule. |
| Uncertainty | NIST has a set of guidance and tools (the Uncertainty Machine) for expressing the uncertainty of measurement results according to the GUM. | This example does not build a full uncertainty budget. See the production notes section at the end of the article. |
The 10:1 rule of resolution to tolerance that people in the field often mention was not read by the author from a verifiable source in this round. It is used here as a rough rule of thumb for the example (you want at least about 10 pixels across the tolerance band), not as a standard requirement.
Overview of the example
The code is in the folder examples/camera-calibration-measurement-validation/. It uses Python 3 with numpy only, needs no additional installs and uses no network. The simulated camera looks at a grid of 17 by 13 dots with 4.5 mm spacing. The true scale is 20 pixels per mm, the rotation is 1.2 degrees, the image is 1600 pixels wide, and the distortion is k1 = -0.030 and k2 = 0.008. The dot detector has 0.10 pixel of noise. All the numbers are generated by us.
| File | Purpose |
|---|---|
| camera.py | Camera model: rotation, scale, distortion, and conversion between millimeters and pixels in both directions |
| fit.py | Finds the parameters with Levenberg-Marquardt |
| validate.py | Repeated gauge measurement, summary of bias, repeatability and P/T, a decision rule, and a reader for a readings file that contains bad rows |
| demo.py / test_calibration.py | A script that runs the whole process in 5 parts, and a unittest suite with 5 cases |
| data/gauge_readings.csv | Sample readings deliberately mixed with blank rows, text and negative values |
Step 1: the camera model, from millimeters to pixels and back
The order in the model is: rotate the coordinates on the target, multiply by the scale to get pixels, apply distortion, then add the image center. Radial distortion pulls points that are far from the center inward or pushes them outward according to the square and the fourth power of the radius. A negative k1 squeezes the image edge inward (barrel). We divide the radius by 1000 pixels before raising it to a power, so k1 and k2 are numbers of a size near 1, which makes the solver more stable.
def distort(u, k1, k2):
"""u: (N,2) ideal offsets from the centre in px -> distorted offsets."""
rn2 = (u ** 2).sum(axis=1, keepdims=True) / R0 ** 2
return u * (1 + k1 * rn2 + k2 * rn2 ** 2)
def undistort(d, k1, k2, iters=20):
"""Invert distort() by fixed-point iteration (fine while |k| is small)."""
u = d.copy()
for _ in range(iters):
rn2 = (u ** 2).sum(axis=1, keepdims=True) / R0 ** 2
u = d / (1 + k1 * rn2 + k2 * rn2 ** 2)
return uThere is no direct closed-form formula for undoing the distortion, so we iterate. The iteration converges when k is small, which is the normal case for ordinary lenses.
def world_to_pixel(p, xy):
scale, theta, cx, cy, k1, k2 = p
u = scale * xy @ rot(theta).T
return distort(u, k1, k2) + np.array([cx, cy])
def pixel_to_world(p, uv, correct=True):
"""correct=False ignores k1/k2: the 'before calibration of lens' reading."""
scale, theta, cx, cy, k1, k2 = p
d = uv - np.array([cx, cy])
u = undistort(d, k1, k2) if correct else d
return (u @ rot(theta)) / scale # u @ R equals R^-1 u for row vectorsThe switch correct=False is the "scale only, no lens correction" reading. This is what many systems actually do when they set the scale at the center of the image. We use it as the before-correction value in the comparison.
Step 2: find the parameters by least squares
What we know is the true coordinates of the dots on the target (mm) and the pixel positions that were detected. We need to find scale, theta, the center cx cy, k1 and k2 that make the difference between the pixels the model predicts and the pixels that were detected as small as possible. The example uses Levenberg-Marquardt with a numerically computed Jacobian, which keeps the code short enough to read in one piece.
def fit(xy, uv, init, fit_k2=True, iters=60):
"""Levenberg-Marquardt with a numeric Jacobian.
simplified: dots are matched to the grid by index (the detector already sorted
them), no outlier rejection, no tangential term. Production: use a vetted
solver (OpenCV calibrateCamera) with several target poses and robust loss.
"""
n = 6 if fit_k2 else 5
p = np.array(init[:n], dtype=float)
lam = 1e-3
cost = (residuals(p, xy, uv, fit_k2) ** 2).sum()
steps = np.array([1e-3, 1e-5, 1e-2, 1e-2, 1e-5, 1e-5])[:n]
for _ in range(iters):
r = residuals(p, xy, uv, fit_k2)
J = np.empty((r.size, n))
for j in range(n):
d = np.zeros(n)
d[j] = steps[j]
J[:, j] = (residuals(p + d, xy, uv, fit_k2) - r) / steps[j]
A, g = J.T @ J, J.T @ r
while True:
try:
dp = np.linalg.solve(A + lam * np.diag(np.diag(A)), -g)
except np.linalg.LinAlgError:
lam *= 10
continue
new = (residuals(p + dp, xy, uv, fit_k2) ** 2).sum()
if new < cost:
p, cost, lam = p + dp, new, lam / 3
break
lam *= 4
if lam > 1e12:
return np.array([*p, 0.0])[:6] if not fit_k2 else p
if np.abs(dp).max() < 1e-10:
break
return np.array([*p, 0.0]) if not fit_k2 else p- You need a starting guess close enough to the truth. In the example we use the scale from the lens spec, 19 pixels per mm (the true value is 20), and the center at the middle of the image.
- The variables differ greatly in size (the scale is in the tens, k is around one hundredth), so we use different step sizes when computing the Jacobian.
- The example matches points to the grid in order and does not reject outliers. A real system needs both.
Step 3: measure the error in millimeters, before and after correction
Evaluating with the same points used for the fit looks better than reality. So we generate a second grid, shifted by half the spacing (held-out), that the fit has never seen. We convert its pixels to millimeters, compare with the true positions, and group the results by distance from the image center.
def edge_error_table(label, cam_p, uv, xy):
err = np.linalg.norm(pixel_to_world(cam_p, uv, correct=label == "after") - xy, axis=1)
r_px = np.linalg.norm(uv - cam_p[2:4], axis=1)
bands = [(0, 250), (250, 500), (500, 750), (750, 2000)]
cells = [f"{err[(r_px >= a) & (r_px < b)].mean():.3f}" for a, b in bands]
print(f" {label:6s} " + " ".join(f"{c:>8s}" for c in cells) + f" max {err.max():.3f}")1) fitted parameters vs simulated truth
scale px/mm true 20.00000 fit(k1 only) 19.97453 fit(k1,k2) 20.00090
theta rad true 0.02094 fit(k1 only) 0.02095 fit(k1,k2) 0.02095
cx px true 812.00000 fit(k1 only) 811.98989 fit(k1,k2) 811.98989
cy px true 597.00000 fit(k1 only) 596.98841 fit(k1,k2) 596.98841
k1 true -0.03000 fit(k1 only) -0.02308 fit(k1,k2) -0.03026
k2 true 0.00800 fit(k1 only) 0.00000 fit(k1,k2) 0.00822
2) mm error on held-out dots, by distance from the image centre (px)
0-250 250-500 500-750 >750
before 0.010 0.089 0.323 0.646 max 0.859
after 0.006 0.006 0.006 0.006 max 0.017
k1-only fit, corrected: max 0.041 mm (k2 left out of the model)
3) gauge block 20.0 mm, 25 repeats, tolerance band 0.2 mm
1 px = 0.050 mm; tolerance band = 4.0 px (below the 10 px-per-band rule of thumb, so edges must be sub-pixel)
centre raw mean 19.9748 bias -0.0252 sd 0.0066 P/T 0.20 FAIL: bias, recalibrate
centre corrected mean 19.9997 bias -0.0003 sd 0.0061 P/T 0.18 MARGINAL: decide by risk
edge raw mean 19.4279 bias -0.5721 sd 0.0057 P/T 0.17 FAIL: bias, recalibrate
edge corrected mean 20.0010 bias +0.0010 sd 0.0061 P/T 0.18 MARGINAL: decide by risk
4) after the camera is bumped or moved (old calibration kept)
nudged: 0.8 deg + centre shift 15 px centre bias +0.0003 MARGINAL: decide by risk
nudged: 0.8 deg + centre shift 15 px edge bias +0.0217 FAIL: bias, recalibrate
working distance +1.5 % (scale) centre bias -0.2992 FAIL: bias, recalibrate
working distance +1.5 % (scale) edge bias -0.2994 FAIL: bias, recalibrate
5) readings file with bad rows
used 7, skipped 3; mean 20.0016 sd 0.0037Reading the results part by part
- Part 1: when both k1 and k2 are fitted, the scale is 20.0009 against 20, the angle is 0.02095 radians against 0.02094, and k1 is -0.0303 against -0.030. The center is off by less than two pixels. If only k1 is fitted although the truth includes k2, the scale drifts to 19.975 and k1 is pulled to -0.0231, because it has to compensate for the part the model does not have.
- Part 2: before correction, the mean held-out error is 0.010 mm at the center, then grows to 0.089, 0.323 and 0.646 mm as the distance increases, with a maximum of 0.859 mm. After correction, every band is about 0.006 mm (maximum 0.017), which is the level of the 0.10 pixel noise at 20 pixels per mm.
- If only k1 is fitted and then used for correction, the maximum error falls to 0.041 mm. That is much better than no correction but worse than the full model. It shows you must choose enough distortion terms.
- Part 3: a 20.000 mm reference gauge block is measured 25 times at the center. Without distortion correction the result is 19.9748 (bias -0.025); with correction it is 19.9997. At the edge of the image, without correction it is 19.428 (bias -0.57 mm); with correction it is 20.001. The standard deviation (repeatability) is about 0.006 mm whether or not we correct, because distortion is a systematic error, not a random one.
- Part 4: when the camera is moved and the old calibration is kept: a 0.8 degree rotation with the center shifted by 15 pixels gives almost zero bias at the center (+0.0003), but at the edge it is +0.022 mm, which fails the criterion. A small change in working distance changes the scale by 1.5 % and gives a bias of about -0.30 mm at both positions.
- Part 5: the readings file has 10 rows; 7 are usable and 3 are skipped (blank row, text, negative value). The mean is 20.0016.
One important observation: checking the gauge at the center of the image alone is not enough. When the camera is bumped and rotates slightly, the result at the center still passes everything, but the edge of the image no longer passes. Always check the gauge at several positions in the field of view, especially the corners and edges.
Step 4: check the measuring system: bias, repeatability and the ratio to tolerance
Calibration says the model fits the points on the target. It does not say the measuring system is good enough for the job. You need to measure a part of known value (a gauge block) many times to get three numbers: the mean compared with the reference value is the bias, the standard deviation is the repeatability, and the P/T ratio compares repeatability with the tolerance of the part.
def measure_length(p_cal, cam, a_mm, b_mm, noise_px, rng, correct=True):
"""Image two end points of a gauge with the REAL camera, convert with the CALIBRATION."""
ends = np.array([a_mm, b_mm], dtype=float)
uv = world_to_pixel(cam.p, ends) + rng.normal(0, noise_px, (2, 2))
w = pixel_to_world(p_cal, uv, correct)
return float(np.linalg.norm(w[1] - w[0]))
def summarise(values, reference, total_tol):
v = np.asarray(values, dtype=float)
mean, sd = v.mean(), v.std(ddof=1)
return {"n": len(v), "mean": mean, "bias": mean - reference, "sd": sd,
"pt": 6 * sd / total_tol} # simplified: P/T with 6 sigma; see README
def verdict(s, total_tol, bias_limit_frac=0.05, pt_ok=0.1, pt_bad=0.3):
"""Our own screening rule, not a standard: bias within 5% of tolerance, P/T bands 0.1/0.3."""
if abs(s["bias"]) > bias_limit_frac * total_tol:
return "FAIL: bias, recalibrate"
if s["pt"] > pt_bad:
return "FAIL: repeatability"
return "MARGINAL: decide by risk" if s["pt"] > pt_ok else "PASS"- In the hypothetical example, the tolerance is ±0.100 mm, 0.200 mm in total, and 1 pixel equals 0.050 mm. That gives only 4 pixels across the tolerance band, below the 10-pixel rule we use as a rough guide. The result therefore depends on subpixel edge finding, which has to be proven with real repeated measurements.
- In the example, P/T uses 6 times the standard deviation divided by the total tolerance, which gives about 0.18, between 0.1 and 0.3. Our rule therefore answers MARGINAL. Decide according to risk. For example, if a bad part reaching the customer would cause large losses, improve the repeatability first.
- The bias criterion in the example is no more than 5 % of the total tolerance (0.010 mm). This is a screening rule we set ourselves, not a standard. A real job must set it according to the consequences for that job.
- Good repeatability does not mean accuracy. A system that does not correct distortion repeats very well but is off by 0.57 mm at the edge. This is why you must look at bias together with repeatability.
Measurement files from the shop floor are rarely clean, so there is a reading function that skips bad rows and counts them, rather than letting negative values or blanks into the average.
def load_readings(path):
"""Read mm values from CSV; skip blanks and non-numbers and count them."""
good, skipped = [], 0
with open(path, newline="") as f:
for row in csv.DictReader(f):
try:
x = float(row["length_mm"])
if not np.isfinite(x) or x <= 0:
raise ValueError
good.append(x)
except (ValueError, TypeError, KeyError):
skipped += 1
return good, skippedTest suite
test_calibration.py has 5 cases. They check that undistort reverses distort, that the fit recovers the simulated parameters within a set tolerance, that distortion correction reduces the error at the edge, that the system warns when the scale changes, and that a bad readings file is skipped correctly. The result is 5 cases passed (python3 -m unittest).
def test_correction_cuts_edge_error(self):
p = fit(self.xy, self.uv, INIT)
held = dot_grid(16, 12, 4.5, offset=(2.25, 2.25))
uvh = detect(TRUE, held, 0.10, self.rng)
far = np.linalg.norm(uvh - p[2:4], axis=1) > 600
before = np.linalg.norm(pixel_to_world(p, uvh, correct=False) - held, axis=1)[far].mean()
after = np.linalg.norm(pixel_to_world(p, uvh) - held, axis=1)[far].mean()
self.assertGreater(before, 0.2)
self.assertLess(after, 0.02)
self.assertLess(after, before / 20)The conditions used are: the error before correction at the edge is greater than 0.2 mm, after correction it is less than 0.02 mm, and it falls by at least a factor of 20. If someone changes the model so that the correction stops working, the test suite fails.
In real use: what this example does not do
- Use a reference target that is manufactured and certified to an accuracy far better than the job's tolerance, and know its coefficient of thermal expansion. If the target itself is off or expands, the whole calibration is skewed with it.
- Photograph the target in several poses so the camera's intrinsic parameters are estimated stably, and cover the whole image area including the corners (following Zhang's approach, which uses at least two poses).
- If the camera is not perpendicular to the work surface, you need a perspective or homography model. This example does not have one.
- Part height relative to the target: if the surface being measured is not in the same plane as the target during calibration, the scale will differ. A telecentric lens reduces this problem but does not eliminate it.
- The edge finder and the dot-center finder (subpixel) are another layer of error that the example simulates with plain smooth noise. In real life it depends on lighting, contrast and surface.
- The acceptance data set needs multiple parts, multiple positions, multiple days, and multiple operators or machine setups. If you need a full Gauge R&R that separates out reproducibility, follow the definition NIST gives.
- Present measurement results with their uncertainty, compared against a budget built from several sources (target, lens, edge finding, temperature), following the approach NIST describes. This example looks only at repeatability and bias.
Hypothetical examples: applying this to the three businesses
Measuring stamped parts of various sizes
If a part is so large that it fills the image, its edge lies in the zone where distortion is greatest. So correct the distortion and check the gauge at the edge. If the tolerance is tighter than what 4 pixels per tolerance band can deliver, increase the resolution or split the measurement across several cameras.
Checking hole positions on an assembly plate
Here we care about distances between points across the whole part. A scale error of 1.5 % makes a 100 mm hole spacing wrong by about 1.5 mm. Checking a gauge or a dot target in the same position at the start of every shift catches a moved camera before a bad lot is made.
Incoming inspection room
With several operators and several parts per day, you should run a real Gauge R&R that separates reproducibility, and record the gauge measurement at the start of every shift on a control chart, so you can see drift before values leave the limits.
Common mistakes and a checklist
- Setting the scale at the center of the image with one part and believing the whole image is correct
- Evaluating accuracy with the same points used for the fit, which looks better than reality
- Looking only at repeatability (a low standard deviation) and concluding the system is accurate
- Continuing to use the old calibration after changing the lens, the working distance or the mount
- Checking the gauge only at the center of the image, when problems usually show up at the edge first
- Using a reference target whose true values are unknown or that is less accurate than the system being checked
- Ignoring temperature and vibration of the camera mount
- Choosing a pass criterion without looking at the consequences for the job (the rules in this example are only a screening guide)
- State what must be measured, the range of positions in the image, and the tolerance.
- Calculate the size of 1 pixel in millimeters and compare it with the tolerance.
- Calibrate with a target of known values, in several poses that cover the whole image.
- Evaluate with points or parts not used for the fit, and look at the error by distance from the center.
- Measure a reference gauge at least 25 times, at several positions, to get bias, repeatability and P/T.
- Set the decision criteria and the re-check frequency before putting the system into use.
- Re-check with the gauge every time the camera is bumped, the lens is changed, the mount is moved or the working distance changes, and routinely at the start of every shift.
Caveats of this example: it is a simulation with data we generated ourselves. There are no real images, no perspective, only one pose, no tangential distortion, no outlier rejection and no uncertainty budget. The pass/fail criteria are the example's own screening rules. Use it as a learning model, not as production-ready code. Values such as 10:1 are rules of thumb and must be set according to your own job's quality documents.
References
- Zhang — A Flexible New Technique for Camera Calibration (IEEE TPAMI 2000) (accessed 2026-11-21)
- NIST/SEMATECH e-Handbook — Gauge R&R studies: important issues (repeatability, reproducibility, stability, bias) (accessed 2026-11-21)
- NIST/SEMATECH e-Handbook — Resolution of the measurement (accessed 2026-11-21)
- NIST/SEMATECH e-Handbook — Bias in calibration against a reference standard (accessed 2026-11-21)
- NIST — Uncertainty of Measurement Results (TN 1297, Uncertainty Machine) (accessed 2026-11-21)
- Wikipedia — Gauge R&R (repeatability, reproducibility, P/T ratio thresholds) (accessed 2026-11-21)




