Matlab Use Visual Inspection
MathWorksOfficialCreated by MathWorks
- Skill
- Tool integration
- Software development
- BSD-2-Clause
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured approach to developing machine vision inspection systems, guiding users through the selection of rule-based, AI-based, or hybrid pipelines. It covers the entire development lifecycle, from initial problem analysis and data preparation to model training and deployment across various hardware targets, including embedded systems, GPUs, and industrial PLCs.
What it does
- Selects between rule-based, AI-based, or hybrid inspection strategies.
- Implements anomaly detection, object detection, counting, and gauging.
- Supports synthetic data generation for training augmentation.
- Provides deployment paths for standalone apps, C/C++, TensorRT, ONNX, and PLCs.
- Offers guidance on vision fixturing and calibrated measurements.
- Includes specific patterns for high-performance production inference.
When to use it
- When building automated defect detection or classification systems.
- When performing precise dimensional measurements or gauging on parts.
- When counting objects with varying levels of visual complexity.
- When deploying inspection models to edge devices or industrial controllers.
- When you need to combine geometric rule-based logic with AI-based flexibility.
Advantages
- Covers the full development arc from problem selection to deployment.
- Provides clear decision criteria for choosing between rule-based and AI approaches.
- Optimized for industrial performance with support for hardware-specific acceleration.
- Includes robust patterns for vision fixturing and pose normalization.
- Reduces development time by providing pre-built functions for common inspection tasks.
Usage examples
- “How do I choose between rule-based and AI-based inspection for my manufacturing line?”
- The skill provides a decision matrix comparing defect predictability, lighting control, data availability, and the need for explainability to guide your choice.
- “I need to deploy a deep learning inspection model to an NVIDIA Jetson device.”
- The skill instructs you to use GPU Coder with TensorRT, providing specific rules for model loading and export to ensure high-performance inference.
- “How can I measure parts in millimeters when my camera has lens distortion?”
- The skill guides you to use camera calibration and imageToWorldPlane to rectify the image, enabling direct measurement in physical units using regionprops.
- “My parts move on a conveyor; how do I ensure my anomaly detector works?”
- The skill mandates using matchshape for vision fixturing to normalize the part pose before passing the cropped region to the anomaly detector.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/matlab/matlab-use-visual-inspection/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip matlab-use-visual-inspection.zip -d .agents/skills
Documentation by MathWorks
Visual Inspection with MATLAB
Build machine vision inspection systems using Visual Inspection Toolbox. Select the right approach — rule-based, AI-based, or hybrid — based on problem characteristics, then implement, train, and deploy.
When to Use
Defect detection and classification
Detecting anomalies on manufactured parts (scratches, dents, contamination)
Training anomaly detectors with good-part images only (one-class learning)
Detecting and localizing defects with bounding boxes (YOLOX)
Classifying defect types or severity levels
Measurement and gauging
Measuring widths, gaps, angles, diameters on parts
Calibrated measurement in physical units (mm, degrees)
Vision fixturing — locating parts and repositioning measurement tools
Blob analysis — area, perimeter, shape metrics of segmented regions
Counting and localization
Counting identical rigid parts via shape matching
Few-shot counting with intra-class variation (CounTR)
Locating parts by edge geometry for downstream inspection
Training data augmentation
Generating synthetic labeled data via copy-paste augmentation
Expanding small defect datasets for YOLOX training
Deployment
Packaging inspection as standalone executables (MATLAB Compiler)
Generating C/C++ for embedded/edge targets (MATLAB Coder)
GPU-accelerated inference with TensorRT (GPU Coder)
ONNX export for NPUs, AI accelerators, smart camera SDKs
Deploying to Beckhoff TwinCAT industrial PLCs
When NOT to Use
Camera acquisition, frame grabber configuration — use Image Acquisition Toolbox
PLC communication, OPC UA, MQTT protocols — use Industrial Communication Toolbox
General image processing unrelated to inspection (artistic filters, medical imaging)
Must-Follow Rules
Approach Selection
Rule-based for geometric, deterministic problems — when defects are dimensional deviations or parts have known geometry, use caliper/fitcircle/matchshape. No training data needed
AI-based for variable appearance — when defect appearance can't be enumerated, use anomaly detection or YOLOX. Requires training data
Hybrid when parts move — use
matchshapeto fixture (locate + normalize pose), then AI on the cropped/warped region. Anomaly detectors are NOT rotation/scale invariant
Anomaly Detection
Anomaly detectors require consistent pose — CNN backbones are not rotation/scale invariant. Fixture with
matchshape+imwarpto canonical orientation before training and inferenceChoose detector by data availability — >100 good images:
studentTeacherAnomalyDetector; <100 images:patchCoreAnomalyDetector; have anomaly labels:fcddAnomalyDetectorUse
classifyfor inference — returns[tf, score, map]for anomaly map visualization
Object Detection (YOLOX)
Use
AutoResize=falsefor full-resolution inference — prevents downscaling that loses small defects. Pair with tiled training when objects are small relative to imageSynthetic data benefits YOLOX most — copy-paste augmentation via
objectInsertionDatastoreis proven for detection tasks
Measurement
Vision fixturing pattern —
matchshapelocates part → transform measurement positions to detected pose → measure at repositioned locationsCalibrated measurements require
imageToWorldPlane— converts pixel measurements to physical units using camera calibrationimages.geotrans.Warperfor production rectification — precompute the mapping once, apply per frame for maximum throughput
Deployment
Always use
persistent+isemptyguard in codegen entry points — load model once, infer many timescoder.loadDeepLearningNetworkfor DL models — notcoder.load(which is for structs/shape models)coder.Constantfor MAT file path — codegen requires compile-time constant pathsPass detector objects directly to
exportONNXNetwork— never extract.Networkor.Backbonefirst. The object-level export includes pre/post-processing logicONNX for NPUs/AI accelerators; GPU Coder + TensorRT for NVIDIA — don't use ONNX for Jetson/Orin
Pipeline Construction
Machine vision inspections compose tools in sequence:
Acquire — Get the image (Image Acquisition Toolbox)
Fixture — Locate a stable reference feature (
matchshape)Reposition — Transform measurement positions to detected pose
Inspect — Apply measurement or classification at repositioned locations
Decide — Compare to tolerances → pass/fail
Communicate — Send results to PLC/SCADA (Industrial Communication Toolbox)
Common Hybrid Patterns
| Pattern | Rule-Based Part | AI Part |
|---|---|---|
| Fixture + classify | matchshape locates part, crops ROI | Anomaly detector on cropped region |
| Fixture + detect | matchshape locates part | YOLOX finds defects relative to fixture |
| Pose normalize + anomaly | matchshape + imwarp to canonical pose | Anomaly detector on normalized image |
| Segment + measure | Thresholding / morphology | regionprops on segmented blobs |
Primary Decision: Rule-Based vs. AI-Based
| Choose Rule-Based When | Choose AI-Based When |
|---|---|
| Defects have predictable, enumerable geometry | Defect appearance varies unpredictably |
| Lighting and positioning are tightly controlled | Background or part appearance varies |
| Need dimensional measurements (mm, degrees) | Need classification without precise measurement |
| Few or no labeled examples available | Have labeled training data (or can generate synthetic) |
| Require explainable, auditable decisions | Accuracy matters more than explainability |
Key Functions
| Function | Purpose | Toolbox | Available From |
|---|---|---|---|
shapemodel | Build edge-geometry model from template | Visual Inspection Toolbox | R2026b |
matchshape | Find model instances in search image | Visual Inspection Toolbox | R2026b |
caliper | Measure edge distances along a profile | Visual Inspection Toolbox | R2026b |
fitangle | Measure angle between edges | Visual Inspection Toolbox | R2026b |
fitcircle | Measure circle center and radius | Visual Inspection Toolbox | R2026b |
studentTeacherAnomalyDetector | One-class anomaly detection (>100 good images) | Visual Inspection Toolbox | R2026b |
patchCoreAnomalyDetector | One-class anomaly detection (few-shot, <100 images) | Visual Inspection Toolbox | R2026b |
fastFlowAnomalyDetector | Normalizing-flow anomaly detection | Visual Inspection Toolbox | R2026b |
fcddAnomalyDetector | Semi-supervised anomaly detection | Visual Inspection Toolbox | R2026b |
yoloxObjectDetector | Object/defect detection with bounding boxes | Visual Inspection Toolbox | R2026b |
counTRObjectCounter | Counting with intra-class variation (few-shot) | Visual Inspection Toolbox | R2026b |
objectInsertionDatastore | Synthetic labeled training data (copy-paste) | Visual Inspection Toolbox | R2026b |
regionprops | Blob area, perimeter, shape features | Image Processing Toolbox | R2006a |
imageToWorldPlane | Calibrated world-unit measurement | Computer Vision Toolbox | R2022b |
Decision Trees
"I need to detect defects"
| Situation | Approach |
|---|---|
| Defect appearance unpredictable; good-part images only | Anomaly detection |
| Classify defect types with bounding boxes; have labeled data | YOLOX object detection |
| Defects are geometric deviations from known shape | Shape matching + gauging |
| Dimensional out-of-tolerance (too wide, too narrow) | Caliper / fitcircle / fitangle |
"I need to measure parts"
| Situation | Approach |
|---|---|
| Widths, gaps, edge-to-edge distances | caliper |
| Angles between edges | fitangle |
| Hole diameters, arc radii | fitcircle |
| Area, perimeter, shape of segmented blobs | regionprops |
| Need measurements in mm (physical units) | Camera calibration + rectification |
| Part position varies image-to-image | Vision fixturing with matchshape |
"I need to count objects"
| Situation | Approach |
|---|---|
| Identical rigid parts, controlled background | shapemodel / matchshape |
| Intra-class variation, few labeled examples | CounTR (few-shot counting) |
| Multiple classes, complex scenes, have labels | YOLOX detection → count |
"I need to locate parts"
| Situation | Approach |
|---|---|
| Rigid part, known edge geometry | shapemodel / matchshape |
| Variable appearance, multiple classes | YOLOX detection |
"I don't have enough training data"
| Situation | Approach |
|---|---|
| Have segmented defect examples + clean images | Copy-paste synthetic data |
| Good-part images only (no defect labels) | Anomaly detection (one-class) |
| No data at all, defects are geometric | Rule-based (no training needed) |
"I need to deploy"
| Target | Path |
|---|---|
| Standalone app, full MATLAB features | MATLAB Compiler |
| Monitoring dashboard or UI app | MATLAB Compiler |
| Embedded CPU (x86, ARM) | MATLAB Coder |
| NVIDIA Jetson/Orin or dGPU | GPU Coder + TensorRT |
| NPU or AI accelerator | ONNX export |
| Smart camera with vendor SDK | ONNX export |
| Beckhoff industrial PLC | MATLAB Coder → TwinCAT |
Patterns
Each reference file contains executable code patterns, API calling conventions, and worked examples for its topic. Load the relevant reference before writing code.
Conventions
Always: use machine vision terminology (rule-based, tool chaining, fixturing)
Always: recommend the specific VIT function, not generic IPT building blocks
Always: consider hybrid pipelines (rule-based fixturing + AI classification)
Always: ensure anomaly detector receives images in consistent pose
Always: use
persistent+isemptyfor model loading in codegen entry pointsAlways: pass detector objects directly to
exportONNXNetwork(never extract.Network)Never: recommend AI when the problem is purely dimensional measurement
Never: recommend rule-based when defect appearance is highly variable
Never: use
coder.loadfor deep learning models (usecoder.loadDeepLearningNetwork)Never: use ONNX export for NVIDIA targets (use GPU Coder + TensorRT)
Prefer: anomaly detection when only good-part images are available
Prefer: YOLOX when labeled defect examples with bounding boxes exist
Prefer:
shapemodel/matchshapeover YOLOX for locating rigid partsPrefer:
images.geotrans.Warperfor production rectification throughputPrefer: MATLAB Compiler for dashboards and UI-based monitoring apps
References
| Load when... | Reference |
|---|---|
| Training or using anomaly detectors | references/detect-anomaly.md |
| Locating parts by shape, vision fixturing | references/match-shape.md |
| Training or using YOLOX object detectors | references/detect-objects.md |
| Counting objects (shape matching, CounTR, YOLOX) | references/count-objects.md |
| Measuring with caliper, fitcircle, fitangle | references/measure-gauging.md |
| Blob analysis, regionprops, calibrated measurement | references/blob-analysis.md |
| Deploying models (Compiler, Coder, TensorRT, ONNX) | references/deploy-inspection.md |
| Generating synthetic training data | references/synthetic-data.md |
Copyright 2026 The MathWorks, Inc.
Files
- ATTRIBUTION.mdAdded by AutoGineer1.1 KiB
- LICENSELicence file added by AutoGineer1.4 KiB
- SKILL.md12.3 KiB
- manifest.yaml629 B
- references/blob-analysis.md7.0 KiB
- references/count-objects.md6.4 KiB
- references/deploy-inspection.md10.1 KiB
- references/detect-anomaly.md10.0 KiB
- references/detect-objects.md11.4 KiB
- references/match-shape.md7.1 KiB
- references/measure-gauging.md11.1 KiB
- references/synthetic-data.md11.7 KiB
references/measure-gauging.md
Vision Gauging and Metrology
Measure part dimensions in images and check them against tolerances — a non-contact replacement for calipers, micrometers, and coordinate measuring machines.
Concepts
Gauging — Measuring dimensions of a part (lengths, diameters, angles, gap widths, hole positions) and checking whether they fall within specified tolerances. The output is a numerical value plus a pass/fail decision.
Fixturing (vision fixturing / software fixturing) — Locating the part in the image using pattern matching or edge-finding on a reference feature, then transforming the coordinate system so measurement tools are positioned relative to where the part actually is. This lets parts arrive with variation in position and rotation without needing precision mechanical fixtures.
Metrology — The science of measurement. Vision metrology requires careful calibration (pixels → real-world units), controlled lighting, and often telecentric lenses for high-precision cases.
When to Use
Measuring part dimensions: widths, diameters, angles, gap sizes
Tolerance checking: pass/fail against dimensional specifications
Vision fixturing: locating parts that arrive in varying positions/orientations
Calibrated measurement in physical units (mm, µm)
Replacing contact gauges with non-contact vision measurement
Automated inspection where parts move on a conveyor
When NOT to Use
Counting objects — see
references/count-objects.mdDefect detection (anomaly or bounding box) — use anomaly/detection skills
Template matching without measurement — see
references/match-shape.md
Measurement Tools
| Tool | Programmatic | Interactive | Measures |
|---|---|---|---|
| Caliper | caliper | uicaliper | Edge distances along a profile line |
| Angle | fitangle | uifitangle | Angle between two edges |
| Circle | fitcircle | uifitcircle | Center, radius, area, circumference |
| T-Square | — | uitsquare | Perpendicular distance from point to edge |
All tools accept a Transformation parameter to report measurements in world
units when spatial referencing is available.
When Is Camera Calibration Necessary?
Not all gauging applications require full camera calibration. The choice depends on the precision required and the amount of distortion in the imaging setup:
| Situation | Approach |
|---|---|
| Low-distortion lens, near-top-down view, moderate tolerance | Simple scale factor: measure a known object in pixels, compute mm/pixel |
| Tighter tolerances, noticeable lens distortion, or perspective | Full camera calibration (intrinsics + extrinsics) → imageToWorldPlane |
Simple scale factor — Machine vision cameras often have low-distortion lenses
and are mounted nearly perpendicular to the imaging plane. In these cases, a
single scale factor (derived from a known reference dimension divided by its
pixel count) passed as an imref2d to the Transformation parameter is often
sufficient.
Full calibration — As required precision tightens and/or lens distortion or
projective distortion becomes significant, you need calibrated intrinsics and
extrinsics. imageToWorldPlane corrects both lens distortion and perspective
in a single step, producing a rectified image where each pixel subtends a known
world distance.
Overall Workflow
Calibrate — simple scale factor or full camera calibration
Rectify (if calibrated) —
imageToWorldPlaneor precomputedimageToWorldPlaneMappingFixture — locate part with
shapemodel/matchshapeto get poseReposition — transform measurement positions to detected part pose
Gauge —
caliper/fitangle/fitcirclewithTransformationDecide — compare measurements against tolerances (pass/fail)
Steps 1–2 are needed only when measuring in physical units. Steps 3–4 are needed only when part position varies between images.
Patterns
Caliper: Edge-Pair Distance (Gauging a Width)
linePosition = [100 200; 300 200];
data = caliper(img, linePosition, MeasurementMode="edge-pair");
width = data.IntraEdgeDistance;Output fields:
Distance— distance from start to each detected edgeIntraEdgeDistance— width of each edge pair (start to end)InterEdgeDistance— gap between consecutive edge pairs
Caliper: Single-Edge Mode
data = caliper(img, linePosition, MeasurementMode="single-edge", ...
EdgeTransition="rising");
edgePositions = data.Distance;Caliper Parameters
| Parameter | Default | Purpose |
|---|---|---|
Width | 10 | Number of scan lines averaged for profile |
EdgeTransition | "both" | "rising", "falling", or "both" |
GradientThreshold | 0.1 | Minimum normalized gradient to count as edge |
Sigma | 1.0 | Gaussian smoothing before gradient detection |
MeasurementMode | "edge-pair" | "edge-pair" or "single-edge" |
Transformation | — | imref2d or tform for world-unit output |
Angle Measurement
position = [50 100; 150 150; 250 100];
data = fitangle(img, position, Snap=true);
angle = data.Theta;Position is [startPoint; vertex; endPoint]. With Snap=true, the tool snaps
to the nearest linear edges in the image.
Circle Measurement
position = [200 200 50];
data = fitcircle(img, position, Snap=true);
diameter = 2 * data.Radius;Position is [xCenter, yCenter, radius]. With Snap=true, the circle snaps
to nearby image edges via RANSAC. Use AngleRange to fit an arc when the
circle is partially occluded.
Simple Scale Factor (No Full Calibration)
When the lens has low distortion and the view is nearly top-down, derive a scale factor from a known reference dimension:
knownWidthMM = 25.0;
knownWidthPixels = 487;
mmPerPixel = knownWidthMM / knownWidthPixels;
Rout = imref2d(size(img), mmPerPixel, mmPerPixel);
data = caliper(img, linePosition, Transformation=Rout);
widthInMM = data.IntraEdgeDistance;Calibrated Measurement in World Units (Full Calibration)
When lens distortion or perspective is significant, rectify the image to a top-down world-coordinate view:
[rectified, Rout] = imageToWorldPlane(img, intrinsics, camExtrinsics);
data = caliper(rectified, linePosition, Transformation=Rout);
widthInMM = data.IntraEdgeDistance;Rout is an imref2d mapping pixels to world units (e.g., mm). All
measurement outputs are then in the calibration unit system.
Precomputing the Rectification Map (Production)
For repeated measurement on a fixed camera, compute the displacement field once and reuse it per frame:
D = imageToWorldPlaneMapping(intrinsics, camExtrinsics);
rectified = imwarp(img, D);Projecting Points Without Full Rectification
When you only need world coordinates for specific points:
worldPts = imagePointsToWorldPlane(imagePoints, intrinsics, camExtrinsics);Interactive Measurement with World Units
v = viewer2d(SpatialUnits="mm");
hIm = imageshow(rectified, Transformation=Rout, Parent=v);
hCal = uicaliper(hIm, Position=caliperPosition);Set SpatialUnits on the viewer2d so tools display the unit label.
Interactive tools inherit the transformation from imageshow.
Vision Fixturing with Shape Matching
When part position varies, locate a reference fixture (a stable visual feature independent of the dimension being measured) and reposition all measurement tools to the detected pose:
model = shapemodel(fixtureTemplate, NumPyramidLevels=3);
matches = matchshape(model, rectified, ScoreThreshold=0.7);
tform = matches.ModelOriginTransformation;
[tform.Translation(1), tform.Translation(2)] = ...
intrinsicToWorld(Rout, tform.Translation(1), tform.Translation(2));
caliperPosForMatch = transformPointsForward(tform, caliperRelativeToModel);
data = caliper(rectified, caliperPosForMatch, Transformation=Rout);The workflow:
Define measurement positions relative to the fixture's model origin (in world coords)
Detect fixture with
matchshape→ getModelOriginTransformationConvert translation from intrinsic to world coordinates via
intrinsicToWorldApply
transformPointsForwardto reposition measurement toolsGauge at the new position
Complete Gauging Function (Production Pattern)
function [measurement, passFail] = gaugePartWidth(img, D, Rout, fixtureModel, refPosition, tolerance)
rectified = imwarp(img, D);
matches = matchshape(fixtureModel, rectified, ScoreThreshold=0.7);
if isempty(matches)
measurement = NaN;
passFail = "no fixture found";
return
end
tform = matches.ModelOriginTransformation;
[tform.Translation(1), tform.Translation(2)] = ...
intrinsicToWorld(Rout, tform.Translation(1), tform.Translation(2));
caliperPos = transformPointsForward(tform, refPosition);
data = caliper(rectified, caliperPos, Transformation=Rout);
measurement = data.IntraEdgeDistance;
passFail = abs(measurement - tolerance(1)) <= tolerance(2);
endDecision Framework
| Situation | Approach |
|---|---|
| Fixed part position, pixel measurements sufficient | caliper/fitangle/fitcircle directly |
| Need physical units (mm) | Calibrate + imageToWorldPlane + Transformation=Rout |
| Part position varies image-to-image | Vision fixturing: matchshape → reposition tools |
| Production (many images, fixed camera) | Precompute imageToWorldPlaneMapping, reuse per frame |
| Only need world coords for specific points | imagePointsToWorldPlane (no full rectification) |
Conventions
Always: pass
Transformation=Routwhen measurements must be in world unitsAlways: set
viewer2d(SpatialUnits="mm")for interactive tools to display unit labelsAlways: precompute
imageToWorldPlaneMappingfor repeated measurement on fixed camerasAlways: convert
ModelOriginTransformation.TranslationviaintrinsicToWorldbefore repositioningNever: manually build projective transforms for rectification — use
imageToWorldPlanePrefer:
fitangle/fitcirclewithSnap=trueover manual edge detection + geometryPrefer:
caliperover custom gradient-based edge finding for distance measurement
Common Mistakes
| Mistake | Why It's Wrong | Correct Approach |
|---|---|---|
| Measuring in pixels and scaling manually | Ignores lens distortion, perspective | imageToWorldPlane + Transformation=Rout |
Recomputing imageToWorldPlane per frame | Slow — recomputes displacement field | imageToWorldPlaneMapping once, imwarp per frame |
Missing SpatialUnits on viewer | Interactive tools show no unit label | viewer2d(SpatialUnits="mm") |
Repositioning without intrinsicToWorld | Translation in ModelOriginTransformation is in intrinsic coords | Convert before transformPointsForward |
| Building custom projective rectification | Error-prone, misses lens distortion correction | imageToWorldPlane handles both |
| Choosing a fixture feature that varies with the measured dimension | Fixture pose correlates with measurement error | Choose fixture independent of what you're measuring |
Copyright 2026 The MathWorks, Inc.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- MathWorks
- Publisher
- MathWorks (Official)
- Source
- matlab/matlab-agentic-toolkit · skills-catalog/image-processing-and-computer-vision/matlab-use-visual-inspection · commit 2a7f215
- Licence
- BSD 2-Clause License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE.md)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by MathWorks or MathWorks.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download matlab-use-visual-inspection.zip