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

Matlab Process Images

MathWorksOfficialCreated by MathWorks

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

From the author

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

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill serves as the primary entry point for MATLAB tasks involving images, scans, frames, and 3-D volumes. It provides core conventions for image data types, coordinate systems, and display practices, while routing users to specific references for tasks such as I/O, filtering, segmentation, and measurement. It ensures consistent use of Image Processing Toolbox functions and helps users navigate common pitfalls in image analysis workflows.

What it does

  • Provides standardized conventions for image data types and coordinate systems.
  • Routes users to specialized references for image I/O, filtering, and transformation tasks.
  • Defines best practices for displaying images using the imageshow function.
  • Offers guidance on handling 3-D volumetric data and large-scale images.
  • Assists with selecting appropriate functions for segmentation and object measurement.
  • Provides troubleshooting patterns for common image processing errors.

When to use it

  • When performing image processing tasks in MATLAB, such as filtering, enhancing, or segmenting.
  • When working with image formats like TIFF, PNG, JPEG, DICOM, or NIfTI.
  • When needing to understand MATLAB-specific coordinate conventions for image data.
  • When determining the correct toolbox function for a specific image analysis goal.
  • When troubleshooting syntax or type-related errors in image processing scripts.

Advantages

  • Ensures consistent coding patterns across different image processing tasks.
  • Reduces errors by providing clear guidance on coordinate and data type conventions.
  • Simplifies the selection of appropriate tools for complex workflows like 3-D volume processing.
  • Promotes the use of modern display functions like imageshow over legacy alternatives.
  • Provides a structured approach to identifying the correct documentation for specific functions.

Usage examples

“How do I read a DICOM file and display it in MATLAB?”
The agent will guide you to use the medical-data-io reference for reading the file and the imageshow function for display, following the core conventions.
“I need to count the number of objects in a binary image.”
The agent will provide the standard analysis pipeline using bwconncomp and regionprops, ensuring the input is correctly formatted as logical.
“How do I perform 3-D filtering on a volume?”
The agent will direct you to the 3-D volume processing reference to select the appropriate 3-D specific function, such as imgaussfilt3.
“Why is my regionprops measurement returning only one object?”
The agent will explain that the input must be a logical array and provide the code to convert your numeric array to logical.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/matlab/matlab-process-images/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip matlab-process-images.zip -d .agents/skills

Documentation by MathWorks

Image Processing

Process, analyze, and transform images using MATLAB Image Processing Toolbox (IPT). This skill routes you to the correct reference for your task and provides core conventions that apply across all IPT work.

When to Use

Loaded for general-purpose IPT work: file and batch I/O, filtering, restoration, morphology, segmentation, measurement, geometric transforms, color, texture, quality metrics, deep learning on images, and image apps. Non-medical microscopy — cell and particle counting on plain IPT — is in scope.

Hand off (and co-load) instead of answering alone: see the handoff table under ## Routing.

When NOT to Use

  • Training a network with no image-specific preprocessing — use Deep Learning Toolbox directly

  • Simulink or Stateflow video blocks — use Simulink directly

  • C/C++ code generation, MEX, GPU acceleration and deployment — use MATLAB Coder / GPU Coder directly

  • Point clouds, 3-D reconstruction, and video stabilization — use Computer Vision Toolbox directly

  • General MATLAB questions unrelated to images

  • Looking at an image yourself (e.g., "look at this screenshot") when no MATLAB work is requested — use your own vision instead

Core Conventions

Image Data Types
TypeRangeWhen to use
uint80–255Display, file I/O, memory-efficient storage
uint160–65535High dynamic range sensors, medical. Camera RAW is n-bit in a uint16 container — rescale with rawinfo BlackLevel/WhiteLevel, not 65535
single / double0.0–1.0Arithmetic, filtering, computation
logical0 or 1Binary masks, segmentation results

Most IPT functions accept integer types directly — do not convert to floating-point unless required.

Default Coordinate Conventions
  • MATLAB images are (row, col) — row is Y (down), column is X (right)

  • size(img) returns [height, width, channels]

  • Spatial functions use (x, y) order for coordinates (e.g., imref2d, regionprops centroids)

  • Pixel centers are at integer intrinsic coordinates; in default world referencing, pixel (1,1) center is at world (1.0, 1.0) and the image edge starts at 0.5

  • imref2d and imref3d can specify non-default spatial referencing to place images into world coordinate systems. By default they use the unit-spaced, integer-pixel-centered coordinate system described here, e.g. Rout = imref2d(imageSize). Functions that do not accept spatial referencing objects assume this intrinsic coordinate system for any operation requiring spatial referencing.

