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/preprocessing.md

Preprocessing

Diagnostic decision guide for preparing images before processing: data type interpretation, conversion, normalization, contrast enhancement, illumination correction, and arithmetic. Start from the problem (dark image, uneven lighting, wrong range), not the function name.

Often loaded with: filtering.md (smoothing/denoising), image-io.md (loading data), deep-learning-imaging.md (per-channel normalization for networks).

Routes to other references: color space conversion → color-processing.md; morphological illumination correction (top-hat, bottom-hat) → morphological-ops.md; indexed image semantics → image-io.md; volumetric preprocessing → 3d-volume-processing.md; display viewers → skill matlab-display-image.

Characterize Before Transforming

Before any preprocessing step, establish these properties (for full characterization workflows, see image-understanding.md):

PropertyHow to checkWhy it matters for preprocessing
Storage classclass(img)Controls arithmetic behavior, saturation, and function compatibility
Actual data range[min(img(:)) max(img(:))]May differ from the type's valid range — e.g., 12-bit sensor data in uint16 uses only [0, 4095]
Display rangeWhat the viewer assumesA dark display does not mean dark data — determines whether you need data modification or just a viewer adjustment

Key insight: conversion is not normalization. im2single does type-aware scaling (uint8 255 → 1.0); rescale remaps actual min/max. double(img) does neither — it just changes the type without scaling, producing values like 128.0 that IPT functions interpret as out-of-range.

Problem-Oriented Preprocessing Workflow

  1. Diagnose — What is wrong? (dark, low contrast, uneven illumination, wrong type for downstream task)

  2. Choose one transformation — Pick the minimal operation that addresses the problem

  3. Inspect the result — Verify the fix didn't introduce new issues

  4. Evaluate — Does it improve the downstream task? (see quality-assessment.md)

  5. Only then add another stage — stacked operations obscure which step caused a failure

Typical Preprocessing Order

When multiple preprocessing steps are needed, this order avoids common pitfalls:

  1. Illumination correction (imflatfield, imtophat) — before contrast enhancement, which would amplify the illumination gradient

  2. Denoising (imgaussfilt, medfilt2, imnlmfilt) — before contrast enhancement, which would amplify noise

  3. Contrast enhancement (imadjust, adapthisteq) — after illumination and noise are addressed

  4. Type conversion (im2single, im2uint8) — at the boundary where downstream functions require a specific type

Illumination correction, contrast enhancement, and histogram equalization are covered in the sections that follow this order. Denoising is covered in filtering.md. The remaining sections — image arithmetic, linear combinations, and image blending — cover operations typically applied at or after the type-conversion boundary.

Display vs Data — Know the Difference

Adjusting the viewer's display range changes presentation only. Calling imadjust or rescale changes the actual pixel data. Before modifying data, ask: does the output need to be saved or only inspected? For scientific/medical data, prefer display-range adjustment over data modification when the goal is visualization.

% Display-only: adjust viewer window/level — data is untouched
imageshow(img, DisplayRange=[500 2000]);

% Data modification: pixels are permanently changed
adjusted = imadjust(img, [500/65535 2000/65535], []);

Illumination Correction

GoalFunctionRoute
Correct smooth, gradual falloff (vignetting, microscopy)imflatfield(img, sigma)This reference
Estimate and subtract backgroundBackground estimation + subtractionThis reference
Extract small bright objects on dark backgroundimtophat (morphological)morphological-ops.md
Extract small dark objects on bright backgroundimbothat (morphological)morphological-ops.md
Clean up documents for OCRMorphological binarization pipelinemorphological-ops.md
imflatfield
corrected = imflatfield(img, sigma);
  • sigma should be larger than the largest foreground object (typical: 30–100)

  • Supports a Mask argument to limit where the correction is applied — pixels where the mask is false retain their original values

  • Processes RGB images through the HSV value channel automatically

  • Simpler than morphological alternatives for smooth illumination gradients

Contrast Enhancement — Choosing a Method

