Generated banner for Matlab Use Visual Inspection
Generated logo for Matlab Use Visual Inspection

Matlab Use Visual Inspection

MathWorksOfficialCreated by MathWorks

  • Skill
  • Tool integration
  • Software development
  • BSD-2-Clause
  • No issues found

From the author

Build machine vision inspection systems with MATLAB Visual Inspection Toolbox. Covers the full arc from problem selection through deployment: anomaly detection (Student-Teacher, PatchCore, FastFlow, FCDD), object detection (YOLOX), counting (CounTR, shape matching), gauging and measurement (caliper, fitcircle, fitangle), blob analysis (regionprops, calibrated measurement), shape matching for fixturing and localization, synthetic data generation for training augmentation, and deployment to standalone apps, embedded C/C++, NVIDIA GPUs (TensorRT), NPUs (ONNX), and Beckhoff PLCs. Routes to rule-based tools when problems are geometric and deterministic, AI-based tools when defect appearance varies, and hybrid pipelines combining both.
— the description by MathWorks

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

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/matlab/matlab-use-visual-inspection/download
  2. Unzip 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 matchshape to 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 + imwarp to canonical orientation before training and inference

  • Choose detector by data availability — >100 good images: studentTeacherAnomalyDetector; <100 images: patchCoreAnomalyDetector; have anomaly labels: fcddAnomalyDetector

  • Use classify for inference — returns [tf, score, map] for anomaly map visualization

Object Detection (YOLOX)
  • Use AutoResize=false for full-resolution inference — prevents downscaling that loses small defects. Pair with tiled training when objects are small relative to image

  • Synthetic data benefits YOLOX most — copy-paste augmentation via objectInsertionDatastore is proven for detection tasks

Measurement
  • Vision fixturing pattern — matchshape locates part → transform measurement positions to detected pose → measure at repositioned locations

  • Calibrated measurements require imageToWorldPlane — converts pixel measurements to physical units using camera calibration

  • images.geotrans.Warper for production rectification — precompute the mapping once, apply per frame for maximum throughput

Deployment
  • Always use persistent + isempty guard in codegen entry points — load model once, infer many times

  • coder.loadDeepLearningNetwork for DL models — not coder.load (which is for structs/shape models)

  • coder.Constant for MAT file path — codegen requires compile-time constant paths

  • Pass detector objects directly to exportONNXNetwork — never extract .Network or .Backbone first. The object-level export includes pre/post-processing logic

  • ONNX 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:

  1. Acquire — Get the image (Image Acquisition Toolbox)

  2. Fixture — Locate a stable reference feature (matchshape)

  3. Reposition — Transform measurement positions to detected pose

  4. Inspect — Apply measurement or classification at repositioned locations

  5. Decide — Compare to tolerances → pass/fail

  6. Communicate — Send results to PLC/SCADA (Industrial Communication Toolbox)

Common Hybrid Patterns
PatternRule-Based PartAI Part
Fixture + classifymatchshape locates part, crops ROIAnomaly detector on cropped region
Fixture + detectmatchshape locates partYOLOX finds defects relative to fixture
Pose normalize + anomalymatchshape + imwarp to canonical poseAnomaly detector on normalized image
Segment + measureThresholding / morphologyregionprops on segmented blobs

Primary Decision: Rule-Based vs. AI-Based

Choose Rule-Based WhenChoose AI-Based When
Defects have predictable, enumerable geometryDefect appearance varies unpredictably
Lighting and positioning are tightly controlledBackground or part appearance varies
Need dimensional measurements (mm, degrees)Need classification without precise measurement
Few or no labeled examples availableHave labeled training data (or can generate synthetic)
Require explainable, auditable decisionsAccuracy matters more than explainability

Key Functions