Multichannel Images
  • Grayscale: M×N or M×N×1

  • RGB: M×N×3

  • With alpha: read using [img, ~, alpha] = imread(...) (alpha is the third output)

  • Convert: rgb2gray, im2gray (preferred, handles more input types)

Display Functions — use imageshow, not imshow

Always use imageshow instead of imshow in all generated code — scripts, apps, examples, and quick previews. The signatures are compatible for common cases: replace imshow(...) with imageshow(...). imageshow (R2024b+) handles sub-bit-depth containers (e.g., 12-bit in uint16) via DisplayRangeMode, supports OverlayData for label/mask overlays, and works with viewer2d. imshow lacks all of these capabilities and should not appear in new code.

Title convention: imageshow creates a viewer2d, not an axes — gca does not return it. To add a title, get the viewer from the Image object's parent:

obj = imageshow(im);
viewer = obj.Parent;
title(viewer, "Title Text");

Do not use title("text") or title(gca, "text") after imageshow — these silently fail or create a stray axes title.

Code Execution

Execute code blocks via evaluate_matlab_code before presenting them to the user. If it errors, fix and re-run. This catches type mismatches, wrong argument orders, and nonexistent functions before the user sees them. If execution requires user data or toolboxes not available in the current session, present the code with a note that it should be run with the user's own data — do not loop trying to synthesize stand-in data.

Error Recovery

If code throws an error after execution, load the matlab-read-documentation skill and look up the function's doc page to verify syntax, required arguments, and supported input types before retrying.

When to Ask the User

Ask for clarification before proceeding when:

  • The image type/format is ambiguous and affects the processing approach

  • Multiple valid approaches exist with different tradeoffs (speed vs quality, lossy vs lossless)

  • The task requires choosing parameters that depend on domain knowledge (e.g., object size thresholds, noise characteristics)

  • The user's MATLAB release is unknown and the recommended function may not be available

Routing

Match your task in the tables below. Check the handoff table first. If the task belongs to another skill, load that skill in addition to this one — the Core Conventions above (data types, coordinate order, code execution) apply to all image data. Do not re-derive them from the sibling. If a row in both tables fits, the handoff table wins on workflow; this skill still owns conventions.

  • Unfamiliar data? Load references/image-understanding.md first — but only when class, range, or content is unknown.

  • Starting from a function name, not a task? The function column is illustrative, not exhaustive. To locate any function: grep -rln '<functionName>' references/. To look up syntax details, load matlab-read-documentation.

  • Pipeline tasks: load several references; cap at three unless the task genuinely spans more.

  • Follow the patterns in loaded references. References contain specific code patterns and workflows — use them instead of improvising equivalent code from general knowledge.

  • No row matches? Name the owning product, state the closest IPT fallback, and say so — do not guess a reference.

