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://mp-staging.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/morphological-ops.md
Morphological Operations
Decision guidance and non-obvious patterns for shape-based image processing. Covers structuring elements, binary cleanup, grayscale morphology, and reconstruction.
Often loaded with:
segmentation-automated.md(creating masks to clean up),analysis-measurement.md(measuring objects after cleanup).
Before You Start — Class and Polarity
Before choosing a function, inspect both class and foreground polarity:
Logical mask → binary morphology (
imerode,imdilate,imopen,imclose,bwareaopen, etc.)Numeric image (uint8, single, etc.) → grayscale morphology (
imtophat,imbothat,imopen,imclose)Binary functions treat nonzero pixels as foreground, but skeletonization expects intended objects to be logical
true— complement dark-on-light images firstDo not pass an RGB or grayscale array to a "mask cleanup" recipe without deliberately creating and validating the mask
A 2-D SE applied to a multi-channel image (e.g., RGB) operates on each channel independently
Structuring Elements
| Shape | Constructor | Typical use |
|---|---|---|
| Disk | strel("disk", radius) | General-purpose, isotropic |
| Square | strel("square", width) | Fast, axis-aligned |
| Rectangle | strel("rectangle", [h w]) | Directional (non-square) |
| Line | strel("line", len, angle) | Directional filtering (e.g., detecting scratches) |
| Diamond | strel("diamond", radius) | 4-connected equivalent of disk |
| Non-flat (height) | offsetstrel("ball", radius, height) | Grayscale morphology with a height profile |
Non-flat structuring elements (offsetstrel) have a height value at each pixel, not just on/off membership. Use them for grayscale morphological smoothing, surface fitting, or envelope extraction where the SE shape should follow a curved profile (e.g., ball, arbitrary height matrix). offsetstrel accepts "ball" and "arbitrary" geometries:
se = offsetstrel("ball", 5, 3); % Ball with radius 5, height 3
se = offsetstrel("arbitrary", heights); % Custom height matrix
smoothed = imclose(img, se); % Grayscale closing with curved SEimdilate and imerode automatically exploit SE decomposition and binary packing — do not hand-implement packing to optimize ordinary morphology. Disk and ball SEs use an approximation that is faster but can change the exact discrete footprint; other documented geometric decompositions (line, rectangle, square, diamond) are exact. Inspect se.Neighborhood to see the pixel footprint, or decompose(se) to see the decomposed sequence.
Choosing a Structuring Element — Decision Workflow
SE choice has three dimensions: target feature, scale, and orientation. A wrong choice can leave artifacts (square SE rounds corners; disk SE rounds right angles) or destroy structure (oversized SE erases foreground during opening, connects unrelated objects during closing).
Name the feature — protrusion, dark notch, gap, bridge, isolated object, line, or local peak
Measure it in pixels — zoom/crop in Image Viewer or use the distance measurement tool to count pixels across the target feature
Choose geometry:
Disk — approximately isotropic features (round objects, general cleanup)
Line — orientation-selective features (scratches, vessels, cracks at a known angle)
Rectangle/square — axis-aligned structure
Arbitrary neighborhood — only when geometry demands a custom shape
Start slightly below the measured scale, inspect the result, then increase gradually — an oversized SE is destructive
Visualize the SE before processing:
se.Neighborhoodshows the actual pixel neighborhoodRecheck object count, topology, and downstream measurements after applying
Caveats:
strel("line", len, angle)has approximate length on the discrete pixel grid — the actual neighborhood may not match the requested length exactlyArbitrary neighborhoods use
floor((size(nhood)+1)/2)as the origin — for even-sized neighborhoods, inspect the origin rather than assuming perfect symmetry
Border Padding in Morphological Operations
Dilation and erosion use different virtual padding values for pixels beyond the image boundary:
Dilation pads with the datatype minimum (0 for binary/uint8)
Erosion pads with the datatype maximum (1 for binary, 255 for uint8)
This means imclose(A, se) and a manual imerode(imdilate(A, se), se) can differ near image borders — the compound operation has different intermediate boundary conditions than the fused function. If a result looks wrong only near edges, check the padding and output-shape ("same" vs "full") assumptions before concluding the morphology is incorrect.
Troubleshooting Morphological Results
| Symptom | Likely cause | Adjustment |
|---|---|---|
| Opening returns all zeros | SE cannot fit inside retained foreground | Reduce SE or choose a better-aligned shape |
| Closing merges separate objects | SE spans the inter-object gap | Reduce SE or use an oriented SE |
| Square corners/flat edges appear | SE geometry is imprinting on the mask | Try a disk/diamond or an oriented line |
| Result differs only near image edges | Dilation/erosion border padding asymmetry | Check padding values and output-shape option; use imclearborder if border objects are unreliable |
| Goal is only enclosed-hole filling | Closing is the wrong abstraction | Use imfill; route detailed recipes to segmentation-automated.md |
Binary Cleanup — Choosing the Right Tool
This is where agents most often pick verbose manual approaches when a one-liner exists:
| Goal | Function | Example |
|---|---|---|
| Remove objects < N pixels | bwareaopen(bw, N) | bwareaopen(bw, 50) |
| Keep objects in size range | bwareafilt(bw, [lo hi]) | bwareafilt(bw, [100 5000]) |
| Keep N largest objects | bwareafilt(bw, N) | bwareafilt(bw, 3) |
| Filter by any property | bwpropfilt(bw, prop, range) | bwpropfilt(bw, "Eccentricity", [0 0.5]) |
| Fill enclosed holes | imfill(bw, "holes") | Only fills fully-enclosed regions |
| Remove border-touching objects | imclearborder(bw) | Removes objects touching any image edge |
| Remove objects touching specific borders | imclearborder(bw, Borders=["top" "left"]) | R2023b: select which borders to clear |
| Keep only border-touching objects | imkeepborder(bw) | R2023b: opposite of imclearborder |
| Smooth object boundaries | imopen(bw, se) then imclose | Opening removes protrusions, closing fills notches |
| Fill only small holes | See pattern below | imfill fills ALL holes; use area filtering to keep large holes |
| Group nearby objects | bwdist(bw) <= d then label | Clusters objects within distance d of each other |
Pattern: Fill Only Small Holes (Not All)
imfill(bw, "holes") fills every hole. To fill only holes below a size threshold:
filled = imfill(bw, "holes"); % Fill all holes
holes = filled & ~bw; % Extract just the hole pixels
bigholes = bwareaopen(holes, 500); % Keep only large holes (>= 500 px)
bw_clean = bw | (holes & ~bigholes); % Fill small holes, preserve large onesThis is far cleaner than manually iterating over holes with regionprops.
Pattern: Group Nearby Objects (Almost-Connected Components)
To label clusters of objects that are close together (within distance d) but not touching:
bw_expanded = bwdist(bw) <= d/2; % All pixels within d of any foreground
L = labelmatrix(bwconncomp(bw_expanded)); % Label the merged clusters
L(~bw) = 0; % Mask back to original objects onlyEach original object now carries the label of its cluster. Objects within d pixels of each other share a label. This uses the distance transform for true isotropic (circular) expansion — more accurate than imdilate with an approximate disk strel for large distances.
bwpropfilt — Filter by Any Region Property
This is extremely useful and agents almost never use it:
% Keep only round objects (low eccentricity)
round = bwpropfilt(bw, "Eccentricity", [0 0.5]);
% Keep objects with area > 500
large = bwpropfilt(bw, "Area", [500 Inf]);
% Keep objects with specific solidity
solid = bwpropfilt(bw, "Solidity", [0.8 1.0]);Accepts a documented subset of regionprops properties — check the bwpropfilt reference page for the supported list.
Grayscale Morphology — Background Correction
The classic pattern for correcting uneven illumination. For smooth, gradual illumination gradients (vignetting, microscopy shading), prefer imflatfield(img, sigma) — one function, one parameter. See preprocessing.md. Use morphological correction below when the background variation is shape-dependent or imflatfield does not model the background well.
Pattern: Top-Hat for Background Removal
se = strel("disk", 15); % Radius > largest foreground object
corrected = imtophat(img, se); % Removes slowly-varying background in one stepimtophat(img, se) = img - imopen(img, se). It returns bright structures that do not survive the opening — i.e., regions where the SE cannot fit inside the foreground, based on shape and orientation, not merely size.
Pattern: Bottom-Hat for Dark Feature Extraction
se = strel("disk", 15);
dark_features = imbothat(img, se); % Extracts dark structures smaller than the SEimbothat(img, se) = imclose(img, se) - img. The dual of imtophat — extracts dark features on a bright background. Combine both for contrast enhancement: enhanced = img + imtophat(img, se) - imbothat(img, se).
Pattern: Opening-by-Reconstruction (Better Shape Preservation)
Standard imopen can truncate object peaks. Reconstruction preserves full object shape:
se = strel("disk", 15);
marker = imerode(img, se); % Create marker below the signal
background = imreconstruct(marker, img); % Reconstruct: grows marker up to mask
corrected = img - background;Key rule for imreconstruct: marker must be ≤ mask pointwise. If marker > mask at any pixel, imreconstruct silently clips the marker down to the mask level — no error or warning. Swapping the arguments (passing mask as marker and vice versa) produces meaningless results with no indication that anything is wrong. Always verify: imreconstruct(marker, mask) where marker ≤ mask.
Pattern: Double Thresholding (Hysteresis)
When a single threshold either includes too many pixels (too low) or misses connected regions (too high), use two thresholds + reconstruction:
mask_high = img > T_high; % Conservative: only strong features (marker)
mask_low = img > T_low; % Liberal: includes weak connected regions (mask)
result = imreconstruct(mask_high, mask_low); % Keep low-threshold regions connected to highThis keeps all pixels above T_low that are connected to any pixel above T_high. Isolated weak pixels (noise) are excluded. This is the same logic Canny edge detection uses internally for edge linking.
Pattern: Keep Whole Objects Touching a Region
To select complete objects that overlap with a mask (ROI, border, etc.) without truncating them:
seeds = bw & roi_mask; % Partial object pixels inside the ROI
whole_objects = imreconstruct(seeds, bw); % Restore full objects from seedsThis is essential when you need to keep entire objects that partially overlap a polygon, border region, or distance buffer — logical AND alone truncates objects at the boundary.
Morphological Minima/Maxima Transforms
For imhmin, imhmax, imextendedmin, imextendedmax, imregionalmin, imregionalmax — used for peak/valley detection and watershed preparation — see the Peak / Bright Spot Detection section in analysis-measurement.md.
Skeletonization
Workflow — In This Order
Unclean masks directly create loops and spurs in the skeleton. Follow this sequence:
Establish foreground polarity — objects must be logical
true. Complement dark-on-light images (~bw)Clean the mask — remove irrelevant components (
bwareaopen, orbwareafilt(bw, 1)for the largest) and fill unintended holes (imfill(bw, "holes")). Holes become loops; fragments become branches. Detailed component filtering belongs insegmentation-automated.md, but these preconditions belong hereSkeletonize — choose a function (see below)
Compare
bwskelandbwmorphwhen centerline placement matters (see below)Prune — only after understanding branch-length units and connectivity (see below)
Validate topology — check endpoints (
bwmorph(skel, "endpoints")), branchpoints (bwmorph(skel, "branchpoints")), and connectivity before measuring length
Choosing a Skeletonization Function
skel = bwmorph(bw, "skel", Inf); % More accurate/symmetric skeletons for 2-D
skel = bwskel(bw); % Supports MinBranchLength pruning
skel = bwskel(bw, "MinBranchLength", 10); % Prune short branches — not available with bwmorphFor 2-D images, bwmorph(bw, "skel", Inf) may produce more accurate and symmetric skeletons than bwskel. However, bwskel supports MinBranchLength for branch pruning — if pruning is needed, use bwskel; if skeleton accuracy matters more, compare both on representative data. bwskel 2-D behavior was improved in R2026a (no longer internally pads to 3-D), but bwmorph skeleton remains the recommended choice for 2-D accuracy.
Branch Pruning
MinBranchLength is measured in pixels using fixed connectivity (pixel-to-pixel hops along the skeleton), not Euclidean path length. A diagonal branch of 10 pixels covers ~14 pixels of Euclidean distance but counts as 10 for pruning. Account for this when setting the threshold.
For bwmorph-based skeletons (which lack MinBranchLength), prune with iterated spur removal:
skel = bwmorph(skel, "spur", n); % Remove n pixels from branch endpointsDisplay Caveat
A one-pixel-wide skeleton may appear discontinuous when the image is downsampled for display — zoom to 100% to verify continuity.
Hit-Miss Transform — bwhitmiss
Exact local binary-pattern matching. Use when you need to find pixels whose neighborhood matches a specific foreground/background configuration — replaces verbose combinations of indexing, convolution, and logical tests:
% Find top-left corner pixels: foreground pixel with background above and to the left
interval = [ -1 -1 -1;
-1 1 0;
-1 0 0];
% 1 = required foreground, -1 = required background, 0 = don't care
corners = bwhitmiss(bw, interval);Equivalent to erosion of the foreground by the 1 positions combined with erosion of the complement by the -1 positions. The two sets of positions must not overlap.
Other uses: finding endpoints, isolated pixels, T-junctions, or any specific local topology without writing custom neighborhood logic.
bwmorph Operations Reference
| Operation | Effect |
|---|---|
"thin" | Thin to 1-pixel width (use Inf iterations) |
"skel" | Skeletonize (see above section for nuance) |
"remove" | Extract perimeter (interior pixels removed) |
"endpoints" | Find endpoints of skeleton branches |
"branchpoints" | Find branch junction points |
"spur" | Remove spur pixels (short branches) |
"bridge" | Connect broken segments (fills gaps) |
"fill" | Fill isolated interior pixels |
"clean" | Remove isolated pixels (salt noise) |
"majority" | Set pixel to 1 if ≥5 of 9 pixels in 3×3 neighborhood are 1; otherwise set to 0 |
Connectivity Matters
Many binary functions default to 8-connectivity in 2-D. This affects object counting:
cc4 = bwconncomp(bw, 4); % 4-connected: stricter (more objects)
cc8 = bwconncomp(bw, 8); % 8-connected: diagonal touching counts (fewer objects)bwareaopen also accepts a connectivity argument (default 8 for 2-D, 26 for 3-D). bwareafilt and bwpropfilt are 2-D only and accept 4 or 8 connectivity. Match connectivity across pipeline steps — using 4-connectivity in bwconncomp but 8-connectivity in bwareaopen gives inconsistent object definitions.
Rule of thumb: Use 4-connectivity for foreground objects, 8-connectivity for holes/background. This follows the Jordan curve convention (ensures objects don't leak through diagonal gaps).
Common Mistakes
| Mistake | Why it's wrong | Correct approach |
|---|---|---|
| Manual loop to remove small objects | Verbose, slow | bwareaopen(bw, minSize) — one line |
bwskel without comparing to bwmorph skeleton | bwmorph(bw, "skel", Inf) may be more accurate for 2-D | Compare both; use bwskel when MinBranchLength pruning is needed |
| Opening then closing for smoothing | Order matters — results differ | Opening first (removes noise), then closing (fills gaps) |
| Ignoring border objects | imfill and regionprops include them | imclearborder(bw) to remove before analysis |
| Manual extraction of border objects | Verbose: bw & ~imclearborder(bw) | imkeepborder(bw) (R2023b) — direct one-liner |
imclearborder removes all borders unwanted | Sometimes only specific edges matter | imclearborder(bw, Borders=["top" "bottom"]) (R2023b) |
Large strel("disk") for grayscale morphology | Can be slow | Consider imtophat (shortcut); decomposition is automatic — do not hand-pack |
| Skeleton has loops or many spurs | Holes and small components in the input mask | Fill holes and remove fragments before skeletonizing |
| Passing a grayscale/RGB image to binary cleanup | Numeric input triggers grayscale morphology, not binary | Create and validate a logical mask first |
Expecting imclose to only fill holes | Closing alters boundaries and can merge objects | Use imfill(bw, "holes") for enclosed-hole filling |
Using parfor with bwskel | Internal multithreading can interact poorly with worker configuration | Test with single-threaded workers or run outside parfor |
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.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download matlab-process-images.zip