Generated banner for Matlab Process Images
Generated logo for Matlab Process Images

Matlab Process Images

MathWorksOfficialCreated by MathWorks

  • Skill
  • Tool integration
  • Software development
  • BSD-2-Clause
  • No issues found

From the author

Load this first for any MATLAB task involving images, photos, scans, frames, volumes, or visual data — reading, writing, filtering, enhancing, denoising, sharpening, deblurring, thresholding, segmenting, masking, detecting, counting objects, removing backgrounds, measuring, registering, stitching, aligning, cropping, resizing, or transforming. Covers image I/O (TIFF, PNG, JPEG, RAW, HDR), histograms, edge detection, color, morphology, deep learning for images, quality assessment, and 3-D volumes. Also for image problems (dark, noisy, blurry, low contrast, uneven lighting, hazy, color cast) or data exploration (folder of images). Includes medical imaging I/O (DICOM, NIfTI, NRRD, medicalVolume) and large/blocked images (blockedImage, whole-slide). Skip if the user just wants you to look at an image, with no MATLAB work. Not for Simulink video-block models, C/C++/CUDA code generation or GPU deployment of a network, or point clouds. Hyperspectral and visual inspection have sibling skills.
— the description by MathWorks

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

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/matlab/matlab-process-images/download
  2. Unzip 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
TypeRangeWhen to use
uint80–255Display, file I/O, memory-efficient storage
uint160–65535High dynamic range sensors, medical. Camera RAW is n-bit in a uint16 container — rescale with rawinfo BlackLevel/WhiteLevel, not 65535
single / double0.0–1.0Arithmetic, filtering, computation
logical0 or 1Binary 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, regionprops centroids)

  • 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

  • imref2d and imref3d can 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×N or M×N×1

  • RGB: M×N×3

  • With 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.md first — 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, load matlab-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; radiomicsNo 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 exportmatlab-display-image