Check first: is this another skill's job?
If the task involves...Also load
Segmenting anatomy — tumor, lesion, organ, vessel — in CT, MRI, PET, ultrasound; MedSAM; radiomicsNo skill covers this — Medical Imaging Toolbox (segmentMedicalImage, groundTruthMedical); look up the doc page
Displaying or viewing a 2-D image: imshow, imageshow, viewer2d, montage, mask overlay, annotation, colorbar, colormap, figure exportmatlab-display-image
Displaying a 3-D volume: volshow, viewer3d, isosurface rendering, slice viewer, orthogonal viewsmatlab-display-volume
Hyperspectral or multispectral cubes, spectral indices, unmixing, ENVI, band selectionmatlab-analyze-spectral-images
Calling a PyTorch or ONNX vision model from MATLABmatlab-integrate-pytorch-vision
OCR, text recognition, reading text out of an imagematlab-recognize-text (requires Computer Vision Toolbox)
Factory-floor visual inspection: anomaly detection, defect/scratch/dent detection, gauging, pass/fail countingmatlab-use-visual-inspection (requires Visual Inspection Toolbox, R2026b+)
Barcode or QR reading, camera calibrationNo skill covers this — Computer Vision Toolbox (readBarcode, estimateCameraParameters); look up the doc page
Optical system design: lens import, prescription-side MTF, spot diagrams, ray tracing, tolerance analysismatlab-model-optics
In scope: pick the reference
If the task or the user's words involve...Illustrative functionsLoad
inspect, understand, characterize, explore data, look at my images, what kind of image, what am I working with, what's in this folder, describe the data, summarize the dataset, what format, bit depth, class and range, indexed image, alpha channel, metadata, file info, dataset characterization, before I start processingimfinfo, imhist, countEachLabelreferences/image-understanding.md
read, write, load, save, import, export, open an image, convert format, batch, folder of images, TIFF, PNG, JPEG, RAW, HDR, test patternimread, imwrite, imageDatastore, hdrreadreferences/image-io.md
video, footage, frames, read video, write video, VideoReader, VideoWriter, frame rate, video codec, MP4, AVIVideoReader, VideoWriter, readFrame, hasFrame, writeVideoreferences/video-io.md
smooth, blur an image, sharpen, denoise, noise, grainy, filter, kernel, padding, edge-preserving, bilateral, non-local means, frequency filterimgaussfilt, medfilt2, imsharpen, imbilatfilt, imnlmfilt, imdiffusefilt, imfilter, ordfilt2, locallapfilt, wiener2references/filtering.md
contrast, brighten, darken, too dark, washed out, enhance, improve, histogram, equalize, CLAHE, normalize, rescale, blend, arithmetic, type convert, flat-field, illumination correction, vignetting, uneven lightingimadjust, stretchlim, adapthisteq, histeq, rescale, mat2gray, im2single, imadd, imlincomb, imblend, imflatfieldreferences/preprocessing.md
erode, dilate, open, close, structuring element, 2-D morphology, fill holes, remove small objects, skeletonize, thin, tidy up a binary resultstrel, imerode, imdilate, imopen, imclose, imfill, bwareaopen, bwskel, imtophat, imreconstructreferences/morphological-ops.md
deblur, blurry, unfocused, out of focus, motion blur, camera shake, restore a blurred image, deconvolution, PSF estimationdeconvblind, deconvlucy, deconvwnr, deconvregreferences/deblurring.md
resize, rotate, crop, warp, scale, flip, straighten, affine, projective, perspective, undistort, lens distortion, spatial referencing, world coordinates, voxel coordinates, pixel coordinates, coordinate conversionimresize, imrotate, imcrop, imwarp, imtranslate, affinetform2d, imref2dreferences/geometric-transforms.md
align two images, stitch, mosaic, panorama, overlapping shots, seam, motion correction, multi-modal alignment, control points, non-rigid, deformable, homography (feature-based requires Computer Vision Toolbox)imregister, imregtform, imregdemons, imregcorr, detectSIFTFeatures, matchFeatures, estgeotform2d (last three: Computer Vision Toolbox), imregdeform (Medical Imaging Toolbox)references/registration.md
segment or threshold with no user input: binarize, Otsu, watershed, k-means or colour clustering, imsegsam automatic mode, deep-learning segmentationimbinarize, graythresh, multithresh, adaptthresh, watershed, imsegkmeans, imsegkmeans3, imsegisodata, imsegsamreferences/segmentation-automated.md
segment with user input: clicks, points, boxes, scribbles, seeds, prompted SAM, grabcut, active contours, region growing, lazy snapping, superpixels, App Designer segmentation UIssegmentAnythingModel, grabcut, activecontour, lazysnapping, imsegfmm, grayconnected, superpixelsreferences/segmentation-interactive.md
measure, count objects, how many, area, perimeter, centroid, size, shape, width, thickness, gap, diameter, Feret, orientation, detect edges, circles, lines, boundary tracing, ROI, world units, metrology, region, region properties, analysisregionprops, bwconncomp, bwareafilt, bwpropfilt, bwlabel, edge, imfindcircles, hough, bwboundariesreferences/analysis-measurement.md
quality, PSNR, SSIM, sharpness, noise level, is it blurry, compare two images, difference, before/after, MTF (camera/chart SFR), test chart, artifact (register first — full-reference metrics need pixel correspondence)psnr, ssim, multissim, immse, brisque, niqe, piqe, measureSharpness, esfrChartreferences/quality-assessment.md
texture, repetitive pattern, frequency domain, Fourier, FFT, DCT, Radon, Gabor, co-occurrence, GLCMgraycomatrix, graycoprops, entropyfilt, fft2, dct2, radon, gaborreferences/texture-transforms.md
color space, LAB, HSV, hue, saturation, white balance, color cast, color correction, color balance, ICC profile, grayscale conversionrgb2lab, lab2rgb, rgb2hsv, chromadapt, illumwhite, makecform, deltaE, decorrstretchreferences/color-processing.md
3-D array, volume, volumetric, voxel, slice stack, z-stack — filtering, 3-D morphology, 3-D transforms, or measurement applied to a volumeimgaussfilt3, medfilt3, imresize3, regionprops3, bwvolumefilt (R2026b), bwpropfilt3 (R2026b)references/3d-volume-processing.md
deep learning, neural network, train, U-Net, semantic segmentation networks, classify images, pretrained model, transfer learning, fine-tune, inference, augment, training dataset (requires DLT, often CVT)unet, deeplabv3plus, trainnet, semanticseg, imageDataAugmenter, augmentedImageDatastorereferences/deep-learning-imaging.md
build your own image app or GUI: sliders, live preview, parameter tuning, ROI widgetsuifigure, uigridlayout, uislider, drawrectanglereferences/app-building.md
DICOM, NIfTI, NRRD, DICOM-RT, patient metadata, anonymizing, medicalVolume, medicalImage, reading/writing medical formats, extractSlice, volume orientation, medical spatial referencingmedicalVolume, medicalImage, dicomreadVolume, dicomCollection, extractSlice, dicomContours, dicomanonreferences/medical-data-io.md
gigapixel, whole-slide, out-of-memory images, blockedImage, tiled workflows, image pyramids, .svs, .ndpi, .czi, TIFF > 10,000 px, parallel image processing, custom adaptersblockedImage, apply, getBlock, getRegion, selectBlockLocations, blockedImageDatastorereferences/large-image-processing.md

