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/segmentation-interactive.md
Interactive Segmentation
Decision guidance for segmentation methods that use user input — point/box prompts, scribbles, ROIs, seed points, or initial masks. Prompted SAM is a strong general-purpose option for point or bounding-box prompts; classical methods may be more appropriate when the task is defined by intensity similarity, edge contrast, or an initial mask.
Often loaded with:
morphological-ops.md(cleaning up masks),analysis-measurement.md(measuring segmented regions),segmentation-automated.md(when no user input is available).
Method Selection
| Task | User input | Algorithm |
|---|---|---|
| Segment an object from sparse visual prompts | Point or bounding box | segmentAnythingModel (prompted SAM 2 / SAM) (CVT+DLT) |
| Foreground/background separation | ROI rectangle | grabcut (requires superpixels) |
| Foreground/background from strokes | Scribbles | lazysnapping (requires superpixels) |
| 2–3 regions from strokes | Scribbles | imseggeodesic |
| Flood-fill from seed | Seed point + tolerance | grayconnected |
| Region growing from seeds | Seed points | imsegfmm |
| Evolving boundary to edges | Initial mask | activecontour |
| Medical organ/tumor (interactive box) | Bounding box | medicalSegmentAnythingModel (MIT) |
| Cell/nucleus instances | Automatic or prompted | cellpose → segmentCells2D / segmentCells3D (MIT) |
General-purpose recommendation: Use prompted SAM when available — it handles a wide range of scenarios with minimal user input and no training data. For tasks defined by intensity similarity (flood-fill, region growing) or evolving an initial mask to edges, the classical methods below may be more direct.
Coordinate order varies by function: SAM functions (ForegroundPoints, BoundingBox) use (x, y) order. grayconnected uses (row, col) order. graydiffweight and coordinate-based imsegfmm use (col, row) order (column first, then row). Active contour and masks use standard (row, col) array indexing.
Prompted SAM 2 and SAM (R2024b+)
Requires IPT Model for Segment Anything Model support package and Computer Vision Toolbox + Deep Learning Toolbox. By default, segmentAnythingModel uses "sam2-large" but also supports other SAM 2 variants (e.g., "sam2-tiny", "sam2-small", "sam2-base-plus") and the base SAM model ("sam-base").
try
sam = segmentAnythingModel; % Verifies support package and required add-on are available
hasSAM = true;
catch
hasSAM = false; % Help the user install the support package
endDo not use
whichalone — it can return true even when required add-ons are missing. Attempt construction to confirm usability.
Setup
sam = segmentAnythingModel; % Uses "sam2-large" by default
embeddings = extractEmbeddings(sam, I); % Expensive — do ONCE per imagePoint Prompts
% Single foreground point — [x, y] coordinates on the object
masks = segmentObjectsFromEmbeddings(sam, embeddings, size(I), ...
ForegroundPoints=[200 150]);
% Refine with background points
masks = segmentObjectsFromEmbeddings(sam, embeddings, size(I), ...
ForegroundPoints=[200 150], BackgroundPoints=[50 50; 350 350]);Bounding Box Prompt
% [x, y, width, height]
masks = segmentObjectsFromEmbeddings(sam, embeddings, size(I), ...
BoundingBox=[50 80 200 180]);Multiple Objects from Same Image
% Extract embeddings once, segment multiple times
embeddings = extractEmbeddings(sam, I);
mask1 = segmentObjectsFromEmbeddings(sam, embeddings, size(I), ...
ForegroundPoints=[100 200]);
mask2 = segmentObjectsFromEmbeddings(sam, embeddings, size(I), ...
BoundingBox=[300 100 150 200]);Key rules:
segmentObjectsFromEmbeddingsreturns an H×W logical mask (single best mask by default). UseReturnMultiMask=trueto get H×W×3 with three ranked candidates.Extract embeddings once per image, segment multiple objects from same embeddings
size(I)(third argument) is required — maps embeddings back to image coordinatesForegroundPointsandBoundingBoxuse (x, y) order, not (row, col)Combine foreground + background points for difficult cases
When SAM is unavailable: Use grabcut for foreground/background, activecontour for boundary refinement, or imsegfmm for region growing.
GrabCut — Foreground/Background from ROI
Gotcha: grabcut requires a superpixel label matrix in addition to the image. Always compute superpixels first:
[L, N] = superpixels(I, 500); % REQUIRED before grabcut
ROI = false(size(I,1), size(I,2));
ROI(50:300, 100:350) = true;
BW = grabcut(I, L, ROI);Works on 3-D volumes too (with superpixels3).
Lazy Snapping — Foreground/Background from Scribbles
Requires scribble masks indicating foreground and background regions. fgScribble and bgScribble are logical masks (same size as image) where true marks user-drawn strokes:
[L, N] = superpixels(I, 500); % REQUIRED before lazysnapping
BW = lazysnapping(I, L, fgScribble, bgScribble);Geodesic Segmentation — 2–3 Regions from Scribbles
For partitioning an image into a small number of regions based on user-drawn scribbles. Requires RGB input — does not work on grayscale. Returns a label matrix (not a binary mask):
L = imseggeodesic(RGB, scribble1, scribble2); % 2 regions
L = imseggeodesic(RGB, scribble1, scribble2, scribble3); % 3 regionsGray Connected — Flood-Fill from Seed
Simple region growing based on intensity similarity to a seed pixel:
BW = grayconnected(I, row, col, 20); % tolerance is positional (not a Name-Value pair)
% R2026b: restrict to 4-connected pixels (horizontal/vertical only)
BW = grayconnected(I, row, col, 20, Connectivity=4);Active Contours — Evolving Boundary
Evolves an initial mask toward object boundaries. Users struggle most with creating the initial mask. Options:
% From rough threshold + dilate (most common)
mask = imbinarize(I);
mask = imdilate(mask, strel("disk", 10));
BW = activecontour(I, mask, 200, "Chan-Vese");
% From bounding rectangle
mask = false(size(I));
mask(r1:r2, c1:c2) = true;
BW = activecontour(I, mask, 200, "edge");| Method | Use when |
|---|---|
"Chan-Vese" | Region-based, objects without strong edges |
"edge" | Objects with clear boundary edges |
Works on 3-D volumes with same syntax.
Fast Marching — imsegfmm
Region growing from seeds using a weight array:
% Weight from intensity difference to seed
% graydiffweight and imsegfmm take (C, R) order — column first, then row
W = graydiffweight(I, col, row, GrayDifferenceCutoff=25);
BW = imsegfmm(W, col, row, 0.01); % threshold on travel time
% Weight from gradient magnitude
W = gradientweight(I);
BW = imsegfmm(W, seedMask, 0.01);Medical Segmentation (Medical Imaging Toolbox)
For medical images with MIT available:
| Task | Function |
|---|---|
| 2-D organ/tumor (interactive box) | medicalSegmentAnythingModel |
| 3-D automatic (organs) | medicalImageLabeler with MONAI Label |
| Cell/nucleus segmentation | cellpose → segmentCells2D / segmentCells3D |
| Radiomic features from ROI | radiomics |
For full medical segmentation workflows (MedSAM, Cellpose, radiomics), see Medical Imaging Toolbox documentation.
Building Interactive Segmentation Apps
The Image Segmenter app (imageSegmenter) provides built-in interactive segmentation tools, including SAM. Use it for ad-hoc interactive segmentation sessions.
For custom apps, use App Designer with SAM. The pattern combines a viewer2d for display, annotation-based prompts, and real-time mask preview. For a complete walkthrough, see the doc example "Create an App to Segment Images with SAM" (R2026b).
Architecture Pattern
Build a custom UI component inheriting from matlab.ui.componentcontainer.ComponentContainer:
classdef SAMSegmenter < matlab.ui.componentcontainer.ComponentContainer
properties
Image
Mask
SavedMask
SegmentationAlpha = 0.5
end
properties (Access = private)
Model % segmentAnythingModel object
Embeddings % Extracted once per image
Viewer % images.ui.graphics.Viewer
ImageObject % Image displayed in viewer
Bbox % Current bounding box
SegmentRequired % Flag to trigger update
CurrentLabelID = 1
IsForegroundMode = true
end
methods (Access = protected)
function setup(comp)
comp.Viewer = viewer2d(comp);
comp.ImageObject = imageshow([], Parent=comp.Viewer);
comp.Viewer.AnnotationAddedFcn = @(~,evt) annotationAdded(comp, evt);
end
end
endKey Workflow: Load → Embed → Annotate → Preview → Commit
% 1. Load image and extract embeddings ONCE
function loadImage(comp, imageData)
comp.Image = imageData;
comp.Model = segmentAnythingModel("sam2-large");
comp.Embeddings = extractEmbeddings(comp.Model, imageData);
comp.ImageObject.Data = imageData;
comp.SavedMask = zeros(size(imageData, [1 2]), "uint8");
endAnnotation-Driven Segmentation (update method)
The update method fires whenever annotations change, providing real-time preview:
function update(comp)
if ~comp.SegmentRequired, return; end
comp.SegmentRequired = false;
imageSize = size(comp.ImageObject.Data);
annotations = comp.Viewer.Annotations;
% Collect foreground/background points from annotations
foreground = [];
background = [];
for idx = 1:numel(annotations)
if isa(annotations(idx), "images.ui.graphics.roi.Point") && isvalid(annotations(idx))
if annotations(idx).UserData % true = foreground
foreground(end+1,:) = annotations(idx).Position(1:2);
else
background(end+1,:) = annotations(idx).Position(1:2);
end
end
end
if isempty(foreground) && isempty(comp.Bbox), return; end
% Segment using current prompts
mask = segmentObjectsFromEmbeddings(comp.Model, comp.Embeddings, imageSize, ...
ForegroundPoints=foreground, BoundingBox=comp.Bbox, BackgroundPoints=background);
% Preview: overlay new mask on saved mask
priorMask = comp.SavedMask;
priorMask(mask) = uint8(comp.CurrentLabelID);
comp.ImageObject.OverlayData = priorMask;
endHandling Annotations via Viewer Events
Use the AnnotationAdded event from Viewer to process user interactions:
function annotationAdded(comp, event)
event.Annotation.Interactions = "click";
if isa(event.Annotation, "images.ui.graphics.roi.Rectangle")
% Bounding box drawn — save position, switch to point mode
comp.Bbox = event.Annotation.Position;
comp.Viewer.Mode.Annotate.Style = "point";
comp.Viewer.Mode.Annotate.ContinueAnnotating = true;
comp.Viewer.Mode.CurrentMode = "annotate";
else
% Point — validate it's inside bounding box
if ~isempty(comp.Bbox)
pos = event.Annotation.Position;
if pos(1) < comp.Bbox(1) || pos(2) < comp.Bbox(2) || ...
pos(1) > (comp.Bbox(1)+comp.Bbox(3)) || pos(2) > (comp.Bbox(2)+comp.Bbox(4))
delete(event.Annotation);
return;
end
end
event.Annotation.UserData = comp.IsForegroundMode;
end
comp.SegmentRequired = true;
endCommit / Revert Pattern
% Commit current preview to saved mask
function saveMask(comp)
comp.SavedMask = comp.ImageObject.OverlayData;
comp.Mask = comp.SavedMask;
comp.Viewer.Annotations = [];
comp.Bbox = [];
end
% Revert to last saved state
function clearAll(comp)
comp.Viewer.Annotations = [];
comp.ImageObject.OverlayData = comp.SavedMask;
comp.Bbox = [];
endApp-Level Integration
Wrap the component in an App Designer app with toolstrip controls:
function startupFcn(app)
app.SamSegmenter = SAMSegmenter(app.WorkingAreaGrid);
end
function loadImageFromFile(app)
[file, location] = uigetfile("*.*", "Select an image");
if ~isequal(file, 0)
d = uiprogressdlg(app.UIFigure, Title="Please Wait", ...
Message="Generating SAM embeddings...", Indeterminate="on");
imageData = imread(fullfile(location, file));
loadImage(app.SamSegmenter, imageData);
close(d);
end
end
function exportMask(app)
mask = app.SamSegmenter.Mask;
assignin("base", "SegmentedImage", mask);
endDesign Guidelines
Extract embeddings once per image — show a progress dialog since it's expensive
Use
ViewerwithOverlayDatafor real-time mask overlay (notlabeloverlay+ redraw)Validate point positions — discard points outside the active bounding box
Commit/revert pattern — let users build up multi-label masks incrementally
ComponentContainerinheritance — isolates segmentation logic from app layout for reusabilityUse
Viewer.Mode.Annotateto control annotation style (point vs rectangle) and continuation
This pattern extends beyond SAM — replace the segmentObjectsFromEmbeddings call with any interactive segmentation method (grabcut, activecontour, imsegfmm, etc.) to build custom annotation apps for any interactive segmentation workflow.
Displaying Segmentation Results
% Direct overlay display (preferred — one step, interactive)
imageshow(I, OverlayData=BW);
% For generating an RGB array (e.g., saving to file or further processing)
rgb = labeloverlay(I, BW, Transparency=0.5);Conventions
Always compute
superpixelsbeforegrabcutorlazysnappingFor prompted SAM, extract embeddings once per image — never per query
Use
bwareafiltorimfillto clean up after interactive segmentation (seemorphological-ops.md)Prompted SAM is a strong default when CVT+DLT are available; use classical methods when the task is better defined by intensity, edges, or an initial mask
Common Mistakes
| Mistake | Why it's wrong | Correct approach |
|---|---|---|
grabcut(I, [], ROI) without superpixels | Requires label matrix input | [L,N] = superpixels(I,500) then grabcut(I,L,ROI) |
extractEmbeddings per bounding box | Embeddings are expensive | Extract once, call segmentObjectsFromEmbeddings multiple times |
activecontour without initial mask | Requires a mask to evolve from | Threshold + dilate, or bounding rectangle |
regiongrowing(I, seed) | Does not exist in IPT | Use activecontour, imsegfmm, or grayconnected |
| SAM coordinates in (row, col) | SAM uses (x, y) order | ForegroundPoints=[x y], not [row col] |
graydiffweight(I, row, col) or imsegfmm(W, row, col, t) | These take (C, R) order — column first, then row | graydiffweight(I, col, row), imsegfmm(W, col, row, t) |
grayconnected(I, r, c, Tolerance=20) | Tolerance is positional, not a Name-Value pair | grayconnected(I, r, c, 20) |
imseggeodesic(grayImg, ...) | Requires RGB input; returns label matrix, not binary | L = imseggeodesic(RGB, scribble1, scribble2) |
imshow(I, OverlayData=BW) | imshow does not support OverlayData | imageshow(I, OverlayData=BW) (R2024b+) |
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