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://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/count-objects.md

Counting Objects in Images

Count objects using the right approach for your data and environment. Three primary methods are available, each suited to different scenarios.

When to Use

  • Counting parts on a conveyor or tray

  • Counting defects in an inspection image

  • Inventory verification (are all N parts present?)

  • Quality check (count matches expected quantity)

Decision Tree

ScenarioData AvailableRecommended Approach
Controlled environment, uniform objects, no labeled dataSingle template imageshapemodel/matchshape with high MaxMatches
Intra-class variation, few examples (1–3 boxes), no full annotationA few exemplar bounding boxescounTRObjectCounter (low-shot counting)
Complex scenes, labeled bounding box dataFull annotation setyoloxObjectDetector → count detections
How to Choose
  1. Are objects uniform in shape? (same part, same orientation range)

    • Yes → shape matching. Count = number of matches. No training needed.

  2. Do objects vary in appearance? (different sizes, orientations, partial views)

    • Yes, but you only have a few examples → CounTR (1–3 exemplar boxes)

    • Yes, and you have full bounding box annotations → YOLOX detection

Blob analysis (bwconncomp + regionprops) is also a standard approach but requires careful parameter tuning to generalize well — particularly for touching or overlapping objects. The approaches above are typically more robust for industrial counting tasks.

Approach 1: Shape Matching (Template-Based)

Best when objects are geometrically uniform and appear against a relatively clean background. Requires zero training — just one template.

model = shapemodel(template, RotationRange=[-30 30]);
results = matchshape(model, searchImage, MaxMatches=Inf, ScoreThreshold=0.7);
count = numel(results);
fprintf("Found %d objects\n", count)

Set MaxMatches at least as high as the maximum expected count in the scene. Use Inf when the count is unknown; use a known upper bound (e.g., 50) when you want to limit computation for speed.

See references/match-shape.md for full guidance on parameter tuning, synthetic templates, and multi-class counting.

Strengths: No training, fast, deterministic, works with a single template. Limitations: Struggles with high intra-class variation, heavy occlusion, or cluttered backgrounds where edges overlap.

Approach 2: CounTR (Low-Shot Counting)

Best when objects vary in appearance and you have only 1–3 exemplar bounding boxes. CounTR is a transformer-based density estimation model — it predicts a density map whose integral equals the count.

Construction from Exemplar Boxes

Provide an image and bounding boxes around a few representative objects:

exemplarImg = imread("scene.png");
exemplarBoxes = [120 80 45 45; 300 210 50 48; 55 310 42 44];
counter = counTRObjectCounter(exemplarImg, exemplarBoxes);
Construction from Patches

Alternatively, provide pre-cropped patches directly:

patches = {patch1; patch2; patch3};
counter = counTRObjectCounter(patches);

Patches are internally resized to 64×64×3.

Counting Objects
count = countObjects(counter, testImage);

For a datastore of images:

counts = countObjects(counter, imds);

Returns an integer-valued count per image.

Density Map Visualization

The density map shows where the model believes objects are located:

dmap = densityMap(counter, testImage);
overlay = anomalyMapOverlay(testImage, dmap, "Blend", "equal");
imshow(overlay)
title(sprintf("Count = %d", countObjects(counter, testImage)))
Key Considerations
  • Exemplar quality matters: Choose exemplars representative of the variation in the scene (different sizes, orientations, lighting if present).

  • No localization: CounTR provides a density map but not individual bounding boxes. If you need per-object localization, use YOLOX detection instead.

  • Support package required: CounTR requires the CounTR support package for Visual Inspection Toolbox.

Approach 3: YOLOX Detection

Best for complex scenes with full bounding box annotations. Count = number of detected objects above threshold.

[bboxes, scores, labels] = detect(detector, img, Threshold=0.5);
count = size(bboxes, 1);

See references/detect-objects.md for training, threshold selection, and evaluation workflows.

Strengths: Precise localization, per-class counting, handles complex scenes. Limitations: Requires labeled training data (bounding boxes for all objects).

Evaluation

Shape Matching

Count accuracy is deterministic given parameters. Tune ScoreThreshold and verify against known counts:

results = matchshape(model, img, MaxMatches=Inf, ScoreThreshold=0.7);
countError = numel(results) - groundTruthCount;
CounTR

Evaluate counting accuracy across a test set:

counts = countObjects(counter, dsTest);
groundTruth = [10; 12; 8; 15; 11];
mae = mean(abs(counts - groundTruth));
fprintf("Mean Absolute Error: %.2f\n", mae)
YOLOX

Use evaluateObjectDetection for full AP/PR analysis. Count accuracy follows from detection accuracy at the chosen threshold.

Conventions

  • Always: start with the decision tree — don't default to generic IPT approaches

  • Always: set MaxMatches high enough to not limit the count (at least the max expected objects in the scene)

  • Never: use CounTR when you need per-object bounding boxes — it only provides density maps

  • Prefer: shape matching over CounTR when objects are geometrically uniform (simpler, no model needed)

  • Prefer: CounTR over YOLOX when you lack full bounding box annotations but have a few exemplars

Common Mistakes

MistakeWhy It's WrongCorrect Approach
Defaulting to YOLOX without labeled dataCan't train without bounding box annotationsCounTR (few exemplars) or shape matching (template)
matchshape with default MaxMatches=1Only finds one objectSet MaxMatches ≥ max expected count
Using CounTR when objects are perfectly uniformOverkill — shape matching is simpler and more preciseshapemodel/matchshape
Not choosing representative CounTR exemplarsModel won't generalize to variation in scenePick exemplars covering size/orientation range

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