Displaying a 3-D volume: volshow, viewer3d, isosurface rendering, slice viewer, orthogonal viewsmatlab-display-volume
Hyperspectral or multispectral cubes, spectral indices, unmixing, ENVI, band selectionmatlab-analyze-spectral-images
Calling a PyTorch or ONNX vision model from MATLABmatlab-integrate-pytorch-vision
OCR, text recognition, reading text out of an imagematlab-recognize-text (requires Computer Vision Toolbox)
Factory-floor visual inspection: anomaly detection, defect/scratch/dent detection, gauging, pass/fail countingmatlab-use-visual-inspection (requires Visual Inspection Toolbox, R2026b+)
Barcode or QR reading, camera calibrationNo 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 analysismatlab-model-optics
In scope: pick the reference
If the task or the user's words involve...Illustrative functionsLoad
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 processingimfinfo, imhist, countEachLabelreferences/image-understanding.md
read, write, load, save, import, export, open an image, convert format, batch, folder of images, TIFF, PNG, JPEG, RAW, HDR, test patternimread, imwrite, imageDatastore, hdrreadreferences/image-io.md
video, footage, frames, read video, write video, VideoReader, VideoWriter, frame rate, video codec, MP4, AVIVideoReader, VideoWriter, readFrame, hasFrame, writeVideoreferences/video-io.md
smooth, blur an image, sharpen, denoise, noise, grainy, filter, kernel, padding, edge-preserving, bilateral, non-local means, frequency filterimgaussfilt, medfilt2, imsharpen, imbilatfilt, imnlmfilt, imdiffusefilt, imfilter, ordfilt2, locallapfilt, wiener2references/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 lightingimadjust, stretchlim, adapthisteq, histeq, rescale, mat2gray, im2single, imadd, imlincomb, imblend, imflatfieldreferences/preprocessing.md
erode, dilate, open, close, structuring element, 2-D morphology, fill holes, remove small objects, skeletonize, thin, tidy up a binary resultstrel, imerode, imdilate, imopen, imclose, imfill, bwareaopen, bwskel, imtophat, imreconstructreferences/morphological-ops.md
deblur, blurry, unfocused, out of focus, motion blur, camera shake, restore a blurred image, deconvolution, PSF estimationdeconvblind, deconvlucy, deconvwnr, deconvregreferences/deblurring.md
resize, rotate, crop, warp, scale, flip, straighten, affine, projective, perspective, undistort, lens distortion, spatial referencing, world coordinates, voxel coordinates, pixel coordinates, coordinate conversionimresize, imrotate, imcrop, imwarp, imtranslate, affinetform2d, imref2dreferences/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 segmentationimbinarize, graythresh, multithresh, adaptthresh, watershed, imsegkmeans, imsegkmeans3, imsegisodata, imsegsamreferences/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 UIssegmentAnythingModel, grabcut, activecontour, lazysnapping, imsegfmm, grayconnected, superpixelsreferences/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, analysisregionprops, bwconncomp, bwareafilt, bwpropfilt, bwlabel, edge, imfindcircles, hough, bwboundariesreferences/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, esfrChartreferences/quality-assessment.md
texture, repetitive pattern, frequency domain, Fourier, FFT, DCT, Radon, Gabor, co-occurrence, GLCMgraycomatrix, graycoprops, entropyfilt, fft2, dct2, radon, gaborreferences/texture-transforms.md
color space, LAB, HSV, hue, saturation, white balance, color cast, color correction, color balance, ICC profile, grayscale conversionrgb2lab, lab2rgb, rgb2hsv, chromadapt, illumwhite, makecform, deltaE, decorrstretchreferences/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 volumeimgaussfilt3, 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, augmentedImageDatastorereferences/deep-learning-imaging.md
build your own image app or GUI: sliders, live preview, parameter tuning, ROI widgetsuifigure, uigridlayout, uislider, drawrectanglereferences/app-building.md
DICOM, NIfTI, NRRD, DICOM-RT, patient metadata, anonymizing, medicalVolume, medicalImage, reading/writing medical formats, extractSlice, volume orientation, medical spatial referencingmedicalVolume, medicalImage, dicomreadVolume, dicomCollection, extractSlice, dicomContours, dicomanonreferences/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 adaptersblockedImage, apply, getBlock, getRegion, selectBlockLocations, blockedImageDatastorereferences/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, viewer2d

  • R2026a: uidraw, uipaint, linkviewers

  • R2026b: 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

references/3d-volume-processing.md

3-D Volume Processing

Decision guidance for processing 3-D volumetric data: filtering, morphology, segmentation, measurement, geometric transforms, and the key differences from 2-D workflows.

Often loaded with: segmentation-automated.md (3-D segmentation methods), segmentation-interactive.md (interactive masks and region growth), analysis-measurement.md (regionprops3 measurement), geometric-transforms.md (2-D transform basics that carry over to 3-D), registration.md (3-D volume alignment and deformable registration), image-io.md (loading multi-page TIFFs into 3-D arrays).

Critical: What Works Differently in 3-D

Many 2-D IPT functions extend to 3-D, but some don't. Key incompatibilities:

Function3-D support3-D alternative
imadjustNoimadjustn
adapthisteq (CLAHE)No (2-D grayscale only)Apply per-slice or use imadjustn
imhistmatch2-D onlyimhistmatchn (N-D)
edgeNo (2-D only)edge3 (methods: "approxcanny", "Sobel") or imgradient3
imgradient2-D onlyimgradient3
imgradientxy2-D onlyimgradientxyz
bwareafilt / bwpropfiltNo (2-D only)bwvolumefilt / bwpropfilt3 (R2026b+), or regionprops3 + ismember
bwlabel2-D onlybwlabeln
bwselect2-D onlybwselect3
bwboundaries2-D onlyNo direct 3-D equivalent — use isosurface or bwperim + surface extraction
bwmorph2-D onlybwmorph3
superpixels2-D onlysuperpixels3
imsegkmeans2-D spatial only (treats 3rd dim as channels, output is M×N not M×N×P)imsegkmeans3
imresizeRuns but in-plane only (no Z resize)imresize3 for true 3-D
imrotateRuns but in-plane only (no Z rotation)imrotate3 for true 3-D
imcrop2-D onlyimcrop3
medfilt2No — errors on 3-Dmedfilt3
imgaussfiltRuns on 3-D but per-slice (no Z smoothing)imgaussfilt3 for true 3-D
imboxfiltRuns on 3-D but per-slice (no Z smoothing)imboxfilt3 for true 3-D
integralImage / integralBoxFilterRun on 3-D but per-sliceintegralImage3 / integralBoxFilter3 for true 3-D
fspecial2-D onlyfspecial3 (types: "average", "ellipsoid", "gaussian", "laplacian", "log", "prewitt", "sobel")
imsharpenNo (2-D grayscale/RGB only)imfilter with fspecial3("laplacian") for unsharp masking
imflatfieldNo (2-D grayscale/RGB only)Apply per-slice, or imgaussfilt3 + division for background correction
label2rgbNo (2-D only)volshow(V, OverlayData=L) for 3-D label visualization
regionpropsAccepts 3-D but limited subset (Area, Centroid, BoundingBox, PixelIdxList, PixelList, Image, SubarrayIdx, FilledImage, FilledArea, and intensity properties) — shape/moment properties are 2-D onlyregionprops3 for full 3-D property set

Functions that do work on N-D arrays without change: imbinarize, imerode, imdilate, imopen, imclose, imtophat, imbothat, imfill, imclearborder, bwareaopen, bwconncomp, bwdist, bwskel (prefer for 3-D; for 2-D use bwmorph "skel"), bwperim (with 6/18/26 conn), watershed, imhmin, imhmax, imregionalmax, imregionalmin, imextendedmax, imextendedmin, imreconstruct, imimposemin, imfilter, adaptthresh (accepts 2-D matrix or 3-D array), graythresh, imadjustn, imhistmatchn, imwarp (with 3-D transform), bwlabeln.

3-D Structuring Elements

se = strel("sphere", 3);       % Sphere of radius 3
se = strel("cube", 5);         % 5×5×5 cube
se = strel("cuboid", [3 3 7]); % Anisotropic cuboid

Do not use strel("disk", …) or strel("square", …) for volumetric morphology — those are 2-D SEs. imerode/imdilate will accept them on a 3-D input without erroring, but silently apply the SE per-slice (no Z coupling), giving 2-D behavior instead of true 3-D morphology.

Anisotropic data (e.g., CT with 0.5×0.5×2.5 mm spacing): Use strel("cuboid", …) scaled to approximate isotropy in physical space:

voxelSize = [0.5 0.5 2.5];  % [row col slice] in mm
targetRadius = 2;  % mm
seSize = round(2*targetRadius ./ voxelSize);
seSize = seSize + (1 - mod(seSize, 2));  % Ensure odd
se = strel("cuboid", seSize);

Connectivity in 3-D

ConnectivityNeighborsMeaningUse when
6Adjacent faces onlyStrictestObjects should connect only through faces
18Face + edgeModerateGood default for most segmentation
26Face + edge + vertexMost permissiveDefault for bwconncomp in 3-D

Gotcha: Default connectivity for bwconncomp, bwvolumefilt, and bwpropfilt3 on 3-D is 26 (most permissive). For segmentation tasks where you want to separate nearby objects, explicitly use 6:

cc = bwconncomp(bw3d, 6);           % Stricter separation
bw = bwvolumefilt(bw3d, 5, 6);      % 5 largest by volume, 6-connectivity

Filtering

Use imgaussfilt3 / imboxfilt3 to apply true 3-D filtering to volumetric data. imgaussfilt and imboxfilt accept 3-D arrays without error or warning but filter per-slice only (no Z-axis smoothing).

% Gaussian smoothing
smoothed = imgaussfilt3(V, sigma);            % Isotropic sigma
smoothed = imgaussfilt3(V, [sx sy sz]);       % Anisotropic sigma