Toolbox Detection

When unsure what's available, check installed toolboxes:

hasIPT = ~isempty(ver('images'));
hasCVT = ~isempty(ver('vision'));
hasDLT = ~isempty(ver('nnet'));
hasMIT = ~isempty(ver('medical'));
hasWavelet = ~isempty(ver('wavelet'));

Most functions in this skill require Image Processing Toolbox. The deep-learning-imaging reference also requires Deep Learning Toolbox. Feature-based registration (detectSIFTFeatures, matchFeatures, estgeotform2d) requires Computer Vision Toolbox.

Release-Gated Features

This skill targets R2024b+ but some features require newer releases. References annotate these with the required release. Key ones:

  • R2024b: imageshow, imblend, viewer2d

  • R2026a: uidraw, uipaint, linkviewers

  • R2026b: bwvolumefilt, bwpropfilt3, uiannotate

If targeting an older release, check with isMATLABReleaseOlderThan("R2026a") and use the fallback patterns documented in the references. To check release notes for a specific function, load matlab-read-documentation.


Copyright 2026 The MathWorks, Inc.


Files

references/geometric-transforms.md

Geometric Transformations

Decision guidance and gotchas for resizing, rotating, cropping, warping, spatial referencing, and geometric transform objects.

Often loaded with: registration.md (aligning images after computing transforms), image-io.md (loading source images).

Legacy vs. Modern Transform Objects

Always use the modern tform objects:

Legacy (avoid)Modern (use)DOF
—transltform2d(tx, ty)2 (translation)
—rigidtform2d(angle, [tx ty])3 (rotation + translation)
—simtform2d(scale, angle, [tx ty])4 (similarity)
affine2daffinetform2d(A)6 (affine)
projective2dprojtform2d(A)8 (projective)
affine3daffinetform3d(A)12 (3-D affine)
—rigidtform3d, simtform3d, transltform3d3-D variants
Matrix Convention Change (R2022b)

Legacy and modern transform objects use a different convention to define the transformation matrix:

  • Legacy affine2d: post-multiply — [x y 1] = [u v 1] * T → translation in bottom row, property name .T

  • Modern affinetform2d: pre-multiply — [x; y; 1] = A * [u; v; 1] → translation in right column, property name .A

