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://mp-staging.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/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:

  1. Storage class and range — integer inputs clip negative/overflow results silently (see Output Class and Clipping)

  2. Noise/artifact type — drives filter selection (see table below)

  3. Downstream task — segmentation needs edge-preserving; display needs visual smoothing; measurement needs bias-free

Noise/Artifact → Filter Selection

Observed artifactLikely noise modelRecommended filterWhy not the alternatives
Uniform grain in flat regionsAdditive Gaussianimgaussfilt or imboxfiltMedian filtering is primarily intended for impulse noise and may unnecessarily alter non-impulsive detail
Constant-power additive white noiseAdditive white Gaussianwiener2Local adaptive filter; Gaussian blur ignores local variance
Bright/dark outlier pixelsImpulse (salt & pepper)medfilt2Gaussian blur spreads outliers; Wiener assumes smooth spectrum
Grain over fine textureAdditive Gaussian over textureimnlmfilt (inspect result — may smooth texture)Better edge preservation than Gaussian/bilateral, but can still reduce fine detail
Noise with strong edges to preserveMixed, edge-sensitive taskimbilatfilt, imguidedfilter, imdiffusefiltGaussian blurs edges; median can round corners
Detail enhancement or smoothingNot noise — want to separate scaleslocallapfiltMulti-scale decomposition; bilateral only operates at one scale

Choosing a Smoothing Method

GoalFunctionKey detail
General Gaussian blurimgaussfilt(img, sigma)Preferred over fspecial+imfilter — auto filter size, replicate padding by default
Box/mean filterimboxfilt(img, filterSize)Internally chooses convolution or integral-image filtering; simpler API than imfilter with average kernel
Remove salt & pepper noisemedfilt2(img, [m n])Grayscale only; nonlinear — preserves edges, removes impulse noise only
Local adaptive denoisingwiener2(img, [m n])Grayscale only; adapts to local variance. Best for constant-power additive white noise; optional scalar noise-power argument
Edge-preserving smoothingimbilatfilt(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 diffusionimdiffusefilt(img)Grayscale only; iterative — use imdiffuseest to estimate GradientThreshold and NumberOfIterations
Guided filteringimguidedfilter(img)Edge-aware, can use separate guidance image
Detail/scale manipulationlocallapfilt(img, sigma, alpha)Does NOT accept double — use single or integer
Local contrastlocalcontrast(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 smoothing

Key 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 detail

  • SearchWindowSize — 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 preserved

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

FunctionDefault padding
imfilterZero
medfilt2Zero
ordfilt2Zero
imgaussfiltReplicate
medfilt3Symmetric
modefiltSymmetric

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:

OptionBehaviorWhen to use
"replicate"Extends border pixelsCommon choice for natural images
"symmetric"Mirrors image at bordersSmooth natural images, avoids discontinuities
"circular"Wraps aroundPeriodic signals (Fourier-consistent data)
Numeric valuePads with that constantWhen 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-down

imgaussfilt 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/left

Default 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 visualization

Rules:

  • 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 fspecial kernels are symmetric (correlation = convolution); the "motion" kernel is asymmetric — use "conv" if convolution semantics are needed

  • Custom 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 patternModern replacementWhy
fspecial('gaussian',n,s) + imfilterimgaussfilt(img, sigma)Auto padding, auto filter size
fspecial('average',n) + imfilterimboxfilt(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 gradientsimgradient(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

MethodTuningBest for
imbilatfiltdegreeOfSmoothing, spatialSigmaGeneral edge-preserving smoothing. For RGB, convert to L*a*b* first for perceptually uniform color smoothing
imguidedfilterDegreeOfSmoothing, NeighborhoodSizeEdge-aware smoothing; guide can be the input itself, a separate image, or a different modality (see channel rules below)
imdiffusefiltNumberOfIterations, GradientThresholdIterative — more iterations = stronger smoothing; strong noise, need fine control
locallapfiltsigma, alpha, NumIntensityLevelsMulti-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 AGuidance GBehavior
RGBRGBEach channel of A filtered using the corresponding channel of G
RGBGrayscaleEach channel of A filtered using the same G
GrayscaleRGBA 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 expect

  • beta — dynamic range compression/expansion (< 1 compresses, > 1 expands; default 1)

  • NumIntensityLevels — speed/quality tradeoff; lower = faster but coarser approximation

  • ColorMode — "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 windows

3. 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 analysis

Local 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 double regardless of input class — rescale or threshold as needed.

  • For texture classification with multiple features, combine entropyfilt with stdfilt and rangefilt. See also texture-transforms.md for 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 typeOutput meaningTypical use
Gabor filter bank (imgaborfilt)Returns magnitude (one output) or [mag, phase] (two outputs) — magnitude indicates match strength at that orientation/frequencyTexture classification, feature engineering
Steerable filtersOrientation-selective responsesEdge/ridge detection, orientation estimation
Hessian-based vesselness (fibermetric)Tubular structure likelihoodVessel/fiber segmentation — preprocessing step, not a segmentor
LoG / LaplacianSecond-derivative response (signed)Blob detection, zero-crossing edges
Filter-bank texture featuresMulti-channel feature vectors per pixelSegmentation, 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:

  1. Dedicated function — imgaussfilt, medfilt2, imboxfilt, imsharpen, etc. (fewest gotchas, internally optimized)

  2. imfilter with a designed kernel — for custom linear filters (specify padding explicitly)

  3. ordfilt2 — for order-statistic / rank filters (generalized median)

  4. Vectorized / blockproc — for non-overlapping tiled operations

  5. nlfilter — 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

MistakeWhy it's wrongCorrect approach
Choosing filter by name, not noise modelWrong filter for the artifactDiagnose the noise type first, then select
imfilter without considering paddingZero default can cause border artifacts with smoothing kernelsChoose padding intentionally — "replicate", "symmetric", "circular", or zero if appropriate
locallapfilt alpha > 1 to enhance detailAlpha > 1 smooths detailsUse alpha < 1 to enhance details
locallapfilt on doubleType error — only single/integerlocallapfilt(im2single(img), ...)
High-pass kernel on uint8 inputNegatives clip to 0Use floating-point input for derivative kernels
Assuming imfilter does convolutionDefault is correlationPass "conv" if convolution is needed
fspecial('gaussian') + imfilterSlower, wrong default paddingUse imgaussfilt(img, sigma)
Sharpening noisy imagesAmplifies noiseSet "Threshold" in imsharpen
imgaussfilt on data with Inf/NaNUndefined behavior in frequency domain (the default "auto" mode may choose it)Set FilterDomain="spatial" to contain Inf/NaN propagation
Expecting imnlmfilt to preserve all textureCan smooth textured regionsVerify on a representative patch; tune DegreeOfSmoothing
nlfilter for everything customExtremely slowTry ordfilt2, blockproc, or vectorized code first
Displaying feature-map output as an enhanced imageFeature responses are measurements, not improved imagesUse 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.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download matlab-process-images.zip