GoalFunctionWhat it does
Remap endpoints to known desired rangeimadjust(img, [low high], [])Linear mapping with explicit limits
Remap endpoints to automatically calculated rangeimadjust(img) (grayscale only)Clips bottom/top 1% via stretchlim — robust to outliers
Remap RGB image to automatically calculated rangeimadjust(rgb, stretchlim(rgb), [])Must provide explicit limits — imadjust(rgb) without args errors
Redistribute intensities for uniform histogramhisteq(img)Maximizes global contrast; can look unnatural and amplify noise in flat regions
Apply locally varying contrast enhancementadapthisteq(img) (CLAHE)Tile-based — reveals detail in varying-brightness images
Gamma correctionimadjust(img, [], [], gamma)gamma < 1 brightens; gamma > 1 darkens
Brighten dark regions selectivelyimlocalbrighten(img)Brightens dim areas while preserving already bright regions; AlphaBlend=true protects highlights
Remove atmospheric hazeimreducehaze(img)Uses approximate dark channel prior method; returns dehazed image, transmission map, and atmospheric light estimate
Histogram Equalization
FunctionEffectRisk
histeqGlobal histogram equalizationCan look unnatural; amplifies noise in flat regions
adapthisteqLocal (tile-based) CLAHEMore stable; ClipLimit controls noise amplification

Color images: Never apply histeq or adapthisteq directly to RGB — per-channel equalization distorts color. Convert to L*a*b* or HSV and equalize only the luminance/value channel.

imadjust Details
adj = imadjust(gray);                           % Auto 1% saturation
adj = imadjust(rgb, stretchlim(rgb), []);        % RGB — required form
adj = imadjust(img, [0.2 0.8], [0 1]);           % Explicit input range
adj = imadjust(img, [], [], 0.5);                 % Gamma correction
  • Single [low high] applies to all channels; a 2-by-3 matrix allows per-channel limits

CLAHE — adapthisteq
enhanced = adapthisteq(img, ClipLimit=0.02, NumTiles=[8 8]);
  • ClipLimit (0–1): higher = more contrast; lower = prevents noise amplification. Start with 0.02

  • NumTiles: more tiles = more local; can expose tile-boundary artifacts at high values

  • NBins: trades speed for dynamic-range fidelity (default 256)

  • Grayscale only — for color images, apply to luminance channel only (convert to L*a*b*, enhance L, convert back, clip out-of-gamut). See color-processing.md for the full pattern

Histogram Matching — imhistmatch / imhistmatchn

Transform an image so its histogram approximates a reference image's histogram. Use for batch normalization, cross-session consistency, or matching imaging conditions:

matched = imhistmatch(img, referenceImg);           % 2-D grayscale or RGB
matched = imhistmatchn(vol, referenceVol);           % N-D grayscale
  • imhistmatch accepts grayscale or RGB (per-channel matching for RGB)

  • imhistmatchn is grayscale only, works on N-D data (volumes)

  • Both accept uint8, uint16, int16, single, double

Conversion and Normalization Decision Tree

GoalFunctionWhat it does
Convert to float for arithmetic with type-aware range scalingim2single(img)uint8 /255, uint16 /65535 → [0, 1] single; preserves relative intensities
Convert to double precision with type-aware range scalingim2double(img)Same scaling as im2single but double; rarely needed — prefer im2single
Remap actual data extrema to a target rangerescale(img) or rescale(img, 0, 255)Linear map of actual min/max; can target any range
Remap from a known sensor rangerescale(img, 0, 1, InputMin=0, InputMax=4095)Useful for 12-bit, 14-bit sensor data in wider containers
Make a non-image matrix displayablemat2gray(img)Actual min/max → double [0, 1]; always outputs double
Robust contrast stretch (clip outliers)imadjust(img) / stretchlimSaturates bottom/top 1% by default
Prepare float data for imwriteim2uint8(img)Float [0,1] → uint8 [0,255]

Do NOT use double(img) for image conversion — it changes the type without scaling, leaving values like 128.0 that IPT treats as out-of-range.

Quantization warning: converting from higher to lower bit depth (e.g., uint16 → uint8) permanently discards precision. Do this only at the end of a pipeline.

Batch warning: rescale and imadjust with default arguments normalize each image to its own min/max. In a dataset where intensity comparisons across images matter (time series, dose response, multi-well plates), compute normalization limits once from the entire dataset and apply them uniformly — otherwise inter-image relationships are destroyed.

