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/filtering.md
Filtering
Diagnostic decision guide for choosing and applying image filters: smoothing, denoising, sharpening, and edge-preserving operations. Start from the noise model or artifact, not the function name.
Often loaded with:
preprocessing.md(contrast/normalization/type conversion),quality-assessment.md(measuring improvement),morphological-ops.md(post-filtering cleanup).Routes to other references: color-aware filtering →
color-processing.md; volumetric data →3d-volume-processing.md; motion-blur restoration / deconvolution →deblurring.md; texture characterization →texture-transforms.md.
Diagnose Before Filtering
Before selecting a filter, characterize the input:
Storage class and range — integer inputs clip negative/overflow results silently (see Output Class and Clipping)
Noise/artifact type — drives filter selection (see table below)
Downstream task — segmentation needs edge-preserving; display needs visual smoothing; measurement needs bias-free
Noise/Artifact → Filter Selection
| Observed artifact | Likely noise model | Recommended filter | Why not the alternatives |
|---|---|---|---|
| Uniform grain in flat regions | Additive Gaussian | imgaussfilt or imboxfilt | Median filtering is primarily intended for impulse noise and may unnecessarily alter non-impulsive detail |
| Constant-power additive white noise | Additive white Gaussian | wiener2 | Local adaptive filter; Gaussian blur ignores local variance |
| Bright/dark outlier pixels | Impulse (salt & pepper) | medfilt2 | Gaussian blur spreads outliers; Wiener assumes smooth spectrum |
| Grain over fine texture | Additive Gaussian over texture | imnlmfilt (inspect result — may smooth texture) | Better edge preservation than Gaussian/bilateral, but can still reduce fine detail |
| Noise with strong edges to preserve | Mixed, edge-sensitive task | imbilatfilt, imguidedfilter, imdiffusefilt | Gaussian blurs edges; median can round corners |
| Detail enhancement or smoothing | Not noise — want to separate scales | locallapfilt | Multi-scale decomposition; bilateral only operates at one scale |
Choosing a Smoothing Method
| Goal | Function | Key detail |
|---|---|---|
| General Gaussian blur | imgaussfilt(img, sigma) | Preferred over fspecial+imfilter — auto filter size, replicate padding by default |
| Box/mean filter | imboxfilt(img, filterSize) | Internally chooses convolution or integral-image filtering; simpler API than imfilter with average kernel |
| Remove salt & pepper noise | medfilt2(img, [m n]) | Grayscale only; nonlinear — preserves edges, removes impulse noise only |
| Local adaptive denoising | wiener2(img, [m n]) | Grayscale only; adapts to local variance. Best for constant-power additive white noise; optional scalar noise-power argument |
| Edge-preserving smoothing | imbilatfilt(img, degreeOfSmoothing, spatialSigma) | Smooths flat regions, preserves edges. Default degreeOfSmoothing is class-dependent: 650.25 for uint8, 0.01 for double [0,1] — always specify explicitly when the input class may vary |
| Anisotropic diffusion | imdiffusefilt(img) | Grayscale only; iterative — use imdiffuseest to estimate GradientThreshold and NumberOfIterations |
| Guided filtering | imguidedfilter(img) | Edge-aware, can use separate guidance image |
| Detail/scale manipulation | locallapfilt(img, sigma, alpha) | Does NOT accept double — use single or integer |
| Local contrast | localcontrast(img, edgeThreshold, amount) | Does NOT accept double — use single or integer |
Grayscale-Only Functions on RGB Images
medfilt2 and wiener2 error on RGB input. imdiffusefilt does not error but warns and treats the RGB image as a 3-D volume, diffusing across color channels — this is a different operation that produces plausible but incorrect results. Convert to a luminance-chrominance color space, filter the luminance channel only, and convert back — this avoids the color shifts that per-channel RGB filtering can introduce:
lab = rgb2lab(img);
lab(:,:,1) = medfilt2(lab(:,:,1), [5 5]);
img_filtered = lab2rgb(lab, OutputType="uint8");See color-processing.md for color space conversion details.
Non-Local Means Denoising — imnlmfilt
Exploits self-similarity to denoise — preserves strong edges but can smooth textured regions and reduce fine detail. Best when the image has repeated structure that the algorithm can match across patches:
[denoised, estimatedDoS] = imnlmfilt(img); % Auto parameters; returns estimated DegreeOfSmoothing
% Tune relative to the auto estimate — avoids hardcoding a class-dependent value
lighter = imnlmfilt(img, DegreeOfSmoothing=0.75*estimatedDoS); % Less smoothing
stronger = imnlmfilt(img, DegreeOfSmoothing=1.25*estimatedDoS); % More smoothingKey parameters:
DegreeOfSmoothing— auto value is based on estimated noise standard deviation, not a universally optimal setting. The appropriate value depends on the input class and data range — do not hardcode a single number across different images. Increase for stronger denoising; decrease to preserve more detailSearchWindowSize— runtime scales linearly with search-window size. Default 21 is a good balance; reduce for speed on large images
When to prefer over other denoisers:
Over
medfilt2: when noise is not impulse (salt & pepper)Over
imgaussfilt: when strong edges must be preservedOver
imbilatfilt: when image has repeated structure the algorithm can exploit for patch matching
Limitations: preserves strong edges but smooths texture — MathWorks examples show grass texture and fine detail being visibly reduced. Runtime scales linearly with search-window area; has a minimum image size requirement. Always inspect results on a representative region before committing, consider imgaussfilt or imbilatfilt as alternatives.
Boundary Padding — Choose Before Filtering
Different functions have different padding defaults. Always decide intentionally:
| Function | Default padding |
|---|---|
imfilter | Zero |
medfilt2 | Zero |
ordfilt2 | Zero |
imgaussfilt | Replicate |
medfilt3 | Symmetric |
modefilt | Symmetric |
Zero padding is not always wrong — the effect depends on the kernel (sign, sum), data values near the border, and output class. For smoothing kernels on typical images, zeros pull border values down, producing a visible dark band. For zero-sum kernels (derivatives) or data where zero is a plausible continuation, zero padding may be appropriate.
Padding options for imfilter:
| Option | Behavior | When to use |
|---|---|---|
"replicate" | Extends border pixels | Common choice for natural images |
"symmetric" | Mirrors image at borders | Smooth natural images, avoids discontinuities |
"circular" | Wraps around | Periodic signals (Fourier-consistent data) |
| Numeric value | Pads with that constant | When a specific background value is known (e.g., zero for masks) |
h = fspecial("gaussian", 11, 2);
filtered = imfilter(img, h); % Zero padding — may cause dark borders with smoothing kernels
filtered = imfilter(img, h, "replicate"); % Replicate padding — avoids border pull-downimgaussfilt uses replicate padding by default, which is one reason it is preferred over fspecial+imfilter for Gaussian smoothing.
Explicit Padding — padarray
For custom convolution, DL preprocessing, or frequency-domain filtering, pad explicitly:
padded = padarray(img, [m n], "replicate"); % Replicate m rows, n cols on each side
padded = padarray(img, [m n], "symmetric"); % Mirror at borders
padded = padarray(img, [m n], "circular"); % Wrap around (periodic)
padded = padarray(img, [m n], 0); % Zero-pad (any numeric scalar)
padded = padarray(img, [m n], "replicate", "pre"); % Pad only top/leftDefault direction is "both" (pad before and after). Also accepts "pre" (top/left only) or "post" (bottom/right only). The padsize argument is [rows cols].
Output Class and Clipping
imfilter returns the same class as the input and performs double-precision accumulation internally before rounding and clipping to the output range. This matters for derivative and high-pass kernels:
% Sobel edge kernel — response is signed
h = fspecial("sobel");
edges_clipped = imfilter(uint8(img), h); % WRONG — negatives clip to 0
edges = imfilter(im2single(img), h, "replicate"); % RIGHT — preserves sign
edges_display = uint8(edges * 128 + 128); % Offset only for visualizationRules:
Derivative/high-pass kernels produce negative values — filter in floating point, then offset only for display
Integer output rounds fractions and clips to [0, intmax] — decide whether clipping is wanted
When combining filter responses (e.g., gradient magnitude), compute in float first, then convert at the end
Correlation vs Convolution
imfilter uses correlation by default, not convolution. For symmetric kernels this makes no difference. For asymmetric kernels (directional derivatives, motion blur):
% Correlation (default) — kernel applied as-is
result = imfilter(img, h);
% Convolution — kernel flipped before applying
result = imfilter(img, h, "conv");Most
fspecialkernels are symmetric (correlation = convolution); the"motion"kernel is asymmetric — use"conv"if convolution semantics are neededCustom asymmetric kernels: decide whether you want correlation or convolution and specify explicitly
Even-sized kernels have an anchor at
floor((size(h)+1)/2)— for a 4-by-4 kernel this is (2,2)
Prefer Dedicated Functions Over fspecial + imfilter
| Old pattern | Modern replacement | Why |
|---|---|---|
fspecial('gaussian',n,s) + imfilter | imgaussfilt(img, sigma) | Auto padding, auto filter size |
fspecial('average',n) + imfilter | imboxfilt(img, n) | Simpler API, correct padding |
Manual unsharp: img + alpha*(img - blur) | imsharpen(img, Radius=r, Amount=a) | Handles clipping, threshold option |
fspecial('sobel') + imfilter for gradients | imgradient(img) / imgradientxy(img) | Returns magnitude+direction or Gx+Gy directly; supports Sobel, Prewitt, Roberts, central, intermediate methods |
fspecial is still useful for motion blur PSFs ("motion"), Laplacian ("laplacian"), and LoG ("log") kernels where no dedicated function exists.
Sharpening
sharpened = imsharpen(img, "Radius", 2, "Amount", 1.5, "Threshold", 0.1);Radius: size of blur for unsharp mask (default 1)Amount: strength of sharpening (default 0.8)Threshold: minimum contrast to sharpen — set this on noisy images to prevent noise amplification
Edge-Preserving Filters — When to Use Which
| Method | Tuning | Best for |
|---|---|---|
imbilatfilt | degreeOfSmoothing, spatialSigma | General edge-preserving smoothing. For RGB, convert to L*a*b* first for perceptually uniform color smoothing |
imguidedfilter | DegreeOfSmoothing, NeighborhoodSize | Edge-aware smoothing; guide can be the input itself, a separate image, or a different modality (see channel rules below) |
imdiffusefilt | NumberOfIterations, GradientThreshold | Iterative — more iterations = stronger smoothing; strong noise, need fine control |
locallapfilt | sigma, alpha, NumIntensityLevels | Multi-scale detail enhancement/smoothing |
Benchmark on representative data and hardware before choosing between these — relative performance depends on image size, parameter values, and platform.
imdiffuseest — Parameter Estimation for Anisotropic Diffusion
Use imdiffuseest to estimate parameters rather than guessing:
[gradThresh, numIter] = imdiffuseest(img);
filtered = imdiffusefilt(img, GradientThreshold=gradThresh, NumberOfIterations=numIter);imguidedfilter — Guidance Image Channel Rules
DegreeOfSmoothing is a variance threshold: neighborhoods with variance well below it get smoothed; those well above it are left mostly unchanged.
The guidance image G can differ from input A in number of channels:
Input A | Guidance G | Behavior |
|---|---|---|
| RGB | RGB | Each channel of A filtered using the corresponding channel of G |
| RGB | Grayscale | Each channel of A filtered using the same G |
| Grayscale | RGB | A filtered using combined color statistics of all three channels of G |
locallapfilt — Parameters and Type Restriction
locallapfilt and localcontrast do NOT accept double. Convert first:
% WRONG — errors on double input
result = locallapfilt(im2double(img), 0.4, 0.5);
% CORRECT — use single
result = locallapfilt(im2single(img), 0.4, 0.5);Parameters:
sigma— amplitude threshold separating "edges" from "details" (larger = more treated as detail)alpha— < 1 enhances details, > 1 smooths details (1 = no change). This is the opposite of what you might expectbeta— dynamic range compression/expansion (< 1 compresses, > 1 expands; default 1)NumIntensityLevels— speed/quality tradeoff; lower = faster but coarser approximationColorMode—"luminance"(default) processes only brightness;"separate"processes each channel
Frequency-Domain Filtering
Use frequency-domain approaches when the requirement is naturally spectral (e.g., remove a periodic pattern) or when the spatial kernel is very large:
When frequency-domain makes sense:
Removing periodic noise (banding, moiré) — design a notch filter in the frequency domain
Very large filter kernels — FFT-based filtering can be faster than spatial convolution
Custom frequency-selective operations not available as built-in spatial filters
Pitfalls:
Sharp ideal cutoffs (brick-wall filters) cause ringing — use smooth transitions or windowed designs
Direct FFT multiplication is circular convolution — pad the image to avoid wraparound artifacts
Preserve phase unless you specifically want phase modification
Frequency-sampling design can produce ripple; larger kernels reduce spatial extent but not height
For most denoising and smoothing tasks, spatial-domain filters are simpler and sufficient.
Designing 2-D FIR Filters
Three approaches, all producing a spatial-domain kernel for use with imfilter:
1. Frequency sampling (fsamp2) — specify the desired frequency response on a grid, get a kernel whose response passes through those points:
% Define desired response on an 11x11 frequency grid
Hd = zeros(11, 11);
Hd(4:8, 4:8) = 1; % Ideal low-pass in frequency domain
[f1, f2] = freqspace(11, "meshgrid"); % Normalized frequency grid [-1, 1]
% Design filter and inspect
h = fsamp2(Hd);
freqz2(h, [32 32]); % Visualize actual frequency response
% Apply
filtered = imfilter(img, h, "replicate");Sharp transitions in Hd produce ripple in the spatial kernel. Increasing the grid size reduces the spatial extent of ripple but not its amplitude.
2. Windowed design (fwind1) — applies a 1-D window to reduce ripple from frequency sampling:
h = fwind1(Hd, hamming(11)); % Circularly symmetric window via Huang's method
h = fwind1(Hd, win1, win2); % Separable window from two 1-D windows3. Frequency transformation (ftrans2) — transforms a 1-D FIR filter into a 2-D filter using the McClellan transform. Requires firpm from Signal Processing Toolbox for optimal 1-D design:
b = firpm(10, [0 0.4 0.6 1], [1 1 0 0]); % 1-D equiripple lowpass (Signal Processing Toolbox)
h = ftrans2(b); % 2-D filter via McClellan transform
filtered = imfilter(img, h, "replicate");Inspecting Filter Frequency Response
Use freqz2 to visualize the actual frequency response of any 2-D FIR kernel:
freqz2(h, [64 64]); % Mesh plot of magnitude response
[H, fx, fy] = freqz2(h, [64 64]); % Return response for custom analysisLocal Entropy Filtering — entropyfilt
entropyfilt computes local entropy in a sliding neighborhood — higher values indicate more complex local texture. Useful for segmenting textured regions from smooth backgrounds or as a feature for classification:
E = entropyfilt(img); % Default 9×9 neighborhood
E = entropyfilt(img, true(15)); % Custom 15×15 neighborhood
% Segment textured vs smooth regions
mask = imbinarize(E);Input must be grayscale (2-D). For RGB, convert to grayscale first.
Default neighborhood is 9×9 — increase for coarser texture discrimination, decrease for finer.
Output is
doubleregardless of input class — rescale or threshold as needed.For texture classification with multiple features, combine
entropyfiltwithstdfiltandrangefilt. See alsotexture-transforms.mdfor Gabor and GLCM alternatives.
Interpreting Filter Outputs — Not All Outputs Are Images
Some filtering operations produce feature representations, not enhanced images. The output is a measurement of local image structure, not a visually improved version of the input:
| Filter type | Output meaning | Typical use |
|---|---|---|
Gabor filter bank (imgaborfilt) | Returns magnitude (one output) or [mag, phase] (two outputs) — magnitude indicates match strength at that orientation/frequency | Texture classification, feature engineering |
| Steerable filters | Orientation-selective responses | Edge/ridge detection, orientation estimation |
Hessian-based vesselness (fibermetric) | Tubular structure likelihood | Vessel/fiber segmentation — preprocessing step, not a segmentor |
| LoG / Laplacian | Second-derivative response (signed) | Blob detection, zero-crossing edges |
| Filter-bank texture features | Multi-channel feature vectors per pixel | Segmentation, ML classification |
For Gabor filter response interpretation (magnitude, phase, normalization, real vs complex formulations), see the Gabor section in texture-transforms.md.
Choosing an Implementation
Prefer the simplest approach that covers the operation. Benchmark on representative data and hardware before making performance claims:
Dedicated function —
imgaussfilt,medfilt2,imboxfilt,imsharpen, etc. (fewest gotchas, internally optimized)imfilterwith a designed kernel — for custom linear filters (specify padding explicitly)ordfilt2— for order-statistic / rank filters (generalized median)Vectorized /
blockproc— for non-overlapping tiled operationsnlfilter— arbitrary sliding-window function (per-pixel function call overhead — use only when no better option exists)
Neighborhood Processing
For custom sliding-window operations not covered by built-in filters:
% ordfilt2 — order-statistic filter (fast generalized median)
result = ordfilt2(img, 5, ones(3,3)); % 5th smallest in 3x3 = median
% blockproc — non-overlapping blocks (faster, for tiled operations)
fun = @(block_struct) std2(block_struct.data) * ones(size(block_struct.data));
result = blockproc(img, [32 32], fun);
% roifilt2 — filter only within a mask, leave the rest unchanged (grayscale)
% vertices of the mask polygon.
c = [222 272 300 270 221 194];
r = [21 21 75 121 121 75];
mask = roipoly(img,c,r);
h = fspecial("gaussian", 7, 2);
result = roifilt2(h, img, mask); % Linear filter inside mask
result = roifilt2(img, mask, @(x) medfilt2(x)); % Custom function inside mask
% integralImage + integralBoxFilter — constant-time subregion summation
intImg = integralImage(img); % Zero-padded on top and left
smoothed = integralBoxFilter(intImg, 11); % Box filter via integral image
% nlfilter — arbitrary function on sliding neighborhood (slow, last resort)
result = nlfilter(img, [3 3], @(x) max(x(:)));Common Mistakes
| Mistake | Why it's wrong | Correct approach |
|---|---|---|
| Choosing filter by name, not noise model | Wrong filter for the artifact | Diagnose the noise type first, then select |
imfilter without considering padding | Zero default can cause border artifacts with smoothing kernels | Choose padding intentionally — "replicate", "symmetric", "circular", or zero if appropriate |
locallapfilt alpha > 1 to enhance detail | Alpha > 1 smooths details | Use alpha < 1 to enhance details |
locallapfilt on double | Type error — only single/integer | locallapfilt(im2single(img), ...) |
| High-pass kernel on uint8 input | Negatives clip to 0 | Use floating-point input for derivative kernels |
Assuming imfilter does convolution | Default is correlation | Pass "conv" if convolution is needed |
fspecial('gaussian') + imfilter | Slower, wrong default padding | Use imgaussfilt(img, sigma) |
| Sharpening noisy images | Amplifies noise | Set "Threshold" in imsharpen |
imgaussfilt on data with Inf/NaN | Undefined behavior in frequency domain (the default "auto" mode may choose it) | Set FilterDomain="spatial" to contain Inf/NaN propagation |
Expecting imnlmfilt to preserve all texture | Can smooth textured regions | Verify on a representative patch; tune DegreeOfSmoothing |
nlfilter for everything custom | Extremely slow | Try ordfilt2, blockproc, or vectorized code first |
| Displaying feature-map output as an enhanced image | Feature responses are measurements, not improved images | Use for classification/segmentation; see texture-transforms.md for Gabor specifics |
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