The two are related by transposition: A = T'. The modern objects, which use a pre-multiply convention, are consistent with most textbooks, Wikipedia, and online resources. When copying a matrix from a reference, use affinetform2d(A) directly — do NOT transpose it.

% Legacy (translation in bottom row — AVOID):
%   T = [1 0 0; 0 1 0; tx ty 1]
%   tform = affine2d(T);     % uses tform.T

% Modern (translation in right column — USE):
%   A = [1 0 tx; 0 1 ty; 0 0 1]
%   tform = affinetform2d(A);  % uses tform.A

Always use .A, not .T: When accessing the matrix from a modern transform object, use the .A property. The .T property exists only on legacy affine2d/affine3d objects and uses the transposed convention.

Constructing Transforms
% Translation only
tform = transltform2d([10 20]);           % [tx ty]

% Rigid: rotation (degrees) + translation
tform = rigidtform2d(30, [10 20]);        % 30° rotation, then translate

% Similarity: scale + rotation + translation
tform = simtform2d(2, 30, [10 20]);       % 2× scale, 30° rotation, translate

% Affine from 3×3 matrix
A = [1.2 0.1 5; -0.1 1.1 10; 0 0 1];
tform = affinetform2d(A);

% From point correspondences (replaces legacy fitgeotrans)
tform = fitgeotform2d(movingPts, fixedPts, "similarity");
Transform Operations
pts_world = transformPointsForward(tform, pts);   % Apply transform
pts_orig = transformPointsInverse(tform, pts);    % Undo transform
tform_inv = invert(tform);                        % Get inverse transform
Custom Non-Linear Transforms — geometricTransform2d

For arbitrary warps (barrel distortion, fisheye correction, custom mappings) that aren't affine or projective:

% Define inverse mapping: given output coords, return where to sample in input
inverseFcn = @(xy) [xy(:,1) + 10*sin(xy(:,2)/20), xy(:,2)];  % sinusoidal warp
tform = geometricTransform2d(inverseFcn);

warped = imwarp(img, tform);
  • imwarp requires at minimum the inverse function (output → input mapping)

  • Optionally provide a forward function for transformPointsForward

  • Function handle must be vectorized: takes N×2 [x y] matrix, returns N×2 [xOut yOut]

imtranslate — Simple Image Shift

For translating an image by a pixel offset, use imtranslate — do NOT build a full transform object:

shifted = imtranslate(img, [tx ty]);           % Shift by [tx ty] pixels (x=col, y=row)
shifted = imtranslate(img, [tx ty], "nearest"); % Specify interpolation
shifted = imtranslate(img, [tx ty], "OutputView", "same");  % Keep same size (default)
shifted = imtranslate(img, [tx ty], "OutputView", "full");  % Expand to fit shifted content

Gotcha: The translation vector is [x, y] (columns, rows) — not [row, col].

When NOT to use: If you also need rotation/scale/shear, build a proper transform and use imwarp.

imrotate — Rotate an Image About a Point

Default is "loose" — output is larger than input. Out-of-bounds pixels are set to 0.

rotated = imrotate(img, 45);                   % "loose": bounding box grows
rotated = imrotate(img, 45, "bilinear", "crop");  % "crop": same size, corners clipped
Rotation About an Arbitrary Point (R2026b)

By default, imrotate rotates about the center of the image. Use RotationCenter to specify a different pivot:

rotated = imrotate(img, 30, RotationCenter=[100 50]);  % Rotate about (cx=100, cy=50)
  • Coordinates are [cx, cy] in intrinsic image coordinates (x = column direction, y = row direction)

  • Default center of an M×N image: [(N+1)/2, (M+1)/2]

  • "loose" bbox is not supported with RotationCenter — defaults to "crop"

  • Out-of-bounds centers are allowed (e.g., rotating a tile around a point in a larger mosaic)

Composing Transforms — Do Not Chain imtranslate → imrotate → imresize

If you need a geometric transformation that is a chain of primitives (translation, rotation, scale), do not chain imtranslate, imrotate, and imresize calls. This is wasteful — each call makes a full pass through the image and creates an intermediate full-image variable, and each interpolation pass degrades quality.

Instead, compose a single geometric transformation by multiplying the primitive .A matrices, then apply once with imwarp:

