From Notebook to Factory Floor: What Breaks When a Defect-Detection Model Meets Real Cameras
Our guides are based on hands-on testing and verified sources. Each article is reviewed for accuracy and updated regularly to ensure current, reliable information.Read our editorial policy.
A defect-detection model can score 98% on a held-out test set and still let cracked parts ship. The notebook grades the model against a frozen dataset. The factory grades the whole system: camera, light, conveyor, threshold, operator, and the cost of every miss.
This article walks through the four places where that gap usually opens, with Python examples you can adapt to your own pipeline. The running example is a public case: a Tier-1 European automotive supplier whose cast aluminum brake calipers had a 0.8% micro-fracture escape rate, putting its OEM contracts at risk.
The Setup: Asymmetric Costs at Line Speed
The supplier did not need a generic vision API. It needed a custom automated optical inspection (AOI) station that could catch visible hairline fractures on cast aluminum without slowing the line. According to the published case study by Yalantis, the system achieved a reported defect detection accuracy of 99.7% and recovered its investment in eight months.
Those are reported end-state numbers. Getting there means respecting one fact that notebooks can hide: the two error types do not cost the same.
- False negative (missed crack): The defective part passes inspection and may reach the customer. This can lead to safety risks, penalties, and lost contracts.
- False reject (good part flagged): The part goes to manual review or scrap. This costs labor and material, but it stays inside the plant.
Every fix below involves managing these two costs without compromising the required inspection standard.
Optical inspection is also limited to defects that the imaging system can resolve. Subsurface defects or cracks that are not adequately visible may require additional inspection methods.
Break 1: The Light Changes, and the Model Doesn’t Know
Training images are often captured under controlled lighting conditions. Production lighting can be less stable. Lamps age, a loading-dock door lets in daylight, lens covers collect dust, and machined aluminum throws reflections that shift with every few millimeters of part position.
The fix has three layers: control what you can, augment what you can’t, and monitor everything.
Control. Enclose the station, use suitable diffuse or structured lighting, and lock camera exposure and gain where appropriate. Every source of unwanted variation you remove in hardware is one less variable the model has to handle.
Augment. Train on the variation you actually measured on the line, not on arbitrary ranges: small brightness and contrast shifts, mild gamma changes, sensor noise, slight motion blur, and part offsets of a few millimeters. Keep the ranges honest. A hairline crack can appear as a subtle contrast change, so aggressive contrast augmentation can teach the model to ignore the very signal it should catch.
Monitor. Track simple image statistics, such as mean brightness and contrast, over a rolling window of frames, and compare them with a representative production baseline.
A deviation of about three baseline standard deviations can serve as an initial alert threshold, but it should be adjusted using actual production variability and false-alarm rates. You can plot sample brightness measurements across shifts using a line graph maker to visualize these trends.
A dimming lamp is a hardware ticket, not a data science problem.
Break 2: The Threshold Was Tuned on the Wrong Data
A default threshold of 0.5 is not necessarily appropriate for a production line. The right threshold comes from a recall target agreed with quality engineering, measured on validation data captured at the actual station, across shifts and casting batches.
Start from recall, because a missed crack is the expensive error. Recall measures the proportion of actual defective parts that the model correctly identifies. Then read off the false-reject rate you pay for it.
The following example assumes binary labels, where 1 represents a defective part, 0 represents a good part, and higher scores indicate a greater likelihood of a defect. The 99.7% recall target is illustrative, not a universal inspection requirement.
import numpy as np
from sklearn.metrics import precision_recall_curve
def pick_threshold(y_true, defect_scores, target_recall=0.997):
y_true = np.asarray(y_true)
scores = np.asarray(defect_scores, dtype=float)
if (
y_true.ndim != 1
or scores.ndim != 1
or y_true.shape != scores.shape
or set(y_true) != {0, 1}
or not np.isfinite(scores).all()
):
raise ValueError(
"Use aligned, finite scores and both binary classes (0 and 1)"
)
if not 0 < target_recall <= 1:
raise ValueError("Target recall must be in (0, 1]")
precision, recall, thresholds = precision_recall_curve(
y_true, scores
)
# Recall is non-increasing as the threshold rises.
# thresholds has len(recall) - 1 entries.
ok = np.where(recall[:-1] >= target_recall)[0]
if len(ok) == 0:
raise ValueError(
"Target recall is not reachable on this validation set"
)
# Highest threshold that still meets the recall target
i = ok[-1]
return thresholds[i], precision[i], recall[i]
def false_reject_rate(y_true, defect_scores, threshold):
y_true = np.asarray(y_true)
scores = np.asarray(defect_scores, dtype=float)
if (
y_true.ndim != 1
or scores.ndim != 1
or y_true.shape != scores.shape
or not np.isin(y_true, [0, 1]).all()
or not np.any(y_true == 0)
or not np.isfinite(scores).all()
or not np.isfinite(threshold)
):
raise ValueError(
"Use aligned, finite scores, binary labels, and good parts"
)
return float((scores[y_true == 0] >= threshold).mean())
# Illustrative validation data
y_true = [0, 0, 1, 1]
defect_scores = [0.10, 0.40, 0.35, 0.80]
threshold, precision, recall = pick_threshold(
y_true, defect_scores
)
print(f"Threshold: {threshold:.2f}")
print(f"Precision: {precision:.2%}")
print(f"Recall: {recall:.2%}")
print(
f"False-reject rate: "
f"{false_reject_rate(y_true, defect_scores, threshold):.2%}"
)Output:
Threshold: 0.35
Precision: 66.67%
Recall: 100.00%
False-reject rate: 50.00%Once you select a threshold, evaluate it on an independent test set with enough representative defective parts to support the required level of statistical confidence.
If the false-reject rate at your recall target is too high, do not simply lower the target. That trade can quietly move the cost from your plant to your customer. Fix the inputs instead: better optics, cleaner labels, or more real defect images.
Revalidate the system whenever the camera, lighting, part supplier, or casting mold changes. Each of those can shift the score distribution, and yesterday’s threshold may no longer perform as expected.
Break 3: Fast on Average, Late When It Matters
The line does not care about mean latency alone. A slow frame can mean a missed inspection deadline or a stopped conveyor. Budget backwards from line speed and the required rejection deadline:
- At 120 parts per minute, a new part arrives every 500 milliseconds.
- The available inspection time depends on conveyor speed, camera placement, processing concurrency, and the distance to the reject actuator.
- Image acquisition, transfer, preprocessing, and reject actuation must all fit within the available end-to-end decision budget.
Measure on the target hardware, with your real preprocessing, after sufficient warm-up runs. Report the 99th percentile (p99), alongside other latency measurements, rather than relying on the mean alone.
If you export benchmark timings to a spreadsheet, an Excel formula generator can help you find the appropriate percentile calculation.
On a GPU, synchronize before you stop the clock when measuring completed inference with a CPU-side timer, or you may time the kernel launch instead of the completed inference.
If p99 is over budget, common options include cropping to the region of interest instead of feeding the full frame, using an optimized runtime such as ONNX Runtime or TensorRT, quantizing the model, or changing the architecture.
Revalidate defect detection performance after these changes. The system should also have a defined response for missed frames, camera failures, and decisions that arrive too late.
Break 4: Nobody Agreed on What a Defect Looks Like
On cast aluminum, a hairline crack and a harmless casting mark can look almost identical. If two experienced inspectors label the same images differently, the model can learn their disagreement as noise.
Measure agreement before you train: Cohen’s kappa between two inspectors labeling the same images is a quick check. A score below roughly 0.6 can indicate that the labeling guide needs review, although this is not a universal acceptance threshold.
For rare defects, examine class-specific agreement and the actual disagreements between inspectors as well.
A labeling guide with reference images for each defect class, plus the borderline cases, can improve agreement before you make any architecture changes.
Even with clean labels, some parts will land near the threshold. Route them to a person instead of forcing a call.
The following example uses an illustrative review band of 0.10. Its width should be adjusted to the model’s score scale and validated against actual inspection outcomes.
import numpy as np
def route(defect_score, threshold, review_band=0.10):
"""Return 'reject', 'pass', or 'review' for one part."""
if (
not np.isfinite(
[defect_score, threshold, review_band]
).all()
or review_band < 0
):
raise ValueError(
"Invalid score, threshold, or review band"
)
if defect_score >= threshold + review_band:
return "reject"
if defect_score < threshold - review_band:
return "pass"
return "review"
print(route(0.85, 0.60))
print(route(0.30, 0.60))
print(route(0.58, 0.60))Output:
reject
pass
reviewSize the review band to your inspectors’ capacity: count how many validation parts fall inside it and convert that to parts per shift. Validate the complete routing process against the required defect detection and false-reject targets. Parts awaiting review should not be released automatically.
Then feed verified and deduplicated reviewed samples back into the training set, keeping independent evaluation data separate. The review queue is not a stopgap; it is where your next, better dataset comes from.
The inspection system developed by the Yalantis computer vision team illustrates why optics, model development, and production integration need to be considered together rather than as separate projects.
Pre-Ship Checklist
Before a vision model goes live on a line, every item below should have an owner and a yes:
- Validation data was captured at the production station, across shifts and part batches.
- Augmentation ranges come from measured lighting and position variance.
- An input drift monitor is wired to maintenance alerts, not just a dashboard.
- The threshold comes from a recall target agreed with quality engineering, and the corresponding false-reject rate is documented.
- Detection performance was evaluated on an independent, representative test set.
- p99 and end-to-end inspection latency were measured on the target hardware with real preprocessing.
- A defined response exists for missed frames, camera failures, and missed inspection deadlines.
- A labeling guide with reference images exists, and inspector agreement was measured.
- The review queue is sized to inspector capacity, and verified reviewed samples flow back into training.
- A revalidation trigger is defined for changes such as a new camera, lamp, supplier, or mold.
None of these items is directly about model architecture. That is the real lesson of the notebook-to-factory gap: getting the model right is only one part of building a reliable inspection system.



Comments
Comments are provided by Disqus, which sets cookies and processes data under its own privacy policy.