Prefer im2single over im2double:

  • Halves memory (4 bytes/pixel vs 8)

  • Many IPT functions have optimized code paths for single

  • 24-bit mantissa covers uint16 range exactly

Most IPT functions accept integer images directly — do not convert to floating-point as a default habit. If an IPT function rejects your data type, check its documentation with matlab-read-documentation — the issue may be a specific type restriction (e.g., int16 not supported), not a blanket float requirement.

When float IS needed: custom arithmetic operations (matrix math, weighted sums — integer clips silently), deep learning network input (see deep-learning-imaging.md for per-channel normalization with ImageNet statistics and dataset mean/std).

Image Arithmetic and Precision

Integer arithmetic clips silently. Nested operations compound rounding error:

Functionuint8 behaviordouble behavior
imadd(A, B)Saturates at 255Can exceed 1.0
imsubtract(A, B)Saturates at 0Can go negative
imabsdiff(A, B)Absolute differenceAlways non-negative
imcomplement(A)255 - A1 - A

Precision rule: If a computation involves subtraction, weighting, or multiple steps, convert to single once at the start, compute, then cast to the output type once at the end:

% WRONG — integer clips at each step
result = imadd(imsubtract(uint8(A), uint8(B)), uint8(C));  % Lost negatives, compounded rounding

% RIGHT — compute in float, cast once
A = im2single(A); B = im2single(B); C = im2single(C);
result = im2uint8(A - B + C);
imlincomb — Linear Combinations Without Intermediate Clipping

For weighted sums, imlincomb computes the entire expression in double precision and rounds only at the end. Use imlincomb when you need precise weighted arithmetic on integer images and the result should remain integer. For visual compositing and blending effects, use imblend instead.

% Weighted blend — no intermediate clipping
result = imlincomb(0.7, img1, 0.3, img2);           % Returns same class as img1
result = imlincomb(0.5, A, 0.5, B, "single");       % Force output class
result = imlincomb(1, img1, -1, img2, 128);          % Difference with offset

Prefer imlincomb over manual a*im2single(A) + b*im2single(B) when the output should remain integer.

Image Blending — imblend

Blend two images using various modes (R2024b). Do NOT manually implement alpha blending:

blended = imblend(foreground, background);                        % Alpha blend (default)
blended = imblend(fg, bg, mask, Mode="Poisson");                  % Seamless Poisson blend
blended = imblend(fg, bg, mask, Mode="PoissonMixGradients");      % Mix gradients at boundary
blended = imblend(fg, bg, mask, Location=[100 50]);               % Place fg at offset in bg
ModeEffectUse case
"Alpha"Opacity-weighted blendGeneral compositing
"Poisson"Seamless gradient-domain blendObject insertion without visible seams
"PoissonMixGradients"Mix fg+bg gradientsTexture transfer, transparent object insertion
"Guided"Edge-preserving blendSmooth transitions preserving structure
"Min" / "Max" / "Average" / "Overlay"Pixel-wise operationsSpecial effects

Common Mistakes

MistakeWhy it's wrongCorrect approach
double(img) instead of im2single(img)No scaling — 128.0 is out of [0,1] rangeUse im2single or im2double for image conversion
Converting to float "just in case"Wastes memory, no benefit for built-in functionsMost IPT functions accept integer directly
imadjust(rgbImage) without argsErrors — no auto mode for RGBimadjust(rgb, stretchlim(rgb), [])
adapthisteq on RGB directlyPer-channel equalization distorts colorApply to L channel in L*a*b* space
Manual (x-min)/(max-min)Reinventing the wheel, no output-range controlrescale(x) or rescale(x, 0, 255)
Integer arithmetic with subtractionNegatives clip to 0 silentlyConvert to float first, or use imlincomb
Stacking multiple adjustments blindlyCan't tell which step caused a problemApply one transformation, inspect, then proceed
adapthisteq on float data outside [0,1]Silently clips output to [0,1] — no error or warningEnsure float input is in [0,1] before calling; use rescale if needed
Modifying scientific data when only display neededPermanent data lossAdjust viewer DisplayRange instead
uint16 → uint8 early in pipelineDiscards 8 bits of precisionConvert to lower bit depth only at the final output step

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