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/deploy-inspection.md
Deploying Visual Inspection Models
Take trained anomaly detectors, YOLOX object detectors, and shape models from the MATLAB desktop to production: standalone executables, embedded C/C++, GPU-accelerated inference, or interoperable ONNX for specialized hardware.
When to Use
Packaging inspection algorithms as standalone applications
Generating C/C++ code for embedded or edge deployment
Targeting NVIDIA GPUs with TensorRT optimization
Exporting models to ONNX for NPUs, AI accelerators, or smart camera SDKs
Deploying to Beckhoff industrial PCs/PLCs via TwinCAT
Deploying monitoring dashboards built with MATLAB UI tools
Running inference in production loops without a MATLAB license
When NOT to Use
Still training or tuning the model — finish training first
Need to choose a detection/anomaly approach — see
references/detect-objects.mdorreferences/detect-anomaly.mdInteractive visualization or labeling — keep in MATLAB desktop
Deployment Targets
| Target | Toolchain | Best For |
|---|---|---|
| Standalone app / shared library / dashboard | MATLAB Compiler | Easiest path; full MATLAB runtime bundled |
| C/C++ on CPU (x86, ARM) | MATLAB Coder | Embedded/edge, x86 or ARM smart cameras |
| NVIDIA GPU (Jetson, Orin, dGPU) | GPU Coder + TensorRT | Maximum throughput, Jetson/Orin smart cameras |
| NPUs, AI accelerators, smart camera SDKs | ONNX export | Hardware with ONNX runtime or vendor SDK |
| Beckhoff industrial PCs/PLCs | MATLAB Coder + TwinCAT | PLC-integrated inspection on Beckhoff hardware |
Choosing a Deployment Path
| Question | Recommendation |
|---|---|
| Need simplest deployment, runtime size not critical? | MATLAB Compiler |
| Deploying a monitoring dashboard or UI app? | MATLAB Compiler — preferred for UI deployment |
| Targeting NVIDIA Jetson/Orin or dGPU? | GPU Coder + TensorRT |
| Targeting x86 or ARM smart camera (Open standard)? | MATLAB Coder |
| Targeting NPU or AI accelerator hardware? | ONNX export |
| Smart camera with vendor SDK (non-NVIDIA)? | ONNX — often easiest integration path |
| Need pre/post-processing bundled as one executable? | Codegen (MATLAB Coder or GPU Coder) |
| Deploying to Beckhoff TwinCAT environment? | MATLAB Coder → TwinCAT integration |
Patterns
MATLAB Compiler: Standalone Application
Package the inspection pipeline as a standalone executable that includes the MATLAB Runtime. No code generation step; full MATLAB language support.
function results = inspectParts(imageFolder, modelPath)
detector = load(modelPath).detector;
imds = imageDatastore(imageFolder);
results = table(Size=[0 3], ...
VariableTypes=["string", "logical", "double"], ...
VariableNames=["File", "Pass", "Score"]);
while hasdata(imds)
[img, info] = read(imds);
[tf, score] = classify(detector, img);
results = [results; {info.Filename, ~tf, score}];
end
endCompile with:
mcc -m inspectParts.m -a modelFile.matMATLAB Compiler: Monitoring Dashboards
MATLAB Compiler is the preferred way to deploy dashboards for monitoring
deployed visual inspection systems. Apps built with MATLAB UI tools (App
Designer, uifigure) deploy directly via Compiler with full graphics support:
mcc -m inspectionDashboard.m -a modelFile.mat -a uiAssets/This preserves all UI functionality — live image display, charts, status indicators — without requiring MATLAB licenses on the monitoring workstation.
For maximum rectification throughput in Compiler-deployed apps, use
images.geotrans.Warper (see references/blob-analysis.md for the pattern).
Code Generation Entry Point: Anomaly Detector
function [tf, score, map] = anomalyInference(I, matFilePath) %#codegen
persistent detector
if isempty(detector)
detector = coder.loadDeepLearningNetwork(matFilePath);
end
[tf, score, map] = classify(detector, I);
endGenerate code:
cfg = coder.config("mex");
cfg.TargetLang = "C++";
cfg.DeepLearningConfig = coder.DeepLearningConfig(TargetLibrary="mkldnn");
inputArgs = {ones(256, 256, 3, "uint8"), coder.Constant("model.mat")};
codegen -config cfg anomalyInference -args inputArgsCode Generation Entry Point: YOLOX Detector
function [bboxes, scores, labels] = yoloxInference(I, matFilePath) %#codegen
persistent detector
if isempty(detector)
detector = coder.loadDeepLearningNetwork(matFilePath);
end
[bboxes, scores, labels] = detect(detector, I, Threshold=0.5);
endGPU Coder + TensorRT (NVIDIA GPU)
For maximum throughput on NVIDIA hardware (desktop GPUs, Jetson, Orin):
cfg = coder.gpuConfig("mex");
cfg.TargetLang = "C++";
cfg.DeepLearningConfig = coder.DeepLearningConfig(TargetLibrary="tensorrt");
inputArgs = {ones(256, 256, 3, "uint8"), coder.Constant("model.mat")};
codegen -config cfg anomalyInference -args inputArgsTensorRT performs layer fusion and FP16/INT8 optimization automatically.
ONNX Export
Export models to ONNX for deployment on NPUs, AI accelerators, or smart camera SDKs where ONNX runtime is available:
detector = load("trainedDetector.mat").detector;
exportONNXNetwork(detector, "detector.onnx");Visual Inspection Toolbox detector objects (e.g. studentTeacherAnomalyDetector,
yoloxObjectDetector) have their own exportONNXNetwork overload. This is
always preferable to extracting any underlying dlnetwork (via .Network,
.Backbone, or dlnetwork(detector)) because the object-level export includes
preprocessing and post-processing logic and provides export options not present
in the generic dlnetwork method.
ONNX is the preferred path when targeting specialized AI-accelerator hardware (NPUs, VPUs) or when integrating with smart camera vendor SDKs that provide ONNX runtime support. The trade-off is that pre/post-processing must be implemented separately in the target environment's native language.
Beckhoff TwinCAT Deployment
For industrial PCs and PLCs running Beckhoff TwinCAT, use MATLAB Coder to generate C/C++ code, then integrate via the TwinCAT Machine Learning Server (TE1401). The generated code runs as a TwinCAT module with deterministic real-time execution.
cfg = coder.config("lib");
cfg.TargetLang = "C++";
cfg.DeepLearningConfig = coder.DeepLearningConfig(TargetLibrary="mkldnn");
inputArgs = {ones(256, 256, 3, "uint8"), coder.Constant("model.mat")};
codegen -config cfg anomalyInference -args inputArgsShape Model Deployment (Non-DL)
Shape models used for fixturing or counting do not require deep learning code generation. They are lightweight and deploy directly via MATLAB Compiler or standard code generation:
function [locations, scores] = matchInFrame(I, matFilePath) %#codegen
persistent model
if isempty(model)
modelData = coder.load(matFilePath);
model = modelData.model;
end
matches = matchshape(model, I, ScoreThreshold=0.7);
locations = matches.Location;
scores = matches.Score;
endEntry-Point Conventions for Code Generation
| Convention | Reason |
|---|---|
persistent variable for model | Load once, infer many times |
coder.loadDeepLearningNetwork(path) | Loads DL networks for codegen |
coder.Constant(path) for MAT file | Path is compile-time constant |
coder.load(path) for non-DL data | Loads structs/shape models for codegen |
%#codegen pragma | Enables code generation checks |
Fixed input size in -args | Codegen requires known dimensions |
Decision Framework
| Scenario | Path |
|---|---|
| Prototype deployment, keep full MATLAB features | MATLAB Compiler |
| Monitoring dashboard or UI app | MATLAB Compiler |
| Embedded CPU target, no GPU | MATLAB Coder (mkl-dnn) |
| NVIDIA Jetson/Orin smart camera | GPU Coder + TensorRT |
| x86 or ARM smart camera (open standard) | MATLAB Coder |
| NPU or dedicated AI accelerator | ONNX export |
| Smart camera with vendor SDK | ONNX — often easiest integration |
| Beckhoff industrial PLC | MATLAB Coder → TwinCAT (TE1401) |
| Need bundled pre/post-processing in one binary | Codegen (MATLAB Coder or GPU Coder) |
| Model only, separate pre/post-processing OK | ONNX export |
| Shape model (non-DL, fixturing/counting) | coder.load + standard codegen |
Common Mistakes
| Mistake | Why It's Wrong | Correct Approach |
|---|---|---|
Not using persistent in entry point | Reloads model every frame | persistent + isempty guard |
| Passing MAT path as runtime variable | Codegen needs compile-time path | coder.Constant("path.mat") |
Using coder.load for DL networks | Wrong loader for deep learning | coder.loadDeepLearningNetwork |
| Exporting to ONNX when pre/post-processing must be bundled | ONNX only exports the network | Use codegen to bundle full pipeline |
| Using ONNX for NVIDIA Jetson/Orin | Misses TensorRT optimization | GPU Coder + TensorRT for NVIDIA hardware |
Extracting .Network or .Backbone before ONNX export | Loses detector-specific pre/post-processing layers | Pass the detector object directly: exportONNXNetwork(detector, ...) |
| Recomputing rectification per frame in production | Slow | Precompute imageToWorldPlaneMapping, reuse |
| Using codegen for UI/dashboard deployment | Codegen doesn't support UI | MATLAB Compiler for apps with UI |
Conventions
Always: use
persistent+isemptyfor model loading in codegen entry pointsAlways: use
coder.loadDeepLearningNetworkfor deep learning modelsAlways: use
coder.Constantfor the MAT file path argumentAlways: specify fixed input dimensions in codegen
-argsNever: mix
coder.load(structs) withcoder.loadDeepLearningNetwork(DL)Never: extract
.Networkor.Backbonebefore callingexportONNXNetwork— pass the detector object directlyPrefer: MATLAB Compiler for dashboards and UI-based monitoring apps
Prefer: GPU Coder + TensorRT for NVIDIA targets (Jetson, Orin, dGPU)
Prefer: MATLAB Coder for x86/ARM smart cameras and Beckhoff TwinCAT
Prefer: ONNX when targeting NPUs, AI accelerators, or vendor camera SDKs
Prefer: codegen when pre/post-processing must be bundled as one executable
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