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/app-building.md
Image Processing Apps
Decision guidance for building interactive image processing applications using viewer2d, imageshow, ROI tools, and UI components.
Boundary with matlab-build-app: This reference covers image-specific UI: viewer2d/viewer3d, imageshow/volshow, uidraw/uipaint/uiannotate, ROI tools, and viewer callbacks. For general app infrastructure — uifigure, uigridlayout, standard UI components (uislider, uibutton, uidropdown, uitree, etc.), callbacks, and app packaging — see the matlab-build-app skill.
Often loaded with: whichever processing references the app needs (e.g.,
filtering.md,preprocessing.md,segmentation-automated.md).
Architecture: Modern Image App Stack (R2024b+)
uifigure
└── uigridlayout
├── viewer2d ← image container (left/main pane)
│ └── imageshow
└── uipanel ← controls (right/side pane)
└── uislider, uibutton, uidropdown, ...Key principle: Use the Viewer object created by viewer2d (for images) and viewer3d (for volumes) as the image container in apps — not axes + imshow. The viewer provides built-in pan, zoom, and pixel inspection, and is the parent for uidraw and uipaint.
Basic App Pattern
fig = uifigure(Name="Image Processor");
gl = uigridlayout(fig, [1 2], ColumnWidth={"1x", 200});
% Image viewer (left)
v = viewer2d(gl);
im = imageshow(img, Parent=v);
% Controls panel (right)
pnl = uipanel(gl, Title="Controls");
pgl = uigridlayout(pnl, [4 1], RowHeight={30, 30, 30, "1x"});
% Add controls
sld = uislider(pgl, Limits=[0 1], Value=0.5);
sld.ValueChangedFcn = @(src, ~) updateThreshold(im, img, src.Value);Updating the Display
Update the displayed image by setting properties on the Image object — do NOT recreate imageshow:
function updateThreshold(im, img, thresh)
bw = imbinarize(img, thresh);
im.Data = bw; % Replace the displayed image
% or
im.OverlayData = bw; % Show mask as overlay on original
endKey Image object properties for reactive updates:
| Property | Purpose |
|---|---|
im.Data | Replace displayed image data |
im.OverlayData | Add/update label or mask overlay |
im.DisplayRange | Change window/level |
im.DisplayRangeMode | "data-range", "type-range", "manual" |
im.Colormap | Change colormap |
im.AlphaData | Transparency mask |
ROI Drawing — uidraw (R2026a)
uidraw creates interactive ROIs in viewer2d/viewer3d contexts.
% Interactive drawing (blocks until user finishes)
roi = uidraw(v, "polygon"); % Wait="drawing" (default)
roi = uidraw(v, "rectangle", Wait="accept"); % Blocks until Enter or accept icon — lets user adjust shape before returning
% Programmatic placement (non-interactive)
roi = uidraw(v, "rectangle", Position=[50 50 100 80], Wait="none");Available Shapes
"point", "line", "rectangle", "circle", "ellipse", "polygon", "polyline", "freehand", "angle" (all R2026a)
Position Format
Position formats vary by shape. Compact shapes use a fixed-length vector; vertex-based shapes use an Nx2 or Nx3 matrix. An optional z coordinate defaults to 1 when omitted — and roi.Position always includes z when read back.
% Rectangle: [xmin ymin width height]
roi = uidraw(v, "rectangle", Position=[50 50 100 80], Wait="none");
% Circle: [x y radius] or [x y z radius]
% Ellipse: [x y semix semiy] or [x y semix semiy theta]
% Angle: similar — optional z in center coordinate
% Polygon/polyline/freehand: Nx2 or Nx3
roi = uidraw(v, "polygon", ...
Position=[50 50; 150 50; 150 150; 50 150], Wait="none");
% Point: [x y] or [x y z]
roi = uidraw(v, "point", Position=[100 100], Wait="none");Getting a Mask from ROI
roi = uidraw(v, "polygon");
mask = createMask(roi); % Binary mask matching displayed image sizeMultiple ROIs
% Interactive: draw multiple, press Enter or accept icon when done
rois = uidraw(v, "polygon", Wait="multiple");
% Programmatic: pass multiple positions as rows of a matrix
rois = uidraw(v, "rectangle", Position=[50 50 100 80; 200 200 60 60]);Viewer Callbacks
Set callbacks on the viewer to respond to user interaction:
% All viewer callbacks were introduced in R2026b
% Click on viewer content — image, volume, or surface
v.ObjectClickedFcn = @(~,evt) onObjectClicked(evt);
% Camera callbacks — after camera settles vs. during movement
v.CameraMovedFcn = @(~,~) updateStatusBar(v.CameraZoom);
v.CameraMovingFcn = @(~,~) showMovingIndicator(); % fires continuously while moving
% Annotation lifecycle callbacks
v.AnnotationAddedFcn = @(~,evt) onAnnotationAdded(evt);
v.AnnotationMovedFcn = @(~,evt) onAnnotationMoved(evt);
v.AnnotationRemovedFcn = @(~,evt) onAnnotationRemoved(evt);Note: AnnotationMovedFcn fires after the move is complete — not continuously during dragging. Use legacy draw* tools if you need per-ROI real-time movement events (MovingROI).
Accessing and Managing Annotations Programmatically
All annotations in a viewer are stored in the Annotations property. Annotations can come from interactive drawing (uidraw, see above), static overlays (uiannotate, see below), or direct constructor calls. You can iterate and modify them:
% Iterate all annotations
for roi = v.Annotations'
roi.Color = [1 0 0];
end
% Index directly
v.Annotations(1).Label = "Region A";
% Count
n = numel(v.Annotations);Note: Annotations may be different types (rectangles, polygons, points, etc.) with different properties, so filtering by property values like {v.Annotations.Label} only works when all annotations share that property. Use isprop or iterate with type checks when mixing annotation types.
SpatialUnits affects display only: Setting v.SpatialUnits = "mm" changes the units shown in measurement labels on the viewer. It does NOT convert ROI position coordinates or measurement properties — roi.Position and distance properties always return values in pixel/voxel units. Apply your own scale factor when converting to world units.
v.SpatialUnits = "mm"; % display labels show "mm"
roi.Position % still in pixel coordinates
roi.Position * pixelSpacing % convert yourselfStatic Annotations — uiannotate (R2026b)
uiannotate places static (non-interactive) annotations. Unlike uidraw, each call accepts all positions at once as a matrix — this makes it the right choice for displaying large numbers of overlays from detection or segmentation results.
% Pass all positions in one call
rects = uiannotate(v, "rectangle", positions); % N-by-4: [x y w h] per row
circs = uiannotate(v, "circle", positions); % N-by-3: [x y r] per row
pts = uiannotate(v, "point", positions); % N-by-2: [x y] per row
arrows = uiannotate(v, "arrow", positions); % N-by-4: [x1 y1 x2 y2] (endpoints) or N-by-5: [x y u v mag] (direction+magnitude) per rowAvailable shapes: "rectangle", "circle", "ellipse", "line", "polyline", "point", "arrow", "plus", "cuboid", "sphere", "ellipsoid", "cylinder"
The returned annotation object has these properties: Color (N-by-3 matrix for per-annotation colors), Alpha, FaceAlpha, Visible, Tag, UserData.
Rendering Updates and Performance
The viewer renders changes efficiently when MATLAB drives the update cycle naturally. Avoid calling drawnow inside loops that update annotation properties — this interrupts the normal update cycle and forces a full display refresh after each individual change, which is significantly slower when working with many annotations.
% Avoid — forces a render after every single property change
for i = 1:numel(rois)
rois(i).Color = newColors(i,:);
drawnow % do not do this in a loop
end
% Prefer — let the viewer process all changes together
for i = 1:numel(rois)
rois(i).Color = newColors(i,:);
endUse drawnow only when you explicitly need the display to update at a specific point — for example, when capturing frames for an animation or showing incremental progress between long operations. In normal app code driven by callbacks, MATLAB handles rendering automatically.
Performance note: Above ~500 annotations, uidraw issues a warning and performance degrades. Use uiannotate for large overlay sets — it is optimized for displaying hundreds to thousands of static annotations.
Paintbrush Annotation — uipaint (R2026a)
For freeform mask painting:
v = viewer2d;
im = imageshow(img, Parent=v);
mask = uipaint(im, BrushSize=15); % Blocks until user finishesMulti-label painting:
im = imageshow(img);
mask1 = uipaint(im, BrushSize=10, OverlayValue=1);
mask2 = uipaint(im, BrushSize=10, OverlayValue=2);Viewer Camera Controls
All camera properties are on the shared Viewer object used by both viewer2d and viewer3d.
| Property | Purpose | Since |
|---|---|---|
CameraZoom | Zoom level (1 = default fit) | — |
CameraPosition | Camera location [x y z] | — |
CameraTarget | Point camera looks at [x y z] | — |
CameraUpVector | Up direction ([0 0 1] default for both viewer2d and viewer3d) | — |
CameraProjection | "orthographic" (default) or "perspective" | R2026a |
CameraViewAngle | Field of view in degrees (default 45, range 0–180); only meaningful with "perspective" projection | R2026a |
CameraViewport | Visible region as [x y width height] in world coordinates | R2026a |
CameraInteractionStyle | Style of rotate, zoom, and pan — see table below | R2026a |
% Programmatic zoom reset button
btn = uibutton(pgl, Text="Reset View");
btn.ButtonPushedFcn = @(~,~) set(v, CameraZoom=1);
% Focus viewer on a specific image region (R2026a)
v.CameraViewport = [x y width height];
% Set view to a standard angle on a 3-D viewer (R2026a)
viewangle(v3d, 45, 30); % azimuth, elevationCameraInteractionStyle Values (R2026a)
Default is "planar" for viewer2d and "scene-orbit" for viewer3d.
| Value | Rotate around | Notes |
|---|---|---|
"scene-orbit" | Scene center | Default for viewer3d |
"click-orbit" | Clicked location | Common for point clouds |
"target-orbit" | CameraTarget | Useful when focusing on a specific object |
"focus-orbit" | Most recent zoom location | Useful when zooming in then rotating around a feature |
"planar" | Scene center (roll only) | Default for viewer2d — image plane stays constant |
"dolly" | — | First-person perspective; requires CameraProjection="perspective" |
"walk" | — | First-person flyover, z stays constant; requires CameraProjection="perspective" |
% Make viewer display-only (disable all user interaction)
v.Interactions = "none";
% Hide or auto-hide toolbar for cleaner app UI
v.Toolbar = "off"; % always hidden
v.Toolbar = "hover"; % appears on mouse-over onlyLinked Viewers (R2026a)
Synchronize pan/zoom across multiple viewers:
gl = uigridlayout(fig, [1 2]);
v1 = viewer2d(gl);
v2 = viewer2d(gl);
imageshow(original, Parent=v1);
imageshow(processed, Parent=v2);
linkviewers([v1 v2]); % Synchronized pan/zoomCropping the Viewer
CropRegion clips the displayed scene to a region — useful for focusing a volume app on a structure of interest after detection. The underlying data is not modified; only the visualization is affected.
% Crop to a rectangular box around a detected region (R2023b)
v.CropRegion = [xmin ymin zmin; xmax ymax zmax];
% Clear the crop
v.CropRegion = [];For 2-D viewers, use CameraViewport instead — CropRegion is primarily for 3-D/volume scenes.
| Property | Purpose |
|---|---|
CropRegion | 2-by-3 matrix (rectangular), [x y z r] (spherical, R2024b), 5-element vector (cylindrical, R2024b) |
CropMode | "inclusive" (show inside, default) or "exclusive" (hide inside) |
CropInteractions | "all" (user can drag crop box, default) or "none" (programmatic only) |
% Programmatic-only crop with no user interaction
v.CropRegion = [xmin ymin zmin; xmax ymax zmax];
v.CropInteractions = "none";
% Inverted crop — hide the interior, show the surroundings
v.CropMode = "exclusive";Legacy ROI Tools (R2018b+, axes-based)
For apps using traditional axes (not viewer2d):
ax = uiaxes(gl);
imshow(img, Parent=ax); % Legacy: axes-based display
roi = drawpolygon(ax); % Interactive polygon
roi = drawrectangle(ax, Position=[50 50 100 80]); % Programmatic
mask = createMask(roi);Legacy ROI events (richer than uidraw):
addlistener(roi, "ROIMoved", @(src, ~) onROIMoved(src));
addlistener(roi, "MovingROI", @(src, evt) onMoving(evt));Available events: MovingROI, ROIMoved, ROIClicked, DeletingROI, DrawingStarted, DrawingFinished
When to Use Legacy vs Modern
| Use case | Approach |
|---|---|
| New app (R2024b+) | viewer2d + imageshow (add uidraw from R2026a) |
| Need ROI event callbacks | Legacy draw* in axes (richer events) |
| Volume display in app | viewer3d + volshow |
Existing app with uiaxes | Legacy draw* functions |
Visual Inspection Metrology Tools (requires Visual Inspection Toolbox)
These tools add precision measurement overlays to an image displayed with imageshow. All take the imageshow Image object as input — not the viewer.
im = imageshow(img); % Image object, not the viewer| Function | Purpose | Key output property | Since |
|---|---|---|---|
uicaliper(im) | Edge-pair distance along a scan line | IntraEdgeDistance, InterEdgeDistance | R2025a |
uitsquare(im) | Point-to-line perpendicular distance (T-square) | Distance | R2026b |
uifitcircle(im) | Circle fitting — center, radius, area | Center, Radius, Area | R2026b |
uifitangle(im) | Angle between two lines | Theta | R2026b |
% Caliper: measure edge-pair distances interactively
cal = uicaliper(im, EdgeTransition="rising");
d = cal.IntraEdgeDistance; % distance within each edge pair
% T-square: point-to-line perpendicular distance
tsq = uitsquare(im);
d = tsq.Distance; % N-by-1 perpendicular distances
% Circle fit: fit circle to circular feature
circ = uifitcircle(im, Snap=true);
r = circ.Radius;
c = circ.Center;
% Angle: measure angle between two edges
ang = uifitangle(im);
theta = ang.Theta;uitsquare, uifitcircle, and uifitangle have a snap() method that automatically aligns the tool to detected edges:
tsq = uitsquare(im, LineSnapMethod="closest", EdgeMap="canny");
snap(tsq); % aligns tool to detected edgesComplete App Example
function imageThresholdApp(img)
fig = uifigure(Name="Threshold App");
gl = uigridlayout(fig, [2 2], ...
RowHeight={"1x", 40}, ColumnWidth={"1x", "1x"});
% Original and result viewers
v1 = viewer2d(gl); v1.Layout.Row = 1; v1.Layout.Column = 1;
v2 = viewer2d(gl); v2.Layout.Row = 1; v2.Layout.Column = 2;
linkviewers([v1 v2]);
gray = im2gray(img);
im1 = imageshow(img, Parent=v1);
im2 = imageshow(imbinarize(gray), Parent=v2);
% Threshold slider
sld = uislider(gl, Limits=[0 1], Value=graythresh(gray));
sld.Layout.Row = 2; sld.Layout.Column = [1 2];
sld.ValueChangedFcn = @(src, ~) updateResult(im2, img, src.Value);
end
function updateResult(im, img, thresh)
im.Data = imbinarize(img, thresh);
endCommon Mistakes
| Mistake | Why it's wrong | Correct approach |
|---|---|---|
figure instead of uifigure | figure includes toolstrips and behaviors not suitable for apps | Use uifigure for apps |
imtool for interactive viewing | Legacy, will be removed | Use viewer2d + imageshow |
imshow in uifigure app | Creates axes, no viewer features | Use viewer2d + imageshow |
Recreating imageshow on each update | Slow, flickers, loses zoom state | Set im.Data = newImg instead |
drawpolygon in viewer2d | Legacy ROIs need axes parent | Use uidraw(v, "polygon") |
Reading uidraw Position and expecting no z column | All shapes store z (defaults to 1) — Position always includes z when read back | Expect z in roi.Position |
uipaint(v) passing viewer | Takes Image object, not viewer | uipaint(im) where im = imageshow(...) |
Building ROI callbacks with uidraw | New ROIs lack MovingROI events | Use legacy draw* if real-time events needed |
Calling drawnow after each annotation change in a loop | Forces one render per change — prevents efficient batching | Update all properties first, let MATLAB handle rendering |
Expecting roi.Position in world units after setting SpatialUnits | SpatialUnits only changes display labels — positions stay in pixels | Apply pixelSpacing scale factor yourself |
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