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/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.md

  • Defect detection (anomaly or bounding box) — use anomaly/detection skills

  • Template matching without measurement — see references/match-shape.md

Measurement Tools

ToolProgrammaticInteractiveMeasures
CalipercaliperuicaliperEdge distances along a profile line
AnglefitangleuifitangleAngle between two edges
CirclefitcircleuifitcircleCenter, radius, area, circumference
T-Square—uitsquarePerpendicular 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:

SituationApproach
Low-distortion lens, near-top-down view, moderate toleranceSimple scale factor: measure a known object in pixels, compute mm/pixel
Tighter tolerances, noticeable lens distortion, or perspectiveFull 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

  1. Calibrate — simple scale factor or full camera calibration

  2. Rectify (if calibrated) — imageToWorldPlane or precomputed imageToWorldPlaneMapping

  3. Fixture — locate part with shapemodel/matchshape to get pose

  4. Reposition — transform measurement positions to detected part pose

  5. Gauge — caliper/fitangle/fitcircle with Transformation

  6. Decide — 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 edge

  • IntraEdgeDistance — 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
ParameterDefaultPurpose
Width10Number of scan lines averaged for profile
EdgeTransition"both""rising", "falling", or "both"
GradientThreshold0.1Minimum normalized gradient to count as edge
Sigma1.0Gaussian 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:

  1. Define measurement positions relative to the fixture's model origin (in world coords)

  2. Detect fixture with matchshape → get ModelOriginTransformation

  3. Convert translation from intrinsic to world coordinates via intrinsicToWorld

  4. Apply transformPointsForward to reposition measurement tools

  5. Gauge 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);
end

Decision Framework

SituationApproach
Fixed part position, pixel measurements sufficientcaliper/fitangle/fitcircle directly
Need physical units (mm)Calibrate + imageToWorldPlane + Transformation=Rout
Part position varies image-to-imageVision fixturing: matchshape → reposition tools
Production (many images, fixed camera)Precompute imageToWorldPlaneMapping, reuse per frame
Only need world coords for specific pointsimagePointsToWorldPlane (no full rectification)

Conventions

  • Always: pass Transformation=Rout when measurements must be in world units

  • Always: set viewer2d(SpatialUnits="mm") for interactive tools to display unit labels

  • Always: precompute imageToWorldPlaneMapping for repeated measurement on fixed cameras

  • Always: convert ModelOriginTransformation.Translation via intrinsicToWorld before repositioning

  • Never: manually build projective transforms for rectification — use imageToWorldPlane

  • Prefer: fitangle/fitcircle with Snap=true over manual edge detection + geometry

  • Prefer: caliper over custom gradient-based edge finding for distance measurement

Common Mistakes

MistakeWhy It's WrongCorrect Approach
Measuring in pixels and scaling manuallyIgnores lens distortion, perspectiveimageToWorldPlane + Transformation=Rout
Recomputing imageToWorldPlane per frameSlow — recomputes displacement fieldimageToWorldPlaneMapping once, imwarp per frame
Missing SpatialUnits on viewerInteractive tools show no unit labelviewer2d(SpatialUnits="mm")
Repositioning without intrinsicToWorldTranslation in ModelOriginTransformation is in intrinsic coordsConvert before transformPointsForward
Building custom projective rectificationError-prone, misses lens distortion correctionimageToWorldPlane handles both
Choosing a fixture feature that varies with the measured dimensionFixture pose correlates with measurement errorChoose 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.

Download ZIP

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