Python Master Course V2 — 170. Computer Vision Capstone: Synthetic Quality Inspection
Purpose and learning outcomes
Build a complete local inspection prototype for synthetic rectangular parts. The system returns a foreground mask, a bounding box, measurable geometry, and a pass, reject, or review recommendation. You will compare a transparent fill-ratio rule with a learned classifier under nominal and shifted image conditions. This is a learning project, not industrial safety certification or permission to control real equipment.
- Assemble an image-processing pipeline with measurable acceptance rules
- Compare deterministic and learned approaches where appropriate
- Document dataset generation, errors and safe operating limits
Prerequisites
- 161–169: computer vision
Environment and execution
Use a project-specific virtual environment with a currently supported Python 3 release compatible with the packages below. Python 3.11 or 3.12 is a practical starting point. Run shell commands in a terminal, then run the Python blocks in order in one script or notebook kernel. They use only included data and local CPU computation. No account, API key, camera, or external dataset is required. Record the installed package versions with python -m pip freeze when you save your results; a random seed does not guarantee identical numerical behavior across library versions.
python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install numpy scipy scikit-learnUnderstand the model and its assumptions
Begin with a measurement specification. A nominal part is a filled rectangle; a defective part has a notch removed from one side. Position, width, height, brightness, and noise vary independently of defect label. Ground truth comes from the generator's intended geometry, not from the inspection algorithm. That separation lets you discover measurement failures instead of defining success as agreement with your own threshold.
The processing stage thresholds the image, selects the largest connected component, and measures its area relative to its bounding box. A complete rectangle has fill ratio one. A notched rectangle has lower fill ratio while retaining its outer box. The measurement depends on contrast and segmentation, so a low fill ratio can also result from noise or a poor threshold. A component with implausibly little area produces review rather than a confident quality claim.
The deterministic rule passes high-fill parts, rejects clearly low-fill parts, and reviews the middle range. A logistic classifier learns from the same measured features and uses conservative probability bands for its own recommendation. Those probabilities are model scores, not calibrated safety guarantees. Both methods can fail together because they share the segmentation stage; model diversity does not imply independent errors.
Evaluate false acceptance of defective parts, false rejection of good parts, and review workload separately. A system that reviews everything has no automatic false accepts but may be operationally useless. Nominal and lower-contrast noisy tests remain distinct because they answer different questions. All limits and decision bands are fixed before final testing. If validation motivates a change, lock the revision and use fresh test evidence for a defensible final comparison.
Worked example: build it in stages
The script includes generation, measurement, both decision policies, and reporting. Every split uses a distinct seed and stores the synthetic condition through its call parameters. The image inspector validates shape, range, and finite values. It returns the selected mask and box as evidence, while classification consumes only a compact numeric feature vector. No files are uploaded and no real-world actions are triggered.
import numpy as np
from scipy import ndimage
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
def generate(seed, per_class=40, foreground=0.8, noise=0.03):
rng = np.random.default_rng(seed)
images, labels = [], []
for defective in (0, 1):
for _ in range(per_class):
mask = np.zeros((32, 40), dtype=bool)
width, height = int(rng.integers(12, 17)), int(rng.integers(10, 15))
x, y = int(rng.integers(4, 18)), int(rng.integers(4, 14))
mask[y:y+height, x:x+width] = True
if defective:
middle = y + height//2
mask[middle-2:middle+2, x+width-4:x+width] = False
level = foreground + rng.uniform(-0.03, 0.03)
image = np.where(mask, level, rng.uniform(0.08, 0.14))
images.append(np.clip(image + rng.normal(0, noise, image.shape), 0, 1))
labels.append(defective)
return np.array(images), np.array(labels)
def inspect(image):
image = np.asarray(image, dtype=float)
if image.shape != (32, 40) or not np.isfinite(image).all():
raise ValueError("expected a finite 32x40 image")
if image.min() < 0 or image.max() > 1:
raise ValueError("expected intensity range [0, 1]")
labels, count = ndimage.label(image > 0.4)
if not count:
return {"mask": np.zeros_like(image, dtype=bool), "box": None,
"features": np.zeros(4), "valid": False}
sizes = np.bincount(labels.ravel())
sizes[0] = 0
mask = labels == int(sizes.argmax())
yy, xx = np.nonzero(mask)
box = (int(xx.min()), int(yy.min()), int(xx.max()+1), int(yy.max()+1))
width, height = box[2]-box[0], box[3]-box[1]
area = int(mask.sum())
fill = area/(width*height)
features = np.array([fill, area/image.size, width/height, image[mask].mean()])
return {"mask": mask, "box": box, "features": features, "valid": area >= 40}
def matrix(images):
return np.vstack([inspect(image)["features"] for image in images])
train_x, train_y = generate(10)
valid_x, valid_y = generate(20, per_class=20)
nominal_x, nominal_y = generate(30, per_class=30)
shift_x, shift_y = generate(40, per_class=30, foreground=0.48, noise=0.08)
learned = make_pipeline(StandardScaler(), LogisticRegression(max_iter=500))
learned.fit(matrix(train_x), train_y)
def decide(image, method):
result = inspect(image)
if not result["valid"]:
result.update(decision="review", reason="insufficient_foreground", score=None)
return result
if method == "rule":
fill = result["features"][0]
decision = "pass" if fill >= 0.98 else ("reject" if fill <= 0.91 else "review")
score = float(1-fill)
elif method == "learned":
defect_column = int(np.flatnonzero(learned.classes_ == 1)[0])
score = float(learned.predict_proba(result["features"][None, :])[0, defect_column])
decision = "pass" if score <= 0.2 else ("reject" if score >= 0.8 else "review")
else:
raise ValueError("unknown method")
result.update(decision=decision, reason="fixed_decision_bands", score=score)
return result
def report(images, truth, method):
decisions = np.array([decide(image, method)["decision"] for image in images])
defective, good = truth == 1, truth == 0
return {"false_accept_rate": float(np.mean(decisions[defective] == "pass")),
"false_reject_rate": float(np.mean(decisions[good] == "reject")),
"review_rate": float(np.mean(decisions == "review")),
"support": len(truth)}
for method in ("rule", "learned"):
print(method, "validation:", report(valid_x, valid_y, method))
print(method, "nominal test:", report(nominal_x, nominal_y, method))
print(method, "shifted test:", report(shift_x, shift_y, method))
example = decide(nominal_x[0], "rule")
print("example box/decision:", example["box"], example["decision"])What the output means
The output reports measured false-accept, false-reject, and review rates for both methods under each condition, then one example box and decision. No accuracy or safety level is promised. False-accept rate uses defective parts as its denominator; false-reject rate uses good parts. Review rate uses all parts. These denominators must remain visible when comparing policies with different review coverage.
Guided lab and acceptance checks
Deliver the script, generator configuration, schema, and an inspection report. Include masks and boxes for several false accepts, false rejects, and reviewed images, or state explicitly when a category has no examples. Test a blank image, a NaN-containing image, and an image with two parts, documenting that the current largest-component assumption does not support multi-part inspection.
Acceptance requires independent generation seeds, training-only scaling, validation before final assessment, and a review path for inadequate measurements. Add a data-lineage record with split name, seed, image index, and generation parameters. Keep nominal performance separate from the shifted-condition result, and state the acquisition assumptions that any real deployment would have to validate.
Common mistakes and repairs
Do not treat a low model defect score as evidence that a part meets an engineering specification. Do not discard reviewed images when reporting overall workload. Choosing the largest component can hide a missing or extra part, so the input contract must limit scenes to one expected part. Never transfer synthetic thresholds directly to a physical process without independent domain validation.
Questions and answers
Why return masks and boxes with the decision?
They expose what the system measured and support review of segmentation failures. A bare pass label hides whether the part was correctly located. Evidence artifacts make debugging possible without pretending that the decision itself is self-explanatory.
Why compare a rule with a learned model?
The rule is an interpretable baseline tied to a geometric specification. The learned model can combine several measurements but may exploit nuisance correlations. Comparing both on identical held-out conditions reveals whether learning adds useful evidence or only complexity.
Why report review rate beside error rates?
A cautious policy can avoid automatic errors by deferring many cases. That can be appropriate, but it creates work and reduces automatic coverage. Error rates without review volume hide an important operational tradeoff.
Can both methods fail on the same shifted image?
Yes. Both depend on threshold-based foreground extraction. Low contrast can damage that shared representation before either decision policy runs. Agreement between the methods therefore does not establish independent confirmation or higher reliability.
What would be needed before real industrial use?
A validated physical specification, representative acquisition data, measurement calibration, appropriate risk review, tested failure handling, and independent performance evidence. This educational generator and prototype provide none of the certification or assurance required for safety-critical control.
Exercises
1. Confirm that a blank image enters review. 2. Confirm that NaN input is rejected. 3. Construct a clean full rectangle and a notched version to test the rule independently of random generation. Explain why passing these tests does not establish operational reliability.
Worked solutions and reasoning
The fixture isolates decision logic: a full rectangle has fill ratio one, while removing twenty pixels from a 192-pixel box gives a fill ratio below 0.91. These tests verify a declared mechanism; they do not measure lighting variation, physical tolerances, rare defects, or real-process risk.
assert decide(np.zeros((32, 40)), "rule")["decision"] == "review"
bad = np.zeros((32, 40)); bad[0, 0] = np.nan
try:
inspect(bad)
raise AssertionError("expected invalid-input rejection")
except ValueError:
pass
fixture = np.zeros((32, 40))
fixture[8:20, 10:26] = 0.8
assert decide(fixture, "rule")["decision"] == "pass"
notched = fixture.copy()
notched[12:16, 21:26] = 0
assert decide(notched, "rule")["decision"] == "reject"Recap
The capstone joins input validation, segmentation, geometry, classification, and selective decisions into one inspectable system. Its strongest deliverable is a reproducible account of assumptions, errors, and review behavior. Synthetic success is a foundation for learning and testing, not a substitute for real-world qualification.
Official references
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.