% Median filtering
denoised = medfilt3(V);                       % Default 3×3×3
denoised = medfilt3(V, [3 3 5]);              % Anisotropic kernel

% Box filtering (fast mean)
mean3 = imboxfilt3(V, [3 3 3]);

% Custom 3-D kernel via imfilter 
h = fspecial3("gaussian", [7 7 7], 1.5);      
filtered = imfilter(V, h, "replicate");

% Anisotropic diffusion (edge-preserving)
% imdiffusefilt accepts 3-D grayscale volumes directly
denoised = imdiffusefilt(V);

% Mode filter for label/categorical volumes (preserves discrete values)
labelSmoothed = modefilt(labelVol, [3 3 3]);

Choosing a 3-D denoiser:

FilterSpeedPreserves edgesNotes
imgaussfilt3FastNoStandard smoothing
imboxfilt3Very fastNoUses 3-D integral image internally
medfilt3MediumYesBest for salt-and-pepper on volumes
modefiltFastN/A (categorical)Smooths label/categorical volumes — preserves discrete class values
imdiffusefilt (on volume)Slow (iterative)YesBest when strong noise + edge detail matters

imnlmfilt, imbilatfilt, imguidedfilter, locallapfilt, and localcontrast are 2-D only. Apply per-slice if you need them on a volume. See filtering.md for parameter guidance and type restrictions on these 2-D filters.

Edge Detection — edge3 and imgradient3

% edge3 — threshold is REQUIRED (unlike 2-D edge which auto-computes)
BW = edge3(V, "approxcanny", 0.5);              % Scalar threshold
BW = edge3(V, "approxcanny", [0.2 0.5]);        % [low high] thresholds
BW = edge3(V, "approxcanny", [0.2 0.5], 1.5);   % With sigma

BW = edge3(V, "Sobel", 0.3);                    % Sobel method

% imgradient3 — gradient magnitude and direction (not binary edges)
[Gmag, Gazimuth, Gelevation] = imgradient3(V);

edge3 only supports "approxcanny" and "Sobel" — not "Canny", "Prewitt", "Roberts", or "log".

Contrast Adjustment

% imadjustn — N-D equivalent of imadjust
Vadj = imadjustn(V);                          % Auto stretch to [0 1] output
Vadj = imadjustn(V, stretchlim(V(:)));        % Percentile-based limits

% N-D histogram matching (align intensities to a reference volume)
Vmatched = imhistmatchn(V, Vref);
Vmatched = imhistmatchn(V, Vref, 128);        % Custom bin count

% Per-slice CLAHE (adapthisteq is 2-D only)
Vclahe = zeros(size(V), "like", V);
for k = 1:size(V, 3)
    Vclahe(:,:,k) = adapthisteq(V(:,:,k));
end

histeq works on 3-D (flattens histogram across entire volume), but imadjustn is generally preferred for volumetric contrast — it provides percentile-based stretching without redistributing the histogram.

When to prefer imhistmatchn over imadjustn: matching two volumes acquired under different conditions (different scanners, sessions, or exposures) before registration or comparison.

Thresholding

BW = imbinarize(V);                                % Otsu on 3-D grayscale
BW = imbinarize(V, "adaptive", Sensitivity=0.5);   % Adaptive on 3-D volume

% Or via adaptthresh (equivalent — build threshold volume explicitly)
T = adaptthresh(V, 0.5);
BW = imbinarize(V, T);

Morphological Cleanup (3-D)

se = strel("sphere", 2);
bw = imbinarize(V);                  % Otsu on volume
bw = imopen(bw, se);                 % Remove small protrusions
bw = imclose(bw, se);                % Fill small gaps
bw = imfill(bw, "holes");            % Fill fully-enclosed 3-D holes
bw = imclearborder(bw);              % Remove objects touching any volume face
bw = bwareaopen(bw, minVoxelCount);  % Remove small objects by voxel count