R = rigidtform2d(theta, [0 0]);       % Rotation only
S = simtform2d(s, 0, [0 0]);          % Scale only
T = transltform2d(tx, ty);            % Translation only
tform = affinetform2d(T.A * S.A * R.A);  % Compose: rotate → scale → translate
out = imwarp(img, tform);

Note on imresize vs. scale in imwarp: imresize applies an antialiasing filter by default when downsampling; imwarp does not. A composed scale transform through imwarp is not equivalent to imresize unless you set imresize(..., "Antialiasing", false).

imwarp — The General-Purpose Warper

warped = imwarp(img, tform);
Key Gotcha: Output Size Changes

By default, imwarp computes a bounding box that contains the entire transformed image. The output size will differ from input size. To keep the same size, specify the OutputView name-value argument:

Rout = imref2d(size(img));  % Same spatial extent as input
warped = imwarp(img, tform, OutputView=Rout);

For more control, use affineOutputView:

% Full transformed content (matches imwarp default when no OutputView is specified)
Rout = affineOutputView(size(img), tform, BoundsStyle="FollowOutput");
warped = imwarp(img, tform, OutputView=Rout);

% Same size as input, centered — default BoundsStyle for affineOutputView
Rout = affineOutputView(size(img), tform, BoundsStyle="CenterOutput");
warped = imwarp(img, tform, OutputView=Rout);

% Same size as input, origin-aligned
Rout = affineOutputView(size(img), tform, BoundsStyle="SameAsInput");
warped = imwarp(img, tform, OutputView=Rout);
Interpolation

Default is "linear" (not "cubic"). Use "nearest" for label maps or binary masks to avoid creating intermediate values.

warped = imwarp(img, tform, "nearest");  % Preserves exact values — use for masks/labels
warped = imwarp(img, tform, "linear");   % Default for numeric images
warped = imwarp(img, tform, "cubic");    % Smoother, slightly slower
FillValues

Specifies what value fills out-of-bounds pixels (default: 0).

warped = imwarp(img, tform, FillValues=128);       % Scalar — all channels
warped = imwarp(rgb, tform, FillValues=[0 255 0]); % Per-channel vector
SmoothEdges

Controls whether the interpolation kernel can sample beyond the original image extent.

  • false (default): Out-of-bounds samples are excluded from interpolation. Edge pixels are interpolated only from actual image content → sharp cutoff at boundary. Good for stitching and mosaics to achieve a crisp seam between images.

  • true: Input is padded with FillValues before interpolation. Edge pixels blend between image content and the fill value → gradual 1–2 pixel transition. Good for single-image display to avoid harsh staircase at diagonal boundaries.

warped = imwarp(img, tform, SmoothEdges=true);   % Blended edges
warped = imwarp(img, tform, SmoothEdges=false);  % Sharp edges (default)

Warper — Fast Repeated Transforms

Use images.geotrans.Warper when applying the same transform to many same-sized images. It precomputes the coordinate mapping once, then only performs interpolation per image.

From a transform object
tform = rigidtform2d(10, [5 3]);
warper = images.geotrans.Warper(tform, size(img));

% Apply to many frames
for i = 1:numFrames
    result = warp(warper, frames{i});
end
From precomputed source coordinates

For custom non-linear mappings (lens undistortion, perspective rectification, etc.) where you compute the coordinate map from any source:

% Precompute mapping (e.g., from camera intrinsics + a plane transform)
[X, Y] = meshgrid(1:width, 1:height);
sourceX = X + displacementX;  % Where each output pixel samples from
sourceY = Y + displacementY;

warper = images.geotrans.Warper(sourceX, sourceY);

% Fast per-frame warp
rectified = warp(warper, frame);
When to use
ScenarioUse
Single image, one-off transformimwarp
Same transform applied to many same-sized imagesWarper (initialize once, warp per frame)

imresize — Resize Images

Resizes an image by a scale factor or to a target [rows cols] size. Applies antialiasing by default when downsampling.

Size Argument is [rows cols], Not [width height]
img = imread("peppers.png");    % 384×512×3
resized = imresize(img, [200 300]);  % 200 rows × 300 cols (NOT 200w × 300h)
Antialiasing

imresize enables antialiasing by default when downsampling. Disabling it is faster but may produce aliasing:

small = imresize(img, 0.25);                        % Antialiased (default)
small = imresize(img, 0.25, "Antialiasing", false); % Faster, may alias
Interpolation

