Matlab Process Images
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 serves as the primary entry point for MATLAB tasks involving images, scans, frames, and 3-D volumes. It provides core conventions for image data types, coordinate systems, and display practices, while routing users to specific references for tasks such as I/O, filtering, segmentation, and measurement. It ensures consistent use of Image Processing Toolbox functions and helps users navigate common pitfalls in image analysis workflows.
What it does
- Provides standardized conventions for image data types and coordinate systems.
- Routes users to specialized references for image I/O, filtering, and transformation tasks.
- Defines best practices for displaying images using the imageshow function.
- Offers guidance on handling 3-D volumetric data and large-scale images.
- Assists with selecting appropriate functions for segmentation and object measurement.
- Provides troubleshooting patterns for common image processing errors.
When to use it
- When performing image processing tasks in MATLAB, such as filtering, enhancing, or segmenting.
- When working with image formats like TIFF, PNG, JPEG, DICOM, or NIfTI.
- When needing to understand MATLAB-specific coordinate conventions for image data.
- When determining the correct toolbox function for a specific image analysis goal.
- When troubleshooting syntax or type-related errors in image processing scripts.
Advantages
- Ensures consistent coding patterns across different image processing tasks.
- Reduces errors by providing clear guidance on coordinate and data type conventions.
- Simplifies the selection of appropriate tools for complex workflows like 3-D volume processing.
- Promotes the use of modern display functions like imageshow over legacy alternatives.
- Provides a structured approach to identifying the correct documentation for specific functions.
Usage examples
- “How do I read a DICOM file and display it in MATLAB?”
- The agent will guide you to use the medical-data-io reference for reading the file and the imageshow function for display, following the core conventions.
- “I need to count the number of objects in a binary image.”
- The agent will provide the standard analysis pipeline using bwconncomp and regionprops, ensuring the input is correctly formatted as logical.
- “How do I perform 3-D filtering on a volume?”
- The agent will direct you to the 3-D volume processing reference to select the appropriate 3-D specific function, such as imgaussfilt3.
- “Why is my regionprops measurement returning only one object?”
- The agent will explain that the input must be a logical array and provide the code to convert your numeric array to logical.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/matlab/matlab-process-images/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip matlab-process-images.zip -d .agents/skills
Documentation by MathWorks
Image Processing
Process, analyze, and transform images using MATLAB Image Processing Toolbox (IPT). This skill routes you to the correct reference for your task and provides core conventions that apply across all IPT work.
When to Use
Loaded for general-purpose IPT work: file and batch I/O, filtering, restoration, morphology, segmentation, measurement, geometric transforms, color, texture, quality metrics, deep learning on images, and image apps. Non-medical microscopy — cell and particle counting on plain IPT — is in scope.
Hand off (and co-load) instead of answering alone: see the handoff table under ## Routing.
When NOT to Use
Training a network with no image-specific preprocessing — use Deep Learning Toolbox directly
Simulink or Stateflow video blocks — use Simulink directly
C/C++ code generation, MEX, GPU acceleration and deployment — use MATLAB Coder / GPU Coder directly
Point clouds, 3-D reconstruction, and video stabilization — use Computer Vision Toolbox directly
General MATLAB questions unrelated to images
Looking at an image yourself (e.g., "look at this screenshot") when no MATLAB work is requested — use your own vision instead
Core Conventions
Image Data Types
| Type | Range | When to use |
|---|---|---|
uint8 | 0–255 | Display, file I/O, memory-efficient storage |
uint16 | 0–65535 | High dynamic range sensors, medical. Camera RAW is n-bit in a uint16 container — rescale with rawinfo BlackLevel/WhiteLevel, not 65535 |
single / double | 0.0–1.0 | Arithmetic, filtering, computation |
logical | 0 or 1 | Binary masks, segmentation results |
Most IPT functions accept integer types directly — do not convert to floating-point unless required.
Default Coordinate Conventions
MATLAB images are (row, col) — row is Y (down), column is X (right)
size(img)returns[height, width, channels]Spatial functions use (x, y) order for coordinates (e.g.,
imref2d,regionpropscentroids)Pixel centers are at integer intrinsic coordinates; in default world referencing, pixel (1,1) center is at world (1.0, 1.0) and the image edge starts at 0.5
imref2dandimref3dcan specify non-default spatial referencing to place images into world coordinate systems. By default they use the unit-spaced, integer-pixel-centered coordinate system described here, e.g.Rout = imref2d(imageSize). Functions that do not accept spatial referencing objects assume this intrinsic coordinate system for any operation requiring spatial referencing.
Multichannel Images
Grayscale:
M×NorM×N×1RGB:
M×N×3With alpha: read using
[img, ~, alpha] = imread(...)(alpha is the third output)Convert:
rgb2gray,im2gray(preferred, handles more input types)
Display Functions — use imageshow, not imshow
Always use imageshow instead of imshow in all generated code — scripts, apps, examples, and quick previews. The signatures are compatible for common cases: replace imshow(...) with imageshow(...). imageshow (R2024b+) handles sub-bit-depth containers (e.g., 12-bit in uint16) via DisplayRangeMode, supports OverlayData for label/mask overlays, and works with viewer2d. imshow lacks all of these capabilities and should not appear in new code.
Title convention: imageshow creates a viewer2d, not an axes — gca does not return it. To add a title, get the viewer from the Image object's parent:
obj = imageshow(im);
viewer = obj.Parent;
title(viewer, "Title Text");Do not use title("text") or title(gca, "text") after imageshow — these silently fail or create a stray axes title.
Code Execution
Execute code blocks via evaluate_matlab_code before presenting them to the user. If it errors, fix and re-run. This catches type mismatches, wrong argument orders, and nonexistent functions before the user sees them. If execution requires user data or toolboxes not available in the current session, present the code with a note that it should be run with the user's own data — do not loop trying to synthesize stand-in data.
Error Recovery
If code throws an error after execution, load the matlab-read-documentation skill and look up the function's doc page to verify syntax, required arguments, and supported input types before retrying.
When to Ask the User
Ask for clarification before proceeding when:
The image type/format is ambiguous and affects the processing approach
Multiple valid approaches exist with different tradeoffs (speed vs quality, lossy vs lossless)
The task requires choosing parameters that depend on domain knowledge (e.g., object size thresholds, noise characteristics)
The user's MATLAB release is unknown and the recommended function may not be available
Routing
Match your task in the tables below. Check the handoff table first. If the task belongs to another skill, load that skill in addition to this one — the Core Conventions above (data types, coordinate order, code execution) apply to all image data. Do not re-derive them from the sibling. If a row in both tables fits, the handoff table wins on workflow; this skill still owns conventions.
Unfamiliar data? Load
references/image-understanding.mdfirst — but only when class, range, or content is unknown.Starting from a function name, not a task? The function column is illustrative, not exhaustive. To locate any function:
grep -rln '<functionName>' references/. To look up syntax details, loadmatlab-read-documentation.Pipeline tasks: load several references; cap at three unless the task genuinely spans more.
Follow the patterns in loaded references. References contain specific code patterns and workflows — use them instead of improvising equivalent code from general knowledge.
No row matches? Name the owning product, state the closest IPT fallback, and say so — do not guess a reference.
Check first: is this another skill's job?
| If the task involves... | Also load |
|---|---|
| Segmenting anatomy — tumor, lesion, organ, vessel — in CT, MRI, PET, ultrasound; MedSAM; radiomics | No skill covers this — Medical Imaging Toolbox (segmentMedicalImage, groundTruthMedical); look up the doc page |
Displaying or viewing a 2-D image: imshow, imageshow, viewer2d, montage, mask overlay, annotation, colorbar, colormap, figure export | matlab-display-image |
Displaying a 3-D volume: volshow, viewer3d, isosurface rendering, slice viewer, orthogonal views | matlab-display-volume |
| Hyperspectral or multispectral cubes, spectral indices, unmixing, ENVI, band selection | matlab-analyze-spectral-images |
| Calling a PyTorch or ONNX vision model from MATLAB | matlab-integrate-pytorch-vision |
| OCR, text recognition, reading text out of an image | matlab-recognize-text (requires Computer Vision Toolbox) |
| Factory-floor visual inspection: anomaly detection, defect/scratch/dent detection, gauging, pass/fail counting | matlab-use-visual-inspection (requires Visual Inspection Toolbox, R2026b+) |
| Barcode or QR reading, camera calibration | No skill covers this — Computer Vision Toolbox (readBarcode, estimateCameraParameters); look up the doc page |
| Optical system design: lens import, prescription-side MTF, spot diagrams, ray tracing, tolerance analysis | matlab-model-optics |
In scope: pick the reference
| If the task or the user's words involve... | Illustrative functions | Load |
|---|---|---|
| inspect, understand, characterize, explore data, look at my images, what kind of image, what am I working with, what's in this folder, describe the data, summarize the dataset, what format, bit depth, class and range, indexed image, alpha channel, metadata, file info, dataset characterization, before I start processing | imfinfo, imhist, countEachLabel | references/image-understanding.md |
| read, write, load, save, import, export, open an image, convert format, batch, folder of images, TIFF, PNG, JPEG, RAW, HDR, test pattern | imread, imwrite, imageDatastore, hdrread | references/image-io.md |
| video, footage, frames, read video, write video, VideoReader, VideoWriter, frame rate, video codec, MP4, AVI | VideoReader, VideoWriter, readFrame, hasFrame, writeVideo | references/video-io.md |
| smooth, blur an image, sharpen, denoise, noise, grainy, filter, kernel, padding, edge-preserving, bilateral, non-local means, frequency filter | imgaussfilt, medfilt2, imsharpen, imbilatfilt, imnlmfilt, imdiffusefilt, imfilter, ordfilt2, locallapfilt, wiener2 | references/filtering.md |
| contrast, brighten, darken, too dark, washed out, enhance, improve, histogram, equalize, CLAHE, normalize, rescale, blend, arithmetic, type convert, flat-field, illumination correction, vignetting, uneven lighting | imadjust, stretchlim, adapthisteq, histeq, rescale, mat2gray, im2single, imadd, imlincomb, imblend, imflatfield | references/preprocessing.md |
| erode, dilate, open, close, structuring element, 2-D morphology, fill holes, remove small objects, skeletonize, thin, tidy up a binary result | strel, imerode, imdilate, imopen, imclose, imfill, bwareaopen, bwskel, imtophat, imreconstruct | references/morphological-ops.md |
| deblur, blurry, unfocused, out of focus, motion blur, camera shake, restore a blurred image, deconvolution, PSF estimation | deconvblind, deconvlucy, deconvwnr, deconvreg | references/deblurring.md |
| resize, rotate, crop, warp, scale, flip, straighten, affine, projective, perspective, undistort, lens distortion, spatial referencing, world coordinates, voxel coordinates, pixel coordinates, coordinate conversion | imresize, imrotate, imcrop, imwarp, imtranslate, affinetform2d, imref2d | references/geometric-transforms.md |
| align two images, stitch, mosaic, panorama, overlapping shots, seam, motion correction, multi-modal alignment, control points, non-rigid, deformable, homography (feature-based requires Computer Vision Toolbox) | imregister, imregtform, imregdemons, imregcorr, detectSIFTFeatures, matchFeatures, estgeotform2d (last three: Computer Vision Toolbox), imregdeform (Medical Imaging Toolbox) | references/registration.md |
segment or threshold with no user input: binarize, Otsu, watershed, k-means or colour clustering, imsegsam automatic mode, deep-learning segmentation | imbinarize, graythresh, multithresh, adaptthresh, watershed, imsegkmeans, imsegkmeans3, imsegisodata, imsegsam | references/segmentation-automated.md |
| segment with user input: clicks, points, boxes, scribbles, seeds, prompted SAM, grabcut, active contours, region growing, lazy snapping, superpixels, App Designer segmentation UIs | segmentAnythingModel, grabcut, activecontour, lazysnapping, imsegfmm, grayconnected, superpixels | references/segmentation-interactive.md |
| measure, count objects, how many, area, perimeter, centroid, size, shape, width, thickness, gap, diameter, Feret, orientation, detect edges, circles, lines, boundary tracing, ROI, world units, metrology, region, region properties, analysis | regionprops, bwconncomp, bwareafilt, bwpropfilt, bwlabel, edge, imfindcircles, hough, bwboundaries | references/analysis-measurement.md |
| quality, PSNR, SSIM, sharpness, noise level, is it blurry, compare two images, difference, before/after, MTF (camera/chart SFR), test chart, artifact (register first — full-reference metrics need pixel correspondence) | psnr, ssim, multissim, immse, brisque, niqe, piqe, measureSharpness, esfrChart | references/quality-assessment.md |
| texture, repetitive pattern, frequency domain, Fourier, FFT, DCT, Radon, Gabor, co-occurrence, GLCM | graycomatrix, graycoprops, entropyfilt, fft2, dct2, radon, gabor | references/texture-transforms.md |
| color space, LAB, HSV, hue, saturation, white balance, color cast, color correction, color balance, ICC profile, grayscale conversion | rgb2lab, lab2rgb, rgb2hsv, chromadapt, illumwhite, makecform, deltaE, decorrstretch | references/color-processing.md |
| 3-D array, volume, volumetric, voxel, slice stack, z-stack — filtering, 3-D morphology, 3-D transforms, or measurement applied to a volume | imgaussfilt3, medfilt3, imresize3, regionprops3, bwvolumefilt (R2026b), bwpropfilt3 (R2026b) | references/3d-volume-processing.md |
| deep learning, neural network, train, U-Net, semantic segmentation networks, classify images, pretrained model, transfer learning, fine-tune, inference, augment, training dataset (requires DLT, often CVT) | unet, deeplabv3plus, trainnet, semanticseg, imageDataAugmenter, augmentedImageDatastore | references/deep-learning-imaging.md |
| build your own image app or GUI: sliders, live preview, parameter tuning, ROI widgets | uifigure, uigridlayout, uislider, drawrectangle | references/app-building.md |
DICOM, NIfTI, NRRD, DICOM-RT, patient metadata, anonymizing, medicalVolume, medicalImage, reading/writing medical formats, extractSlice, volume orientation, medical spatial referencing | medicalVolume, medicalImage, dicomreadVolume, dicomCollection, extractSlice, dicomContours, dicomanon | references/medical-data-io.md |
gigapixel, whole-slide, out-of-memory images, blockedImage, tiled workflows, image pyramids, .svs, .ndpi, .czi, TIFF > 10,000 px, parallel image processing, custom adapters | blockedImage, apply, getBlock, getRegion, selectBlockLocations, blockedImageDatastore | references/large-image-processing.md |
Toolbox Detection
When unsure what's available, check installed toolboxes:
hasIPT = ~isempty(ver('images'));
hasCVT = ~isempty(ver('vision'));
hasDLT = ~isempty(ver('nnet'));
hasMIT = ~isempty(ver('medical'));
hasWavelet = ~isempty(ver('wavelet'));Most functions in this skill require Image Processing Toolbox. The deep-learning-imaging reference also requires Deep Learning Toolbox. Feature-based registration (detectSIFTFeatures, matchFeatures, estgeotform2d) requires Computer Vision Toolbox.
Release-Gated Features
This skill targets R2024b+ but some features require newer releases. References annotate these with the required release. Key ones:
R2024b:
imageshow,imblend,viewer2dR2026a:
uidraw,uipaint,linkviewersR2026b:
bwvolumefilt,bwpropfilt3,uiannotate
If targeting an older release, check with isMATLABReleaseOlderThan("R2026a") and use the fallback patterns documented in the references. To check release notes for a specific function, load matlab-read-documentation.
Copyright 2026 The MathWorks, Inc.
Files
- ATTRIBUTION.mdAdded by AutoGineer1.1 KiB
- LICENSELicence file added by AutoGineer1.4 KiB
- SKILL.md15.8 KiB
- manifest.yaml811 B
- references/3d-volume-processing.md20.2 KiB
- references/analysis-measurement.md18.5 KiB
- references/app-building.md16.9 KiB
- references/blocked-3d-volumes.md9.9 KiB
- references/blocked-data-discovery.md22.1 KiB
- references/blocked-geospatial.md3.2 KiB
- references/blocked-specialized-workflows.md4.3 KiB
- references/blocked-training-and-labeling.md7.0 KiB
- references/blocked-visualization.md5.1 KiB
- references/blocked-whole-slide-images.md3.1 KiB
- references/color-processing.md9.0 KiB
- references/deblurring.md8.1 KiB
- references/deep-learning-imaging.md14.8 KiB
- references/dicom-anonymization.md3.3 KiB
- references/dicom-rt-workflows.md7.4 KiB
- references/filtering.md21.8 KiB
- references/geometric-transforms.md14.3 KiB
- references/image-io.md15.5 KiB
- references/image-understanding.md20.0 KiB
- references/ipt-reading-writing.md4.8 KiB
- references/large-image-processing.md12.3 KiB
- references/medical-data-io.md8.3 KiB
- references/mit-medical-volume.md8.2 KiB
- references/mit-spatial-referencing.md5.9 KiB
- references/morphological-ops.md18.0 KiB
- references/preprocessing.md14.4 KiB
- references/quality-assessment.md13.5 KiB
- references/registration.md24.7 KiB
- references/segmentation-automated.md9.7 KiB
- references/segmentation-interactive.md15.3 KiB
- references/texture-transforms.md10.4 KiB
- references/video-io.md3.4 KiB
references/analysis-measurement.md
Analysis & Measurement
Decision guidance and gotchas for measuring region properties, detecting objects (edges, circles, lines), boundary tracing, and ROI-based processing.
Often loaded with:
segmentation-automated.md(creating masks to measure),morphological-ops.md(cleaning masks before measurement).
The Standard Analysis Pipeline
bw = imbinarize(img); % 1. Threshold
bw = imfill(bw, "holes"); % 2. Clean up
bw = imclearborder(bw); % 3. Remove border objects
cc = bwconncomp(bw); % 4. Find connected components
numObjects = cc.NumObjects; % 5. Object count
props = regionprops(cc, "Area", "Centroid", "Eccentricity"); % 6. Measurebwconncomp vs bwlabel
bwconncomp | bwlabel | |
|---|---|---|
| Dimensionality | 2-D, 3-D, N-D | 2-D only |
| Output | Struct with PixelIdxList | Double label matrix |
| Memory | Stores only pixel indices | Full image-sized label matrix |
| Connectivity control | Explicit via second argument | Limited |
Use bwconncomp when you need N-D support, explicit connectivity control, or want to avoid allocating a full label matrix. bwlabel is a concise 2-D labeling API that returns a label matrix directly — legitimate when that is the representation you need.
cc = bwconncomp(bw); % Component structure — N-D, explicit connectivity
L = labelmatrix(cc); % Create label matrix only when needed (uses smallest uint type)
bw2 = cc2bw(cc); % Convert back to binary (R2024a) — cleaner than labelmatrix(cc)>0
L = bwlabel(bw); % Direct label matrix — 2-D onlyregionprops — Measurement
Critical: Input Must Be logical for Binary Images
% WRONG — numeric [0,1] treated as label matrix (finds 1 region!)
BW = double(imbinarize(gray));
props = regionprops(BW, "Area"); % Returns 1 object
% CORRECT — logical input triggers connected component analysis
props = regionprops(logical(BW), "Area"); % Finds all objects
% BEST — use bwconncomp for explicit control over connectivity
cc = bwconncomp(logical(BW), 4); % 4-connected (default is 8)
props = regionprops(cc, "Area");If regionprops returns fewer objects than expected, check that the input is logical — numeric arrays (even with only 0/1 values) are interpreted as pre-formed label matrices.
Output Format: Struct (Default) vs Table
% Struct output (default)
props = regionprops(cc, "Area", "Centroid", "Eccentricity");
areas = [props.Area]; % Extract as numeric array
keep = areas > 500;
% Table output — convenient for display and complex filtering
props = regionprops("table", cc, "Area", "Centroid", "Eccentricity");
large = props(props.Area > 500, :);Performance tip: Compute all desired properties in a single regionprops call rather than calling it multiple times for different properties.
Coordinate Convention — Critical Gotcha
Centroid and BoundingBox use [x, y] coordinates, NOT [row, col]:
% Object at rows 20-40, cols 50-80:
% Centroid = [65.0, 30.0] → [x=col, y=row]
% BoundingBox = [49.5 19.5 31.0 21.0] → [x y width height]To plot centroids from struct output (default): centroids = cat(1, props.Centroid); plot(centroids(:,1), centroids(:,2), 'r+') — struct-array dot indexing returns a comma-separated list, so concatenate first. From table output: plot(props.Centroid(:,1), props.Centroid(:,2), 'r+') works directly.
To index into image: img(round(centroid(2)), round(centroid(1))) — swap order!
Intensity Measurements Require a Grayscale Image
% Shape-only properties:
props = regionprops("table", bw, "Area", "Perimeter", "Circularity");
% Intensity properties need the grayscale image as second arg:
props = regionprops("table", bw, gray, "MeanIntensity", "MaxIntensity", "PixelValues");Key Properties Reference
Shape (no intensity image needed):
| Property | What it measures |
|---|---|
Area | Pixel count |
Centroid | Center of mass [x, y] |
BoundingBox | [x y width height] enclosing rectangle |
Perimeter | Boundary length in pixels |
Circularity | Measure of circularity (max is 1.0, a perfect circle) |
Eccentricity | 0 (circle) to 1 (line) |
Solidity | Area / ConvexArea (1.0 = convex) |
Orientation | Angle of major axis (-90° to 90°) |
EquivDiameter | Diameter of circle with same area |
MajorAxisLength, MinorAxisLength | Equivalent ellipse axes (same 2nd moments) — not physical length |
MaxFeretProperties, MinFeretProperties | Structs with .MaxFeretDiameter/.MinFeretDiameter (caliper length/width), angle, and endpoint coordinates |
Extent | Area / BoundingBox area |
FilledArea | Area with holes filled |
ConvexArea | Area of convex hull |
EulerNumber | Objects minus holes |
BoundaryCoordinates | Exterior boundary pixels as N×2 [x, y] matrix (R2026a) |
BoundaryCoordinates (R2026a): Returns boundary pixel coordinates directly from regionprops, eliminating the need for a separate bwboundaries call. Coordinates are [x, y] (same as Centroid). Requires a bwconncomp struct or logical input — not supported with label matrix input. Use when you need both measurements and boundaries from the same regionprops call.
Measuring length: MajorAxisLength is the axis of an equivalent ellipse, not the actual object length. For non-elliptical shapes it can exceed the true extent. Use MaxFeretDiameter for actual length (longest caliper distance) and MinFeretDiameter for width.
Intensity (requires grayscale image):
| Property | What it measures |
|---|---|
MeanIntensity | Mean pixel value in region |
MaxIntensity | Maximum pixel value |
MinIntensity | Minimum pixel value |
PixelValues | Vector of all pixel values (can be large) |
WeightedCentroid | Intensity-weighted center [x, y] |
Filtering Objects by Properties
Three approaches, from simplest to most flexible:
% 1. One-liner with bwpropfilt (best for simple filters)
bw_large = bwpropfilt(bw, "Area", [500 Inf]);
bw_round = bwpropfilt(bw, "Eccentricity", [0 0.5]);
% 2. Struct filtering + cc2bw (for compound conditions, R2024a)
props = regionprops(cc, "Area", "Eccentricity");
keep = [props.Area] > 500 & [props.Eccentricity] < 0.5;
bw_filtered = cc2bw(cc, ObjectsToKeep=find(keep));
% 3. bwareafilt for size-only filtering
bw_large = bwareafilt(bw, [500 Inf]); % Area range
bw_top5 = bwareafilt(bw, 5); % N largest objectsPeak / Bright Spot Detection
For finding local intensity peaks (particles, fluorescent spots, stars, etc.):
To improve results from imregionalmax, always suppress small peaks first with imhmax — without suppression, every noise bump registers as a peak:
% Step 1: Suppress peaks with prominence < h
h = 20; % Minimum peak height above surroundings
suppressed = imhmax(gray, h); % Flatten insignificant peaks
% Step 2: Find regional maxima of the suppressed image
peaks = imregionalmax(suppressed); % Now only significant peaks remain
% Step 3 (optional): Sub-pixel localization via weighted centroid
props = regionprops(peaks, gray, "WeightedCentroid");
locations = cat(1, props.WeightedCentroid); % [x, y] sub-pixel positionsTuning h: too small → noise peaks detected; too large → real peaks merged or missed. Start with a value equal to your expected noise amplitude.
Alternative: imextendedmax(gray, h) combines both steps (equivalent to imregionalmax(imhmax(gray, h))).
For minima (dark spots): use imhmin + imregionalmin, or imextendedmin.
Distance Transform — bwdist
Computes the distance from every pixel to the nearest foreground (nonzero) pixel. Foreground pixels get 0:
D = bwdist(bw); % Euclidean distance (default)
D = bwdist(bw, "cityblock"); % Manhattan distance
[D, idx] = bwdist(bw); % Also returns linear index of nearest foreground pixelCommon uses:
Watershed segmentation prep:
watershed(-bwdist(~bw))separates touching objectsProximity analysis: find all pixels within distance
dof foreground —bwdist(bw) <= dGrouping nearby objects: see pattern in
morphological-ops.mdMedial axis:
bwdist+ local maxima gives a weighted skeleton
Distance methods: "euclidean" (default), "cityblock", "chessboard", "quasi-euclidean".
Edge Detection
edges = edge(gray, "Canny"); % Default thresholds
edges = edge(gray, "Canny", [0.05 0.15]); % Manual thresholds [low high]
edges = edge(gray, "Canny", [], 2); % Custom sigma ([] = auto threshold)Choosing a method:
| Method | Strength | Typical use |
|---|---|---|
"Canny" | Best general-purpose, thin edges | Default choice |
"Sobel" / "Prewitt" | Fast gradient magnitude | When speed matters |
"log" | Good at finding edges at specific scale | Scale-specific detection |
"Roberts" | Diagonal edge emphasis | Rarely preferred |
Gotcha: edge returns auto-computed thresholds as second output — useful for tuning:
[~, thresh] = edge(gray, "Canny"); % Get auto thresholds, then adjust
edges = edge(gray, "Canny", thresh * 0.8); % Slightly more sensitiveDirectional gradients: For "Sobel", "Prewitt", and "Roberts", the four-output syntax returns directional gradients:
[BW, thresh, Gx, Gy] = edge(gray, "Sobel"); % Gx = horizontal, Gy = verticalFor "Roberts", Gx and Gy correspond to 135° and 45° from horizontal, respectively. This syntax is not available for "Canny" or "log".
Gradient Magnitude and Direction — imgradient / imgradientxy
Unlike edge (which returns binary edges), these return continuous gradient values — useful for edge strength analysis, orientation maps, and feature computation:
[Gmag, Gdir] = imgradient(gray); % Magnitude + direction (degrees, [-180, 180])
[Gmag, Gdir] = imgradient(gray, "sobel"); % Methods: "sobel" (default), "prewitt", "central", "intermediate", "roberts"
[Gx, Gy] = imgradientxy(gray); % Directional gradients (x=horizontal, y=vertical)
[Gx, Gy] = imgradientxy(gray, "sobel"); % Methods: "sobel" (default), "prewitt", "central", "intermediate"When to use: imgradient for edge strength maps and orientation analysis; imgradientxy when you need the directional components separately (e.g., for steering filters or gradient-based features). For 3-D volumes, use imgradient3 / imgradientxyz (see 3d-volume-processing.md).
Circle Detection — imfindcircles
[centers, radii, metric] = imfindcircles(img, [rMin rMax], ...
"ObjectPolarity", "bright", ... % "bright" or "dark" circles on background
"Sensitivity", 0.85); % Default 0.85; higher finds more (more false positives)Key parameters:
ObjectPolarity—"bright"(default) or"dark". Must match the contrast of circular objects relative to the backgroundSensitivity(default 0.85) — higher values detect more circles but increase false positivesEdgeThreshold— controls which edge pixels vote in the accumulator. Default is computed automatically usinggraythresh. Lower it to detect faint or low-contrast circlesMethod—"PhaseCode"(default, typically faster for radius estimation) or"TwoStage"Radius range
[rMin rMax]— narrowing this range improves performance. Minimum radius ≤ 5 limits accuracy
[centers, radii] = imfindcircles(img, [20 40], ...
"Sensitivity", 0.92, "EdgeThreshold", 0.08);Behavioral notes:
Circle centers that fall outside the image are not returned
Concentric circle detection is limited — the algorithm may not reliably separate circles sharing a center
RGB input is converted to grayscale internally; binary input is smoothed before processing
imfindcirclesYOLO (R2026a) — deep learning circle detection that detects circles without a caller-supplied radius range and returns confidence scores. Requires the Image Processing Toolbox Model for Circle Detection support package (add-on):
[centers, radii, scores] = imfindcirclesYOLO(img);Alternative: template matching with normxcorr2 when gradient-based detection fails entirely (finds center but not radius — combine with edge detection for radius):
% For circles with known internal pattern (e.g., quadrant pattern)
template = repelem([0 1; 1 0], 50, 50); % Construct expected pattern
C = normxcorr2(template, gray);
[~, idx] = max(C(:));
[yPeak, xPeak] = ind2sub(size(C), idx);
center = [xPeak, yPeak] - [size(template,2) size(template,1)]/2 + 0.5; % Adjust for template offsetCreating Masks from Detected Circles
After detecting circles, create a binary mask directly (R2024a):
[centers, radii] = imfindcircles(img, [20 50]);
mask = circles2mask(centers, radii, size(img, [1 2]));This replaces manual approaches using viscircles or loops with insertShape.
Line Detection — Hough Transform
bw_edges = edge(gray, "Canny");
[H, theta, rho] = hough(bw_edges);
peaks = houghpeaks(H, numLines);
lines = houghlines(bw_edges, theta, rho, peaks, ...
"FillGap", 10, ... % Bridge gaps up to 10 pixels
"MinLength", 30); % Ignore segments shorter than 30 pixelsEach line in the output struct has .point1 and .point2 (endpoints as [x, y]).
Boundary Tracing — bwboundaries
[B, L] = bwboundaries(bw); % B is cell array of boundaries
% Default: includes holes, [row,col] coordinates, pixelcenter trace
% Each B{k} is N×2 matrix of [row, col] coordinates (NOT [x,y]!)Default behavior includes holes — the output contains boundaries for both objects and their holes. Pass "noholes" when hole boundaries are not needed, which can also improve performance:
B = bwboundaries(bw, 8, "noholes"); % Object boundaries only, fasterCoordinate gotcha: bwboundaries defaults to [row, col] ("yx") order — opposite of regionprops Centroid which is [x, y]. To plot: plot(B{k}(:,2), B{k}(:,1)) (swap columns). Use CoordinateOrder="xy" (R2023a) to get [x, y] directly.
TraceStyle: "pixeledge" vs "pixelcenter" (R2023a)
| TraceStyle | What it traces | Use when |
|---|---|---|
"pixelcenter" (default) | Polygon through centers of boundary pixels | General boundary detection, spatial indexing |
"pixeledge" | Polygon along outer edge of boundary pixels | When the downstream calculation requires pixel-edge geometry (e.g., overlay alignment, ROI export) |
These are different trace geometries — match TraceStyle to the coordinate convention your downstream calculation expects:
B = bwboundaries(bw, 8, "noholes", TraceStyle="pixeledge", CoordinateOrder="xy");
% B{k} is now [x, y] coordinates along the outer pixel edges — ready for plot() directlyCoordinateOrder and TraceStyle were both added in R2023a.
ROI-Based Processing
Apply filter only within a region:
mask = poly2mask(xVertices, yVertices, imgHeight, imgWidth);
filtered = roifilt2(img, mask, @(x) imgaussfilt(x, 3));Inpaint a region (fill from surroundings):
result = regionfill(img, mask); % Interpolates from boundary valuesCreate masks:
| Function | Input | Output |
|---|---|---|
poly2mask(x, y, m, n) | Polygon vertices | Binary mask |
createMask(roi) | ROI object (from drawpolygon etc.) | Binary mask |
roipoly(img) | Interactive polygon drawing | Binary mask |
Visualization
% Label overlay for display — use imageshow with OverlayData
imageshow(gray, OverlayData=L);
% For generating an RGB array (e.g., saving to file)
rgb = label2rgb(L, "jet", "k", "shuffle");
% Better adjacent-label contrast (R2025a) — maximizes color difference between neighbors
overlay = labeloverlay(gray, L, ColorAssignment="contrasting-neighbors");When to Escalate to Visual Inspection Toolbox
For the following tasks, the Visual Inspection Toolbox has built-in tools that supplement IPT measurement tools:
Shape matching for part localization or fixturing
Gauging and metrology (caliper measurements, fit a circle, or angle on edges)
Anomaly/defect detection where defect appearance varies
Counting with deep-learning counters (CounTR) or template matching at scale
Deployment to embedded targets, GPUs (TensorRT), or PLCs
If Visual Inspection Toolbox is installed: Use its purpose-built tools for these workflows — anomaly detection models, caliper tools, shape matchers, deployment pipelines. No sibling skill covers them.
If Visual Inspection Toolbox is NOT installed: Recommend the user consider it. IPT's regionprops, imfindcircles, and template matching via normxcorr2 can handle simple cases, but production machine vision metrology (sub-pixel edge detection, calibrated measurements, shape matching for fixturing) benefits significantly from the dedicated library.
Common Mistakes
| Mistake | Why it's wrong | Correct approach |
|---|---|---|
regionprops(BW, ...) with numeric BW | Numeric [0,1] treated as label matrix (1 object) | Ensure input is logical or pass bwconncomp output |
regionprops(bw, "MeanIntensity") | Intensity props need the gray image | regionprops(bw, gray, "MeanIntensity") |
Using Centroid as (row, col) for indexing | Centroid is [x, y] = [col, row] | img(round(c(2)), round(c(1))) |
bwlabel for 3-D or N-D images | bwlabel is 2-D only | Use bwconncomp for N-D data |
| Plotting boundaries without swapping | bwboundaries returns [row,col] | plot(B{k}(:,2), B{k}(:,1)) |
imfindcircles finds nothing | ObjectPolarity does not match image contrast | Try both "bright" and "dark" |
| Manual loop to filter by area | Verbose | bwpropfilt(bw, "Area", [min Inf]) |
ismember(L, find(keep)) to filter objects | Verbose (pre-R2024a) | cc2bw(cc, ObjectsToKeep=find(keep)) |
| Manual circle mask with loops | Slow and verbose | circles2mask(centers, radii, [m n]) (R2024a) |
Accessing props.Image from table without {} | R2022a+: always cell array in table output | Use props.Image{k} even for small objects |
Trusting Perimeter or Circularity on very small objects | 1-pixel object: Perimeter=0, Circularity=1.0; chain-code approximation degrades below ~10 pixels | Filter out small objects with bwareaopen before measuring shape properties |
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-process-images · 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-process-images.zip