3-D-specific bwmorph3 operations — only these six: "branchpoints", "clean", "endpoints", "fill", "majority", "remove". It does not support "thin", "skel", "spur", "bridge" — use bwskel for 3-D skeletonization.

Filtering Objects by Properties — 3-D

R2026b+: bwvolumefilt and bwpropfilt3

Starting in R2026b, use these dedicated 3-D object filtering functions — they mirror the 2-D bwareafilt/bwpropfilt functions:

% Filter by volume (3-D equivalent of bwareafilt)
bwFiltered = bwvolumefilt(bw, [minVol maxVol]);           % Keep objects in volume range
bwFiltered = bwvolumefilt(bw, n);                          % Keep n largest objects (default)
bwFiltered = bwvolumefilt(bw, n, "smallest");              % Keep n smallest
bwFiltered = bwvolumefilt(bw, n, 6);                       % With explicit connectivity

% Filter by any regionprops3 property (3-D equivalent of bwpropfilt)
bwFiltered = bwpropfilt3(bw, "SurfaceArea", [100 Inf]);
bwFiltered = bwpropfilt3(bw, "Solidity", 3, "largest");
bwFiltered = bwpropfilt3(bw, I, "MeanIntensity", [50 200]);   % Needs grayscale I

% Both accept a connected component structure (from bwconncomp) as input:
cc = bwconncomp(bw, 6);
ccFiltered = bwpropfilt3(cc, "Volume", [1000 Inf]);
Pre-R2026b: regionprops3 + ismember fallback

In R2026a and earlier, bwareafilt and bwpropfilt are 2-D only. Use regionprops3 and ismember to manually filter by 3-D properties:

cc = bwconncomp(bw, 26);
props = regionprops3(cc, "Volume", "Centroid");

keep = props.Volume > minVolume;
L = labelmatrix(cc);
bwFiltered = ismember(L, find(keep));

% Multiple properties
keep = props.Volume > 100 & props.Volume < 10000;
bwFiltered = ismember(L, find(keep));

Note: bwareaopen(bw, minVoxels) works on 3-D for simple size thresholding (remove objects below a minimum), but cannot filter by range or by non-volume properties.

regionprops3 — 3-D Measurement

props = regionprops3(cc, "Volume", "Centroid", "PrincipalAxisLength", "SurfaceArea");

Key 3-D properties:

PropertyDescription
VolumeVoxel count (equivalent to 2-D Area)
CentroidCenter of mass [x, y, z] — x=col, y=row, z=slice. To index the volume: V(round(c(2)), round(c(1)), round(c(3)))
SurfaceAreaSurface area (Crofton formula, assumes unit voxel spacing)
PrincipalAxisLength[major, middle, minor] axis lengths
OrientationEuler angles [roll, pitch, yaw] in degrees (rotation about x-, y-, z-axes)
BoundingBox[x y z width height depth]
EquivDiameterDiameter of sphere with same volume
SolidityRatio of Volume to ConvexVolume
ConvexVolumeVolume of convex hull
ConvexHull / ConvexImageConvex hull vertices / binary convex hull image
ExtentRatio of Volume to BoundingBox volume
EigenValues / EigenVectorsPrincipal moments and directions
VoxelIdxListLinear indices of all voxels in region
VoxelList[x y z] subscript coordinates of all voxels
SubarrayIdxCell of subscript ranges for bounding box

Converting to physical units: Volume and SurfaceArea are in voxels/voxel² by default. Multiply manually: physicalVolume = props.Volume * prod(voxelSpacing). Note that SurfaceArea assumes isotropic voxels and cannot be corrected by a simple scalar for anisotropic spacing.

Intensity measurements (require grayscale volume):

props = regionprops3(cc, V, "MeanIntensity", "MaxIntensity", "MinIntensity", "VoxelValues", "WeightedCentroid");

3-D Segmentation

Beyond thresholding (imbinarize, adaptthresh) and k-means (imsegkmeans3, superpixels3), these methods handle more complex 3-D segmentation tasks:

Watershed — Separating Touching Objects
% Distance-transform based (for separating touching convex objects)
D = bwdist(~bw);
D = -D;
D = imhmin(D, 2);      % Suppress shallow minima to reduce over-segmentation
L = watershed(D);
bwSeparated = bw & (L > 0);  % Watershed lines are L==0

imhmin accepts an N-D connectivity argument — pass 6 or 18 to influence how minima are grouped in 3-D:

D = imhmin(D, 2, 6);   % Stricter minima connectivity in 3-D
Active Contours — activecontour

Level-set segmentation, works on 3-D volumes:

% Initial mask (rough estimate of region)
mask = false(size(V));
mask(r1:r2, c1:c2, s1:s2) = true;

% Chan-Vese (region-based, no edge needed) — default method
result = activecontour(V, mask, numIterations, "Chan-Vese");

% Edge-based
result = activecontour(V, mask, numIterations, "edge");
Seed-Based Region Growing — imsegfmm

Fast marching segmentation from seed points, works on 3-D:

W = graydiffweight(V, seedCol, seedRow, seedSlice);       % Intensity-difference weights
BW = imsegfmm(W, seedCol, seedRow, seedSlice, 0.01);     % Geodesic threshold

W = gradientweight(V);                                    % Gradient-based weights
BW = imsegfmm(W, seedCol, seedRow, seedSlice, 0.05);

3-D Geometric Transforms

Resizing — imresize3
Vs = imresize3(V, 0.5);                          % Uniform scale
Vs = imresize3(V, [200 200 100]);                % Explicit output size
Vs = imresize3(V, [200 200 100], "nearest");     % Preserve labels/masks

Interpolation methods: "nearest", "linear", "cubic" (default), "box", "triangle", "lanczos2", "lanczos3".

Categorical / label volumes: imresize3 accepts categorical arrays directly — use "nearest" to avoid invalid intermediate labels.

Rotation — imrotate3

Rotates about an arbitrary axis (unlike 2-D imrotate which always rotates about the image center in-plane):

Vr = imrotate3(V, 30, [0 0 1]);                          % 30° about Z
Vr = imrotate3(V, 45, [1 1 0], "linear", "crop");        % 45° about [1 1 0], cropped to input size
Vr = imrotate3(V, 15, [1 0 0], FillValues=NaN);          % NaN fill (FillValues must be numeric)

Accepts categorical arrays (labels/masks) — use "nearest" interpolation. Default bounding box is "loose" (output grows to contain the entire rotated volume). Use "crop" to keep the same size as the input, clipping regions that rotate outside the original bounds.

Cropping — imcrop3
Vc = imcrop3(V, [xmin ymin zmin width height depth]);
Oblique Slicing — obliqueslice

Extract a 2-D slice at an arbitrary angle from a volume (multiplanar reformation):

[B, x, y, z] = obliqueslice(V, [cx cy cz], [nx ny nz]);  % Center point + normal vector
B = obliqueslice(V, center, normal, Method="nearest");     % For label volumes

To reslice a full volume along an arbitrary plane, call obliqueslice in a loop with varying center points along the desired axis.

General warping — imwarp with 3-D transforms
% 3-D affine transform (12 DOF)
A = [1 0 0 tx; 0 1 0 ty; 0 0 1 tz; 0 0 0 1];   % Translation example
tform = affinetform3d(A);

% Rigid: Euler angles + translation
tform = rigidtform3d(eulerAngles, [tx ty tz]);

% Warp with spatial referencing (critical for anisotropic voxels)
Rin  = imref3d(size(V), voxSpacing(2), voxSpacing(1), voxSpacing(3));  % x,y,z
Vw   = imwarp(V, Rin, tform, OutputView=Rin);
Vw   = imwarp(V, Rin, tform, "nearest");  % For label/mask volumes