Default is "bicubic". Use "nearest" for label maps or masks to avoid creating intermediate values:

mask_resized = imresize(mask, 0.5, "nearest");  % Preserves binary/label values

imcrop — Coordinate Convention

imcrop uses [xmin ymin width height] — spatial (x,y) coordinates, NOT (row, col):

% x = column direction, y = row direction
cropped = imcrop(img, [100 50 200 150]);  % x: 100–300, y: 50–200
% Equivalent indexing: img(50:200, 100:300, :)

Output size is (height+1) × (width+1) because both endpoints are included.

imcrop does not accept spatial referencing objects. imcrop(img, R, rect) where R is an imref2d silently returns an empty result — R is misinterpreted as legacy imcrop(xref, yref, ...) arguments. To crop in world coordinates, convert world bounds to pixel indices with worldToSubscript or worldToDiscrete and use array indexing.

Center and Random Crops
win = centerCropWindow2d(size(img), [200 200]);  % Centered crop window
cropped = imcrop(img, win);

win = randomCropWindow2d(size(img), [100 100]);  % Random location
cropped = imcrop(img, win);

Spatial Referencing — imref2d / imref3d

Associates pixel grid with world coordinates. Critical for imwarp OutputView and registration:

% Default: pixel coordinates (pixel centers at 1, 2, 3, ...)
R = imref2d(size(img));

% Custom world extent: image covers [0,10] × [0,10] world units
R = imref2d(size(img), [0 10], [0 10]);  % [XWorldLimits], [YWorldLimits]

% Uniform pixel spacing (e.g., 0.5 mm pixels)
R = imref2d(size(img), 0.5, 0.5);  % PixelExtentInWorldX, PixelExtentInWorldY

Key properties: XWorldLimits, YWorldLimits, PixelExtentInWorldX, PixelExtentInWorldY, ImageSize

Coordinate Conversion

Convert between voxel/pixel subscripts and world coordinates using methods on the spatial referencing object:

% 2-D: pixel ↔ world
R = imref2d(size(img), pixelSpacingX, pixelSpacingY);
[xWorld, yWorld] = intrinsicToWorld(R, col, row);
[col, row] = worldToIntrinsic(R, xWorld, yWorld);
[row, col] = worldToSubscript(R, xWorld, yWorld);  % Rounded to nearest pixel

% 3-D: voxel ↔ world
R3 = imref3d(size(V), xSpacing, ySpacing, zSpacing);
[xW, yW, zW] = intrinsicToWorld(R3, col, row, slice);
[col, row, slice] = worldToIntrinsic(R3, xW, yW, zW);
[row, col, slice] = worldToSubscript(R3, xW, yW, zW);

% Check if a world point is inside the volume bounds
tf = contains(R3, xW, yW, zW);

Argument order gotcha: intrinsicToWorld and worldToIntrinsic use (x, y, z) order (col, row, slice), but worldToSubscript returns (row, col, slice) order for direct array indexing.

Image Pyramids

reduced = impyramid(img, "reduce");   % Gaussian smooth + downsample by 2
expanded = impyramid(img, "expand");  % Upsample by 2 + interpolate

Build a multi-level pyramid:

pyramid = cell(1, 4);
pyramid{1} = img;
for i = 2:4
    pyramid{i} = impyramid(pyramid{i-1}, "reduce");
end

Common Mistakes

MistakeWhy it's wrongCorrect approach
Using affine2d / projective2dLegacy, transposed matrix conventionUse affinetform2d / projtform2d
imresize(img, [width height])Argument is [rows cols] not [w h]imresize(img, [rows cols])
imwarp without OutputViewOutput size changes unpredictablySet "OutputView", imref2d(size(img))
imcrop(img, [row col h w])imcrop takes [x y w h] not [row col ...]Remember: x=col, y=row
imresize(mask, 0.5) for labelsBicubic creates non-integer valuesUse "nearest" for masks/labels
imrotate expecting same sizeDefault is "loose" (larger output)Add "crop" for same-size output
Building transform matrix in legacy formatRow/column of translation differsUse constructor: rigidtform2d(angle, [tx ty])
fitgeotransLegacy functionUse fitgeotform2d
Building affinetform2d just to translateOvercomplicated for a shiftUse imtranslate(img, [tx ty])

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