Matlab Process Images
MathWorksOfficialCreated by MathWorks
- Skill
- Tool integration
- Software development
- BSD-2-Clause
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill serves as the primary entry point for MATLAB tasks involving images, scans, frames, and 3-D volumes. It provides core conventions for image data types, coordinate systems, and display practices, while routing users to specific references for tasks such as I/O, filtering, segmentation, and measurement. It ensures consistent use of Image Processing Toolbox functions and helps users navigate common pitfalls in image analysis workflows.
What it does
- Provides standardized conventions for image data types and coordinate systems.
- Routes users to specialized references for image I/O, filtering, and transformation tasks.
- Defines best practices for displaying images using the imageshow function.
- Offers guidance on handling 3-D volumetric data and large-scale images.
- Assists with selecting appropriate functions for segmentation and object measurement.
- Provides troubleshooting patterns for common image processing errors.
When to use it
- When performing image processing tasks in MATLAB, such as filtering, enhancing, or segmenting.
- When working with image formats like TIFF, PNG, JPEG, DICOM, or NIfTI.
- When needing to understand MATLAB-specific coordinate conventions for image data.
- When determining the correct toolbox function for a specific image analysis goal.
- When troubleshooting syntax or type-related errors in image processing scripts.
Advantages
- Ensures consistent coding patterns across different image processing tasks.
- Reduces errors by providing clear guidance on coordinate and data type conventions.
- Simplifies the selection of appropriate tools for complex workflows like 3-D volume processing.
- Promotes the use of modern display functions like imageshow over legacy alternatives.
- Provides a structured approach to identifying the correct documentation for specific functions.
Usage examples
- “How do I read a DICOM file and display it in MATLAB?”
- The agent will guide you to use the medical-data-io reference for reading the file and the imageshow function for display, following the core conventions.
- “I need to count the number of objects in a binary image.”
- The agent will provide the standard analysis pipeline using bwconncomp and regionprops, ensuring the input is correctly formatted as logical.
- “How do I perform 3-D filtering on a volume?”
- The agent will direct you to the 3-D volume processing reference to select the appropriate 3-D specific function, such as imgaussfilt3.
- “Why is my regionprops measurement returning only one object?”
- The agent will explain that the input must be a logical array and provide the code to convert your numeric array to logical.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/matlab/matlab-process-images/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip matlab-process-images.zip -d .agents/skills
Documentation by MathWorks
Image Processing
Process, analyze, and transform images using MATLAB Image Processing Toolbox (IPT). This skill routes you to the correct reference for your task and provides core conventions that apply across all IPT work.
When to Use
Loaded for general-purpose IPT work: file and batch I/O, filtering, restoration, morphology, segmentation, measurement, geometric transforms, color, texture, quality metrics, deep learning on images, and image apps. Non-medical microscopy — cell and particle counting on plain IPT — is in scope.
Hand off (and co-load) instead of answering alone: see the handoff table under ## Routing.
When NOT to Use
Training a network with no image-specific preprocessing — use Deep Learning Toolbox directly
Simulink or Stateflow video blocks — use Simulink directly
C/C++ code generation, MEX, GPU acceleration and deployment — use MATLAB Coder / GPU Coder directly
Point clouds, 3-D reconstruction, and video stabilization — use Computer Vision Toolbox directly
General MATLAB questions unrelated to images
Looking at an image yourself (e.g., "look at this screenshot") when no MATLAB work is requested — use your own vision instead
Core Conventions
Image Data Types
| Type | Range | When to use |
|---|---|---|
uint8 | 0–255 | Display, file I/O, memory-efficient storage |
uint16 | 0–65535 | High dynamic range sensors, medical. Camera RAW is n-bit in a uint16 container — rescale with rawinfo BlackLevel/WhiteLevel, not 65535 |
single / double | 0.0–1.0 | Arithmetic, filtering, computation |
logical | 0 or 1 | Binary masks, segmentation results |
Most IPT functions accept integer types directly — do not convert to floating-point unless required.
Default Coordinate Conventions
MATLAB images are (row, col) — row is Y (down), column is X (right)
size(img)returns[height, width, channels]Spatial functions use (x, y) order for coordinates (e.g.,
imref2d,regionpropscentroids)Pixel centers are at integer intrinsic coordinates; in default world referencing, pixel (1,1) center is at world (1.0, 1.0) and the image edge starts at 0.5
imref2dandimref3dcan specify non-default spatial referencing to place images into world coordinate systems. By default they use the unit-spaced, integer-pixel-centered coordinate system described here, e.g.Rout = imref2d(imageSize). Functions that do not accept spatial referencing objects assume this intrinsic coordinate system for any operation requiring spatial referencing.
Multichannel Images
Grayscale:
M×NorM×N×1RGB:
M×N×3With alpha: read using
[img, ~, alpha] = imread(...)(alpha is the third output)Convert:
rgb2gray,im2gray(preferred, handles more input types)
Display Functions — use imageshow, not imshow
Always use imageshow instead of imshow in all generated code — scripts, apps, examples, and quick previews. The signatures are compatible for common cases: replace imshow(...) with imageshow(...). imageshow (R2024b+) handles sub-bit-depth containers (e.g., 12-bit in uint16) via DisplayRangeMode, supports OverlayData for label/mask overlays, and works with viewer2d. imshow lacks all of these capabilities and should not appear in new code.
Title convention: imageshow creates a viewer2d, not an axes — gca does not return it. To add a title, get the viewer from the Image object's parent:
obj = imageshow(im);
viewer = obj.Parent;
title(viewer, "Title Text");Do not use title("text") or title(gca, "text") after imageshow — these silently fail or create a stray axes title.
Code Execution
Execute code blocks via evaluate_matlab_code before presenting them to the user. If it errors, fix and re-run. This catches type mismatches, wrong argument orders, and nonexistent functions before the user sees them. If execution requires user data or toolboxes not available in the current session, present the code with a note that it should be run with the user's own data — do not loop trying to synthesize stand-in data.
Error Recovery
If code throws an error after execution, load the matlab-read-documentation skill and look up the function's doc page to verify syntax, required arguments, and supported input types before retrying.
When to Ask the User
Ask for clarification before proceeding when:
The image type/format is ambiguous and affects the processing approach
Multiple valid approaches exist with different tradeoffs (speed vs quality, lossy vs lossless)
The task requires choosing parameters that depend on domain knowledge (e.g., object size thresholds, noise characteristics)
The user's MATLAB release is unknown and the recommended function may not be available
Routing
Match your task in the tables below. Check the handoff table first. If the task belongs to another skill, load that skill in addition to this one — the Core Conventions above (data types, coordinate order, code execution) apply to all image data. Do not re-derive them from the sibling. If a row in both tables fits, the handoff table wins on workflow; this skill still owns conventions.
Unfamiliar data? Load
references/image-understanding.mdfirst — but only when class, range, or content is unknown.Starting from a function name, not a task? The function column is illustrative, not exhaustive. To locate any function:
grep -rln '<functionName>' references/. To look up syntax details, loadmatlab-read-documentation.Pipeline tasks: load several references; cap at three unless the task genuinely spans more.
Follow the patterns in loaded references. References contain specific code patterns and workflows — use them instead of improvising equivalent code from general knowledge.
No row matches? Name the owning product, state the closest IPT fallback, and say so — do not guess a reference.
Check first: is this another skill's job?
| If the task involves... | Also load |
|---|---|
| Segmenting anatomy — tumor, lesion, organ, vessel — in CT, MRI, PET, ultrasound; MedSAM; radiomics | No skill covers this — Medical Imaging Toolbox (segmentMedicalImage, groundTruthMedical); look up the doc page |
Displaying or viewing a 2-D image: imshow, imageshow, viewer2d, montage, mask overlay, annotation, colorbar, colormap, figure export | matlab-display-image |
Displaying a 3-D volume: volshow, viewer3d, isosurface rendering, slice viewer, orthogonal views | matlab-display-volume |
| Hyperspectral or multispectral cubes, spectral indices, unmixing, ENVI, band selection | matlab-analyze-spectral-images |
| Calling a PyTorch or ONNX vision model from MATLAB | matlab-integrate-pytorch-vision |
| OCR, text recognition, reading text out of an image | matlab-recognize-text (requires Computer Vision Toolbox) |
| Factory-floor visual inspection: anomaly detection, defect/scratch/dent detection, gauging, pass/fail counting | matlab-use-visual-inspection (requires Visual Inspection Toolbox, R2026b+) |
| Barcode or QR reading, camera calibration | No skill covers this — Computer Vision Toolbox (readBarcode, estimateCameraParameters); look up the doc page |
| Optical system design: lens import, prescription-side MTF, spot diagrams, ray tracing, tolerance analysis | matlab-model-optics |
In scope: pick the reference
| If the task or the user's words involve... | Illustrative functions | Load |
|---|---|---|
| inspect, understand, characterize, explore data, look at my images, what kind of image, what am I working with, what's in this folder, describe the data, summarize the dataset, what format, bit depth, class and range, indexed image, alpha channel, metadata, file info, dataset characterization, before I start processing | imfinfo, imhist, countEachLabel | references/image-understanding.md |
| read, write, load, save, import, export, open an image, convert format, batch, folder of images, TIFF, PNG, JPEG, RAW, HDR, test pattern | imread, imwrite, imageDatastore, hdrread | references/image-io.md |
| video, footage, frames, read video, write video, VideoReader, VideoWriter, frame rate, video codec, MP4, AVI | VideoReader, VideoWriter, readFrame, hasFrame, writeVideo | references/video-io.md |
| smooth, blur an image, sharpen, denoise, noise, grainy, filter, kernel, padding, edge-preserving, bilateral, non-local means, frequency filter | imgaussfilt, medfilt2, imsharpen, imbilatfilt, imnlmfilt, imdiffusefilt, imfilter, ordfilt2, locallapfilt, wiener2 | references/filtering.md |
| contrast, brighten, darken, too dark, washed out, enhance, improve, histogram, equalize, CLAHE, normalize, rescale, blend, arithmetic, type convert, flat-field, illumination correction, vignetting, uneven lighting | imadjust, stretchlim, adapthisteq, histeq, rescale, mat2gray, im2single, imadd, imlincomb, imblend, imflatfield | references/preprocessing.md |
| erode, dilate, open, close, structuring element, 2-D morphology, fill holes, remove small objects, skeletonize, thin, tidy up a binary result | strel, imerode, imdilate, imopen, imclose, imfill, bwareaopen, bwskel, imtophat, imreconstruct | references/morphological-ops.md |
| deblur, blurry, unfocused, out of focus, motion blur, camera shake, restore a blurred image, deconvolution, PSF estimation | deconvblind, deconvlucy, deconvwnr, deconvreg | references/deblurring.md |
| resize, rotate, crop, warp, scale, flip, straighten, affine, projective, perspective, undistort, lens distortion, spatial referencing, world coordinates, voxel coordinates, pixel coordinates, coordinate conversion | imresize, imrotate, imcrop, imwarp, imtranslate, affinetform2d, imref2d | references/geometric-transforms.md |
| align two images, stitch, mosaic, panorama, overlapping shots, seam, motion correction, multi-modal alignment, control points, non-rigid, deformable, homography (feature-based requires Computer Vision Toolbox) | imregister, imregtform, imregdemons, imregcorr, detectSIFTFeatures, matchFeatures, estgeotform2d (last three: Computer Vision Toolbox), imregdeform (Medical Imaging Toolbox) | references/registration.md |
segment or threshold with no user input: binarize, Otsu, watershed, k-means or colour clustering, imsegsam automatic mode, deep-learning segmentation | imbinarize, graythresh, multithresh, adaptthresh, watershed, imsegkmeans, imsegkmeans3, imsegisodata, imsegsam | references/segmentation-automated.md |
| segment with user input: clicks, points, boxes, scribbles, seeds, prompted SAM, grabcut, active contours, region growing, lazy snapping, superpixels, App Designer segmentation UIs | segmentAnythingModel, grabcut, activecontour, lazysnapping, imsegfmm, grayconnected, superpixels | references/segmentation-interactive.md |
| measure, count objects, how many, area, perimeter, centroid, size, shape, width, thickness, gap, diameter, Feret, orientation, detect edges, circles, lines, boundary tracing, ROI, world units, metrology, region, region properties, analysis | regionprops, bwconncomp, bwareafilt, bwpropfilt, bwlabel, edge, imfindcircles, hough, bwboundaries | references/analysis-measurement.md |
| quality, PSNR, SSIM, sharpness, noise level, is it blurry, compare two images, difference, before/after, MTF (camera/chart SFR), test chart, artifact (register first — full-reference metrics need pixel correspondence) | psnr, ssim, multissim, immse, brisque, niqe, piqe, measureSharpness, esfrChart | references/quality-assessment.md |
| texture, repetitive pattern, frequency domain, Fourier, FFT, DCT, Radon, Gabor, co-occurrence, GLCM | graycomatrix, graycoprops, entropyfilt, fft2, dct2, radon, gabor | references/texture-transforms.md |
| color space, LAB, HSV, hue, saturation, white balance, color cast, color correction, color balance, ICC profile, grayscale conversion | rgb2lab, lab2rgb, rgb2hsv, chromadapt, illumwhite, makecform, deltaE, decorrstretch | references/color-processing.md |
| 3-D array, volume, volumetric, voxel, slice stack, z-stack — filtering, 3-D morphology, 3-D transforms, or measurement applied to a volume | imgaussfilt3, medfilt3, imresize3, regionprops3, bwvolumefilt (R2026b), bwpropfilt3 (R2026b) | references/3d-volume-processing.md |
| deep learning, neural network, train, U-Net, semantic segmentation networks, classify images, pretrained model, transfer learning, fine-tune, inference, augment, training dataset (requires DLT, often CVT) | unet, deeplabv3plus, trainnet, semanticseg, imageDataAugmenter, augmentedImageDatastore | references/deep-learning-imaging.md |
| build your own image app or GUI: sliders, live preview, parameter tuning, ROI widgets | uifigure, uigridlayout, uislider, drawrectangle | references/app-building.md |
DICOM, NIfTI, NRRD, DICOM-RT, patient metadata, anonymizing, medicalVolume, medicalImage, reading/writing medical formats, extractSlice, volume orientation, medical spatial referencing | medicalVolume, medicalImage, dicomreadVolume, dicomCollection, extractSlice, dicomContours, dicomanon | references/medical-data-io.md |
gigapixel, whole-slide, out-of-memory images, blockedImage, tiled workflows, image pyramids, .svs, .ndpi, .czi, TIFF > 10,000 px, parallel image processing, custom adapters | blockedImage, apply, getBlock, getRegion, selectBlockLocations, blockedImageDatastore | references/large-image-processing.md |
Toolbox Detection
When unsure what's available, check installed toolboxes:
hasIPT = ~isempty(ver('images'));
hasCVT = ~isempty(ver('vision'));
hasDLT = ~isempty(ver('nnet'));
hasMIT = ~isempty(ver('medical'));
hasWavelet = ~isempty(ver('wavelet'));Most functions in this skill require Image Processing Toolbox. The deep-learning-imaging reference also requires Deep Learning Toolbox. Feature-based registration (detectSIFTFeatures, matchFeatures, estgeotform2d) requires Computer Vision Toolbox.
Release-Gated Features
This skill targets R2024b+ but some features require newer releases. References annotate these with the required release. Key ones:
R2024b:
imageshow,imblend,viewer2dR2026a:
uidraw,uipaint,linkviewersR2026b:
bwvolumefilt,bwpropfilt3,uiannotate
If targeting an older release, check with isMATLABReleaseOlderThan("R2026a") and use the fallback patterns documented in the references. To check release notes for a specific function, load matlab-read-documentation.
Copyright 2026 The MathWorks, Inc.
Files
- ATTRIBUTION.mdAdded by AutoGineer1.1 KiB
- LICENSELicence file added by AutoGineer1.4 KiB
- SKILL.md15.8 KiB
- manifest.yaml811 B
- references/3d-volume-processing.md20.2 KiB
- references/analysis-measurement.md18.5 KiB
- references/app-building.md16.9 KiB
- references/blocked-3d-volumes.md9.9 KiB
- references/blocked-data-discovery.md22.1 KiB
- references/blocked-geospatial.md3.2 KiB
- references/blocked-specialized-workflows.md4.3 KiB
- references/blocked-training-and-labeling.md7.0 KiB
- references/blocked-visualization.md5.1 KiB
- references/blocked-whole-slide-images.md3.1 KiB
- references/color-processing.md9.0 KiB
- references/deblurring.md8.1 KiB
- references/deep-learning-imaging.md14.8 KiB
- references/dicom-anonymization.md3.3 KiB
- references/dicom-rt-workflows.md7.4 KiB
- references/filtering.md21.8 KiB
- references/geometric-transforms.md14.3 KiB
- references/image-io.md15.5 KiB
- references/image-understanding.md20.0 KiB
- references/ipt-reading-writing.md4.8 KiB
- references/large-image-processing.md12.3 KiB
- references/medical-data-io.md8.3 KiB
- references/mit-medical-volume.md8.2 KiB
- references/mit-spatial-referencing.md5.9 KiB
- references/morphological-ops.md18.0 KiB
- references/preprocessing.md14.4 KiB
- references/quality-assessment.md13.5 KiB
- references/registration.md24.7 KiB
- references/segmentation-automated.md9.7 KiB
- references/segmentation-interactive.md15.3 KiB
- references/texture-transforms.md10.4 KiB
- references/video-io.md3.4 KiB
references/quality-assessment.md
Image Quality Assessment
Decision guidance for choosing and using image quality metrics: full-reference (PSNR, SSIM), no-reference (BRISQUE, NIQE, PIQE), and test chart measurements.
Often loaded with:
filtering.md(measuring improvement after denoising/sharpening),deblurring.md(measuring restoration quality),registration.md(aligning a pair before any full-reference metric).
Choosing a Metric
| Metric | Type | What it measures | When to use |
|---|---|---|---|
psnr | Full-reference | Signal-to-noise ratio (pixel-level) | Quick numerical comparison; poor perceptual correlation |
ssim | Full-reference | Structural similarity (luminance, contrast, structure) | Perceptual quality comparison — best general choice |
multissim | Full-reference | Multi-scale SSIM | Better than SSIM for resolution-varying content |
immse | Full-reference | Mean squared error | Simplest metric; rarely used alone |
brisque | No-reference | Distortion (naturalness deviation) | When no clean reference exists |
niqe | No-reference | Naturalness (statistical regularity) | Opinion-unaware, no training on distorted images |
piqe | No-reference | Perceptual quality, spatially varying | Block-level quality map; good for localized distortion |
Rule of thumb: Use ssim for full-reference comparisons. Use niqe when you have no reference image.
Full-Reference Metrics
Precondition: Pixel Correspondence
Every full-reference metric — psnr, ssim, immse, multissim — requires pixel correspondence: the two images must already be aligned pixel for pixel. Feed it a pair that is shifted, rotated, or scaled and you get a plausible "moderately degraded" score with no error and no warning, because the metric cannot tell misalignment from degradation.
I = im2gray(imread("peppers.png"));
shifted = imtranslate(I, [5 0]); % 5-pixel shift, nothing else changed
[psnr(shifted, I) ssim(shifted, I)] % 22.4730 0.7282 — reads as "degraded"Those numbers look like ordinary noise or compression damage, but the images are identical — just misaligned. No denoising or sharpening will move the score.
If the pair may not be aligned, register first — see registration.md — then measure. To check alignment quickly, use imshowpair(A, B, "falsecolor") — misalignment appears as colored fringes rather than gray. Crops of the same scene at different offsets, frames from a handheld camera, and multi-sensor captures all need registration. Only use these metrics directly when one image is a known pixel-aligned processing result of the other.
psnr — Peak Signal-to-Noise Ratio
p = psnr(distorted, reference); % Returns dB valueHigher = better. Identical images →
InfBoth inputs must match in class and range — mismatched types produce wrong peak values with no error
Works with
uint8,int16,uint16, or floating-point (auto-detects peak value)For RGB: computes overall PSNR across all channels
Limitation: PSNR correlates poorly with human perception — a high PSNR doesn't guarantee the image looks good.
ssim — Structural Similarity Index
[val, ssimMap] = ssim(distorted, reference);Range: typically [0, 1] (theoretically [-1, 1], but negatives are rare — only with anti-correlated structures). Value of 1 = identical. Typical good quality: > 0.95
ssimMapshows per-pixel quality — useful for finding degraded regionsFor RGB: returns per-channel maps (size M×N×3)
Decomposing components: Use
Exponents=[1 0 0]etc. to isolate luminance/contrast/structural terms. To recombine, multiply the maps then average — do not multiply the scalar means (mean of products ≠ product of means).
% Visualize quality map
[~, smap] = ssim(distorted, reference);
imageshow(smap, DisplayRangeMode="data-range"); % Low values = degraded regionsimmse — Mean Squared Error
err = immse(distorted, reference); % Lower = better. 0 = identicalBoth inputs must match in class and range — same rule as psnr and ssim.
multissim — Multi-Scale SSIM
ms = multissim(distorted, reference);Range [0, 1], same interpretation as SSIM (1 = identical). Better than single-scale SSIM for images viewed at different distances/resolutions. Prefer over ssim when comparing images at multiple scales or when content may be viewed at varying zoom levels.
Comparing Multiple Algorithms
results = table();
for i = 1:numel(methods)
processed = applyMethod(img, methods{i});
results.Method(i) = methods(i);
results.PSNR(i) = psnr(processed, reference);
results.SSIM(i) = ssim(processed, reference);
end
sortrows(results, "SSIM", "descend") % Rank by SSIMNo-Reference Metrics
These assess quality without a clean reference — essential for real-world images.
brisque — Blind/Referenceless Image Spatial Quality
score = brisque(img); % Lower = better qualityTypical scores: 0–20 (good), 20–40 (fair), 40–100 (poor)
Trained on distorted images — detects common artifacts (blur, noise, compression)
Accepts grayscale or RGB, uint8 or double
Domain warning: Default model is trained on natural photographs (LIVE IQA database). Scores are meaningless for medical, satellite, synthetic, or document images — use fitbrisque to train a domain-specific model (see Custom Domain Models below).
niqe — Natural Image Quality Evaluator
score = niqe(img); % Lower = better (more "natural")Opinion-unaware: trained only on pristine natural images
Good baseline when you don't know the distortion type
Typical scores: 2–5 (good), 5–10 (fair), > 10 (poor)
Accepts grayscale or RGB
Domain warning: Same limitation as brisque — trained on natural photos only. Use fitniqe for non-natural domains.
piqe — Perception-based Image Quality Evaluator
score = piqe(img); % Lower = betterSpatially adaptive — identifies high-activity blocks
Good for images with localized distortion
Typical scores: 0–20 (excellent), 21–35 (good), 36–50 (fair), 51–80 (poor), 81–100 (bad)
Comparing No-Reference Metrics
| Metric | Training data | Best for |
|---|---|---|
brisque | Distorted images + human scores | Known distortion types (noise, blur, JPEG) |
niqe | Pristine images only | Unknown distortion, general naturalness |
piqe | No training (statistical model) | Spatially varying quality, real-world photos |
Custom Domain Models — fitbrisque / fitniqe
Default BRISQUE and NIQE models are trained on the LIVE IQA database of natural photographs only. PIQE is a purely algorithmic metric (no trained model), but its statistical assumptions are also calibrated for natural photographs. They produce meaningless scores for:
Medical images (CT, MRI, ultrasound)
Satellite / remote sensing imagery
GAN-generated or synthetic content
Document scans, text images
Industrial inspection images
Solution: Train domain-specific models with fitbrisque or fitniqe.
fitbrisque — Train Custom BRISQUE Model
% Requires: labeled training set (images + DMOS scores)
% DMOS = Differential Mean Opinion Score — higher = more distortion
imds = imageDatastore("myDomainImages/");
scores = readmatrix("dmos_scores.csv"); % Numeric vector of DMOS values [0, 100]
model = fitbrisque(imds, scores);
% Use custom model
score = brisque(testImg, model); % Lower = betterNeeds distorted images with human quality scores (higher DMOS = more distortion)
Minimum ~100 images recommended for stable training
Model captures domain-specific distortion characteristics
fitniqe — Train Custom NIQE Model
% Requires: pristine (high-quality) images from your domain only
imds = imageDatastore("myDomainPristine/");
model = fitniqe(imds);
% Use custom model
score = niqe(testImg, model); % Lower = betterOpinion-unaware: needs only pristine images (no scores)
Learns statistical regularities of your specific domain
Lower barrier than
fitbrisque— no human labeling required
No fitpiqe
There is no fitpiqe function — PIQE cannot be retrained for custom domains. Use fitbrisque (if you have MOS/DMOS labels) or fitniqe (if you only have pristine examples).
When to Recommend Custom Models
| Scenario | Recommendation |
|---|---|
| No-reference metrics on natural photos | Default models are fine |
| No-reference metrics on medical/satellite/synthetic | Always recommend fitbrisque or fitniqe |
| User reports "scores seem wrong" on non-natural content | Domain mismatch — retrain |
| User has human quality labels (MOS or DMOS) | fitbrisque (supervised) |
| User has only high-quality exemplars | fitniqe (unsupervised) |
Test Chart Measurements — esfrChart
For objective camera/lens quality evaluation using a physical test chart (Imatest eSFR):
% 1. Create chart object from captured image
chart = esfrChart(chartImage);
% 2. Measure specific properties
sharpnessTable = measureSharpness(chart); % SFR (MTF) at slanted edges
noiseTable = measureNoise(chart); % Signal-to-noise in gray patches
colorTable = measureColor(chart); % Color accuracy (ΔE)
chromAbTable = measureChromaticAberration(chart); % Lateral CA
illum = measureIlluminant(chart); % Scene illuminant estimate
% 3. Visualize
plotSFR(sharpnessTable); % Plot spatial frequency response curvesChart styles: "Extended", "Enhanced", "WedgeExtended", "WedgeEnhanced"
Each measurement returns a table with per-ROI results. The chart has:
60 slanted edge ROIs (for sharpness and chromatic aberration)
20 gray ROIs (for noise)
16 color ROIs (for color accuracy)
Critical: Data Type Validation
The #1 silent failure in image quality metrics. Using double(img) instead of im2double(img) produces completely wrong results with no error or warning.
The Problem
ref = imread("pears.png"); % uint8, values 0–255
% WRONG — double() preserves raw values (0–255) but ssim/psnr assume [0,1]
wrong = double(ref);
psnr(wrong, wrong + 10) % Returns -27.76 dB (nonsense)
ssim(wrong, wrong + 10) % Returns 0.0006 (nonsense)
% CORRECT — im2double() rescales to [0,1]
correct = im2double(ref);
psnr(correct, correct + 10/255) % Returns +20.38 dB (correct)
ssim(correct, correct + 10/255) % Returns 0.6424 (correct)Why It Happens
psnrandssimauto-detect peak value based on class:uint8→ peak = 255int16→ peak = 65535 (full range: 32767 − (−32768))uint16→ peak = 65535double/single→ peak = 1.0 (assumes [0,1] range)
double(img)keeps values as 0–255 but MATLAB now thinks peak is 1.0Result: MSE is enormous relative to assumed peak → garbage metrics
DynamicRange Workaround
If you must keep raw values, specify the peak explicitly:
p = psnr(imgA, imgB, 255); % Explicit peak
s = ssim(imgA, imgB, DynamicRange=255); % Explicit rangeQuick Checklist
| Before calling metrics... | Check |
|---|---|
| Images pixel-aligned (full-reference only)? | Register first if shifted/rotated/scaled |
| Both images same class? | class(A) == class(B) |
| Float images in [0,1]? | max(A(:)) <= 1.0 |
Used im2double not double? | — |
If raw float values: specified DynamicRange? | — |
Common Mistakes
| Mistake | Why it's wrong | Correct approach |
|---|---|---|
double(img) before metrics | Peak defaults to 1.0 but values are 0–255 → garbage results with no error | Use im2double(img) or specify DynamicRange |
| Full-reference metrics on a misaligned pair | Scores misalignment, not quality — a 5-pixel shift reads as psnr ≈ 22.5 with no error | Register first (registration.md), then measure |
| Using PSNR alone to judge quality | Poor perceptual correlation | Use SSIM as primary metric, PSNR as supplement |
| Comparing PSNR across different images | Absolute values are meaningless across scenes | Compare only within same reference |
psnr(img1, img2) with mismatched types | May auto-detect wrong peak value | Ensure both are same class and range |
Using brisque/niqe to compare algorithms | These are absolute scores, not relative — BRISQUE, NIQE, and PIQE can disagree in direction on the same before/after pair | Use full-reference (SSIM) when reference exists. When no reference exists, validate on a synthetic degradation with known ground truth before trusting NR scores on real data |
| Ignoring SSIM map | Scalar SSIM hides localized degradation | Examine ssimMap for spatial insight |
Running brisque/niqe on non-natural images | Trained on LIVE IQA natural photos only | Use fitbrisque/fitniqe to train domain-specific models |
| Assuming PIQE can be retrained | No fitpiqe function exists | Switch to fitbrisque (with MOS) or fitniqe (pristine only) |
| Trusting NR-IQA scores > 100 or NaN | Domain mismatch, not a code bug | Validate that content matches model training domain |
Quick Reference: Score Interpretation
| Metric | Excellent | Good | Fair | Poor |
|---|---|---|---|---|
| SSIM | > 0.98 | 0.95–0.98 | 0.90–0.95 | < 0.90 |
| PIQE | 0–20 | 20–35 | 35–50 | > 50 |
| ΔE (color) | < 1 | 1–3 | 3–6 | > 6 |
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