imref3d argument order gotcha: the constructor is imref3d(imageSize, xSpacing, ySpacing, zSpacing) where x=cols, y=rows, z=slices. Passing row/col spacing in the natural array order swaps X and Y and silently produces geometrically wrong results.

OutputView controls the output grid. Pass OutputView=Rin to keep the output in the same coordinate system as the input. To resample onto a different grid (e.g., matching a reference volume), create an imref3d for the target size and spacing and pass it as OutputView.

imwarp accepts categorical arrays — use "nearest" interpolation for labels.

Resampling to Isotropic Spacing

Many algorithms assume isotropic voxels. Resample anisotropic data first:

voxelSize = [0.5 0.5 2.5];        % [row col slice] mm
targetSpacing = min(voxelSize);   % Resample to finest dimension
scale = voxelSize / targetSpacing;
newSize = round(size(V) .* scale);
Viso = imresize3(V, newSize, "linear");

For label/mask volumes, use "nearest" interpolation to avoid creating invalid labels:

maskIso = imresize3(uint8(mask), newSize, "nearest") > 0;
% Or, for a categorical label volume:
labelsIso = imresize3(labelsCategorical, newSize, "nearest");

Visualization

% Volume rendering
volshow(V);

% With label overlay
volshow(V, OverlayData=labelVol);

% Orthogonal slice planes through the volume
volshow(V, RenderingStyle="SlicePlanes");

% Isosurface extraction + display (modern: viewer3d + Surface)
viewer = viewer3d;
[faces, verts] = isosurface(V, isovalue);
tri = triangulation(faces, verts);
images.ui.graphics.Surface(viewer, Data=tri);

% Slice browsing
sliceViewer(V);              % Single-direction slice browser with slider
orthosliceViewer(V);         % Three orthogonal views with linked crosshairs

% All slices as tiled gallery
montage(V);

Common Mistakes

MistakeWhy it's wrongCorrect approach
bwareafilt(bw3d, [min Inf])2-D only — errors on 3-Dbwvolumefilt (R2026b+) or regionprops3 + ismember
imadjust(V) on volumeDoesn't accept 3-Dimadjustn(V)
adapthisteq(V) on volume2-D grayscale onlyPer-slice loop or imadjustn/imhistmatchn
edge(V, "Canny") on volume2-D only, and edge3 doesn't offer "Canny"edge3(V, "approxcanny", …) or imgradient3
imgaussfilt(V, sigma)Runs but filters per-slice only — no Z smoothing, no warningimgaussfilt3(V, sigma)
strel("disk", r) for 3-D morphologyCreates 2-D SE — imerode/imdilate silently apply it per-slice (no Z coupling)strel("sphere", r)
Ignoring anisotropic voxel spacingSE is wrong physical size per axisUse strel("cuboid", …) scaled by voxel size, or resample to isotropic first
Default 26-connectivity merging objectsOver-connects in dense volumesExplicitly use 6-connectivity
imresize3(mask, newSize) for labelsDefault "cubic" creates non-binary/invalid valuesimresize3(mask, newSize, "nearest")
imref3d(sz, rowSpacing, colSpacing, sliceSpacing)Constructor is (sz, xSpacing, ySpacing, zSpacing) — x=cols, y=rowsimref3d(sz, colSpacing, rowSpacing, sliceSpacing)
fspecial3("box", …)No such type — use "average"fspecial3("average", hsize)
Passing Centroid [x y z] straight to V(…)Array indexing is [row col slice] = [y x z]V(round(c(2)), round(c(1)), round(c(3)))
regionprops(cc3d, "Solidity") on 3-DShape/moment properties (Solidity, Eccentricity, Orientation, etc.) warn and return empty on 3-DUse regionprops3 for full 3-D property set
edge3(V, "approxcanny") without thresholdThreshold is required (unlike 2-D edge which auto-computes)edge3(V, "approxcanny", thresh)
imsegkmeans(V, K) on a volumeTreats 3rd dim as channels — output is M×N, not M×N×Pimsegkmeans3(V, K)

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