FunctionPurposeToolboxAvailable From
shapemodelBuild edge-geometry model from templateVisual Inspection ToolboxR2026b
matchshapeFind model instances in search imageVisual Inspection ToolboxR2026b
caliperMeasure edge distances along a profileVisual Inspection ToolboxR2026b
fitangleMeasure angle between edgesVisual Inspection ToolboxR2026b
fitcircleMeasure circle center and radiusVisual Inspection ToolboxR2026b
studentTeacherAnomalyDetectorOne-class anomaly detection (>100 good images)Visual Inspection ToolboxR2026b
patchCoreAnomalyDetectorOne-class anomaly detection (few-shot, <100 images)Visual Inspection ToolboxR2026b
fastFlowAnomalyDetectorNormalizing-flow anomaly detectionVisual Inspection ToolboxR2026b
fcddAnomalyDetectorSemi-supervised anomaly detectionVisual Inspection ToolboxR2026b
yoloxObjectDetectorObject/defect detection with bounding boxesVisual Inspection ToolboxR2026b
counTRObjectCounterCounting with intra-class variation (few-shot)Visual Inspection ToolboxR2026b
objectInsertionDatastoreSynthetic labeled training data (copy-paste)Visual Inspection ToolboxR2026b
regionpropsBlob area, perimeter, shape featuresImage Processing ToolboxR2006a
imageToWorldPlaneCalibrated world-unit measurementComputer Vision ToolboxR2022b

Decision Trees

"I need to detect defects"
SituationApproach
Defect appearance unpredictable; good-part images onlyAnomaly detection
Classify defect types with bounding boxes; have labeled dataYOLOX object detection
Defects are geometric deviations from known shapeShape matching + gauging
Dimensional out-of-tolerance (too wide, too narrow)Caliper / fitcircle / fitangle
"I need to measure parts"
SituationApproach
Widths, gaps, edge-to-edge distancescaliper
Angles between edgesfitangle
Hole diameters, arc radiifitcircle
Area, perimeter, shape of segmented blobsregionprops
Need measurements in mm (physical units)Camera calibration + rectification
Part position varies image-to-imageVision fixturing with matchshape
"I need to count objects"
SituationApproach
Identical rigid parts, controlled backgroundshapemodel / matchshape
Intra-class variation, few labeled examplesCounTR (few-shot counting)
Multiple classes, complex scenes, have labelsYOLOX detection → count
"I need to locate parts"
SituationApproach
Rigid part, known edge geometryshapemodel / matchshape
Variable appearance, multiple classesYOLOX detection
"I don't have enough training data"
SituationApproach
Have segmented defect examples + clean imagesCopy-paste synthetic data
Good-part images only (no defect labels)Anomaly detection (one-class)
No data at all, defects are geometricRule-based (no training needed)
"I need to deploy"
TargetPath
Standalone app, full MATLAB featuresMATLAB Compiler
Monitoring dashboard or UI appMATLAB Compiler
Embedded CPU (x86, ARM)MATLAB Coder
NVIDIA Jetson/Orin or dGPUGPU Coder + TensorRT
NPU or AI acceleratorONNX export
Smart camera with vendor SDKONNX export
Beckhoff industrial PLCMATLAB 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 + isempty for model loading in codegen entry points

  • Always: 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.load for deep learning models (use coder.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/matchshape over YOLOX for locating rigid parts

  • Prefer: images.geotrans.Warper for production rectification throughput

  • Prefer: MATLAB Compiler for dashboards and UI-based monitoring apps

References
Load when...Reference
Training or using anomaly detectorsreferences/detect-anomaly.md
Locating parts by shape, vision fixturingreferences/match-shape.md
Training or using YOLOX object detectorsreferences/detect-objects.md
Counting objects (shape matching, CounTR, YOLOX)references/count-objects.md
Measuring with caliper, fitcircle, fitanglereferences/measure-gauging.md
Blob analysis, regionprops, calibrated measurementreferences/blob-analysis.md
Deploying models (Compiler, Coder, TensorRT, ONNX)references/deploy-inspection.md
Generating synthetic training datareferences/synthetic-data.md

Copyright 2026 The MathWorks, Inc.


Files

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.md or references/detect-anomaly.md

  • Interactive visualization or labeling — keep in MATLAB desktop

Deployment Targets

TargetToolchainBest For
Standalone app / shared library / dashboardMATLAB CompilerEasiest path; full MATLAB runtime bundled
C/C++ on CPU (x86, ARM)MATLAB CoderEmbedded/edge, x86 or ARM smart cameras
NVIDIA GPU (Jetson, Orin, dGPU)GPU Coder + TensorRTMaximum throughput, Jetson/Orin smart cameras
NPUs, AI accelerators, smart camera SDKsONNX exportHardware with ONNX runtime or vendor SDK
Beckhoff industrial PCs/PLCsMATLAB Coder + TwinCATPLC-integrated inspection on Beckhoff hardware

Choosing a Deployment Path

QuestionRecommendation
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
end

Compile with:

mcc -m inspectParts.m -a modelFile.mat
MATLAB 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);
end

Generate 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 inputArgs
Code 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);
end
GPU 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 inputArgs

TensorRT 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 inputArgs
Shape 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;
end

Entry-Point Conventions for Code Generation

ConventionReason
persistent variable for modelLoad once, infer many times
coder.loadDeepLearningNetwork(path)Loads DL networks for codegen
coder.Constant(path) for MAT filePath is compile-time constant
coder.load(path) for non-DL dataLoads structs/shape models for codegen
%#codegen pragmaEnables code generation checks
Fixed input size in -argsCodegen requires known dimensions

Decision Framework

ScenarioPath
Prototype deployment, keep full MATLAB featuresMATLAB Compiler
Monitoring dashboard or UI appMATLAB Compiler
Embedded CPU target, no GPUMATLAB Coder (mkl-dnn)
NVIDIA Jetson/Orin smart cameraGPU Coder + TensorRT
x86 or ARM smart camera (open standard)MATLAB Coder
NPU or dedicated AI acceleratorONNX export
Smart camera with vendor SDKONNX — often easiest integration
Beckhoff industrial PLCMATLAB Coder → TwinCAT (TE1401)
Need bundled pre/post-processing in one binaryCodegen (MATLAB Coder or GPU Coder)
Model only, separate pre/post-processing OKONNX export
Shape model (non-DL, fixturing/counting)coder.load + standard codegen

Common Mistakes

MistakeWhy It's WrongCorrect Approach
Not using persistent in entry pointReloads model every framepersistent + isempty guard
Passing MAT path as runtime variableCodegen needs compile-time pathcoder.Constant("path.mat")
Using coder.load for DL networksWrong loader for deep learningcoder.loadDeepLearningNetwork
Exporting to ONNX when pre/post-processing must be bundledONNX only exports the networkUse codegen to bundle full pipeline
Using ONNX for NVIDIA Jetson/OrinMisses TensorRT optimizationGPU Coder + TensorRT for NVIDIA hardware
Extracting .Network or .Backbone before ONNX exportLoses detector-specific pre/post-processing layersPass the detector object directly: exportONNXNetwork(detector, ...)
Recomputing rectification per frame in productionSlowPrecompute imageToWorldPlaneMapping, reuse
Using codegen for UI/dashboard deploymentCodegen doesn't support UIMATLAB Compiler for apps with UI

Conventions

  • Always: use persistent + isempty for model loading in codegen entry points

  • Always: use coder.loadDeepLearningNetwork for deep learning models

  • Always: use coder.Constant for the MAT file path argument

  • Always: specify fixed input dimensions in codegen -args

  • Never: mix coder.load (structs) with coder.loadDeepLearningNetwork (DL)

  • Never: extract .Network or .Backbone before calling exportONNXNetwork — pass the detector object directly

  • Prefer: 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.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download matlab-use-visual-inspection.zip