Matlab Analyze Spectral Images
MathWorksOfficialCreated by MathWorks
- Skill
- Tool integration
- Science and research
- BSD-2-Clause
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a comprehensive interface for working with hyperspectral and multispectral data within the MATLAB environment. It covers the entire lifecycle of spectral imaging, including data ingestion from various formats (ENVI, NITF, TIFF, Sentinel-2, Landsat, ASTER), radiometric calibration, atmospheric correction, and advanced analytical techniques such as spectral unmixing, anomaly detection, and spectral index calculation. The skill also supports modern deep learning workflows, including pixel classification with 3D CNNs and semantic segmentation, as well as interactive labeling via the Spectral Image Labeler app.
What it does
- Reads and writes industry-standard spectral image formats like ENVI, NITF, and GeoTIFF.
- Performs radiometric calibration and atmospheric correction on raw spectral data.
- Executes advanced spectral analysis including endmember extraction, unmixing, and target detection.
- Computes standard and custom spectral indices like NDVI and EVI using optimized built-in functions.
- Facilitates spectral-aware image segmentation and clustering.
- Supports deep learning pipelines for pixel classification and semantic segmentation of spectral cubes.
When to use it
- When processing hyperspectral or multispectral satellite or airborne imagery.
- When performing quantitative analysis on spectral signatures using ECOSTRESS libraries.
- When building deep learning models for spectral image classification or unmixing.
- When needing to compute spectral indices or perform anomaly detection on hypercubes.
- When managing large-scale spectral data with block processing requirements.
Advantages
- Optimized built-in functions for spectral indices and processing, avoiding manual computation errors.
- Seamless integration with MATLAB's deep learning and image processing toolboxes.
- Native support for complex spectral data structures and metadata management.
- Includes specialized apps for interactive labeling and visualization of high-dimensional data.
Usage examples
- “Read a hyperspectral image from an ENVI file and calculate the NDVI.”
- The agent provides code to load the file using imhypercube and compute the index using the built-in ndvi function.
- “How do I perform anomaly detection on my hyperspectral cube?”
- The agent provides the syntax for anomalyRX to identify anomalous pixels within the spectral data.
- “Extract endmembers from my hyperspectral data.”
- The agent provides a workflow using countEndmembersHFC to determine the number of endmembers followed by nfindr for extraction.
- “How can I visualize my multispectral cube as a true-color image?”
- The agent provides the colorize function syntax with the appropriate method parameter for multicube visualization.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/matlab/matlab-analyze-spectral-images/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip matlab-analyze-spectral-images.zip -d .agents/skills
Documentation by MathWorks
Spectral Imaging Skill
Generate MATLAB code for working with hyperspectral and multispectral data using the Hyperspectral Imaging Library for Image Processing Toolbox. Requires desktop MATLAB (not MATLAB Online or MATLAB Mobile) and the Hyperspectral Imaging Library add-on.
When to Use
Reading/writing hyperspectral or multispectral images (ENVI, NITF, GeoTIFF, TIFF, ASTER, Sentinel-2, Landsat)
Reading ECOSTRESS spectral library signatures (
readEcostressSig)Creating hypercube/multicube objects, band selection, cropping, block processing
Radiometric calibration, atmospheric correction, spectral correction
Denoising, sharpening, dimensionality reduction (PCA, MNF)
Endmember extraction, spectral unmixing, abundance estimation
Spectral matching, target detection, anomaly detection
Computing spectral indices (NDVI, EVI, custom)
Segmentation (spectral clustering, superpixels, ISODATA)
Labeling with the Spectral Image Labeler app
Creating ground truth objects for spectral labeling
Deep learning classification or unmixing of spectral images
Semantic segmentation of multispectral satellite imagery (DeepLabV3+ with multi-channel input)
When NOT to Use
General image reading/writing (use
imread/imwrite)Non-spectral 3-D volume data (use Medical Imaging or Image Processing Toolbox)
General image classification not involving spectral cubes (use Deep Learning Toolbox)
Non-spectral semantic segmentation of RGB/grayscale images (use Computer Vision Toolbox)
Point spectra or spectral libraries without spatial dimensions
Prerequisite Check
If you suspect the Hyperspectral Imaging Library might not be installed (e.g., user reports errors), verify with exist('imhypercube','file'). If not installed, suggest installing via Add-On Explorer and fall back to multibandread/imread. Do NOT run this check if you are confident the library is available.
Quick Start
% Read hyperspectral data
hcube = imhypercube("scene.hdr");
% Visualize — colorize syntax (NO name-value for basic usage):
falseColor = colorize(hcube); % false-colored image (default, 3 most informative bands)
rgb = colorize(hcube, Method="rgb"); % true RGB (hypercube ONLY — needs R/G/B wavelengths)
cir = colorize(hcube, Method="cir"); % color infrared (hypercube ONLY)
custom = colorize(hcube, [30 20 10]); % false color from specific band INDICES (not wavelengths)
imshow(falseColor)
% Radiometric pipeline
hcube = dn2radiance(hcube);
hcube = radiance2Reflectance(hcube);
hcube = fastInScene(hcube);
% Compute NDVI
ndviMap = ndvi(hcube);
% Endmember extraction and unmixing
numEM = countEndmembersHFC(hcube);
endmembers = nfindr(hcube, numEM);
abundance = estimateAbundanceLS(hcube, endmembers, Method="fcls");
% Anomaly detection
rxScore = anomalyRX(hcube);
% Segmentation
L = hyperseganchor(hcube, 8);
% Launch viewer app
hyperspectralViewer(hcube)
% Launch labeler app (Since R2026a)
spectralImageLabeler(hcube)Essential Syntax (use without reading reference files)
colorize — Visualization
% HYPERCUBE (supports Method, 2 outputs, ContrastStretching default=false)
falseColor = colorize(hcube) % false-colored (default)
rgb = colorize(hcube, Method="rgb") % true color RGB
cir = colorize(hcube, Method="cir") % color infrared
custom = colorize(hcube, [b1 b2 b3]) % 3 band indices
[img, indices] = colorize(hcube) % also get band indices used
img = colorize(hcube, ContrastStretching=true) % with CLAHE
% MULTICUBE (NO Method param, 1 output, ContrastStretching default=true)
rgb = colorize(mcube) % true RGB (auto-selects by wavelength)
custom = colorize(mcube, [b1 b2 b3]) % false color from band indices
img = colorize(mcube, ContrastStretching=false) % disable contrast stretchingI/O and Band Management
hcube = imhypercube("file.hdr"); % read ENVI/NITF/TIFF
mcube = immulticube("MTL.txt"); % read Landsat (pass *_MTL.txt file)
mcube = immulticube("manifest.safe"); % read Sentinel-2 (pass manifest.safe file, NOT .SAFE folder)
mcube = immulticube("AST_L1T.hdf"); % read ASTER HDF
cropped = cropData(hcube, 30:110, 30:110); % row indices, col indices (NOT [x y w h])
vnir = selectBands(hcube, Wavelength=[400 1000]); % by wavelength range
subset = selectBands(hcube, BandNumber=[1 10 20]); % by band index
cleaned = removeBands(hcube, Wavelength=[1350 1450]); % remove wavelength range
data = gather(hcube); % get M-by-N-by-C numeric array
% ACCESSING DIMENSIONS — NO NumRows/NumColumns/NumBands properties exist:
height = hcube.Metadata.Height; % number of rows (M)
width = hcube.Metadata.Width; % number of columns (N)
bands = hcube.Metadata.Bands; % number of spectral bands (C)
% For multicube: use mcube.BandSize(1,1) for height, mcube.BandSize(1,2) for width
% RESAMPLING vs SELECTING (multicube only):
mcubeUniform = resampleBands(mcube, 30); % RESAMPLE all bands TO 30m (keeps ALL bands, changes spatial size)
mcubeUniform = resampleBands(mcube, 30, Method="bilinear"); % interpolation: "nearest"(default),"bilinear","cubic"
mcube30m = selectBands(mcube, "DataResolution", 30); % KEEP only bands already at 30m (DISCARDS others)
% When asked to "resample" or "match resolution" → use resampleBands
% When asked to "select" or "filter" bands by resolution → use selectBandsSpectral Indices (NEVER compute manually — use built-in functions)
% NDVI — use built-in ndvi() function (supports block processing natively)
ndviMap = ndvi(spcube); % direct numeric M-by-N output, range [-1,1]
ndviMap = ndvi(spcube, BlockSize=[512 512]); % with block processing for large data
% Standard indices — use spectralIndices() (returns struct with .IndexName and .IndexImage)
indices = spectralIndices(spcube, "NDVI"); % single index → struct
indices = spectralIndices(spcube, ["NDVI","EVI"]); % multiple → struct array
indices = spectralIndices(spcube, "all"); % all 16 supported indices
indices = spectralIndices(spcube, "NDVI", BlockSize=[512 512]); % with block processing
% Supported: "NDVI","EVI","NDBI","NBR","MNDWI","MSI","GVI","OSAVI","SR","CMR","MCARI","MTVI","PRI","NDNI","NDMI","CAI"
% Custom formula — use customSpectralIndex() (3 required args: cube, wavelengths, @func)
indexImage = customSpectralIndex(spcube, [800 670], @(nir,red) (nir-red)./(nir+red));
indexImage = customSpectralIndex(spcube, [800 670 475], @(nir,red,blue) 2.5*(nir-red)./(nir+6*red-7.5*blue+1));
indexImage = customSpectralIndex(spcube, [560 1650], @(g,swir) (g-swir)./(g+swir), BlockSize=[512 512]);
% DO NOT manually extract bands and compute — always use these built-in functionsDetection, Matching, and Processing
% Target detection — method is POSITIONAL (3rd arg, not Name=Value)
target = resampleSignature(libData(1), hcube.Wavelength); % resample library spectrum to cube wavelengths
score = detectTarget(hcube, target, "ACE"); % "CEM","ACE","SignedACE","MF","GLRT","AMSD","OSP"
rxScore = anomalyRX(hcube); % higher = more anomalous
% Similarity scores — cube first, reference second (lower = better match)
score = sam(hcube, refSpectrum); % spectral angle mapper [0, pi]
score = sid(hcube, refSpectrum); % spectral information divergence
% spectralMatch — UNUSUAL ARG ORDER: library struct FIRST, then cube/spectrum
% DO NOT pass numeric vectors — first arg MUST be a struct with .Reflectance and .Wavelength fields
libData = readEcostressSig("vegetation.txt"); % returns 1-by-K struct array
score = spectralMatch(libData, hcube); % returns M-by-N-by-K (one score map per signature)
score = spectralMatch(libData, hcube, Method="sam");% "sam"(default),"sid","sidsam","jmsam","ns3"
score = spectralMatch(libData, reflectance, wavelength); % compare against single spectrum (returns K-vector)
% Lower score = stronger match. Returns NaN when bandwidth overlap < MinBandWidth (default 300nm)
% For direct numeric comparison without library: use sam(hcube, target) or sid(hcube, target)
% Spectral clustering / segmentation (use INSTEAD of kmeans for spectral data)
L = hyperseganchor(hcube, numClusters); % spectral-aware clustering (1 output)
[L, n] = hyperslic(hcube, K); % spectral superpixels (2 outputs)
% Block processing — callback receives OBJECT, must use gather()
result = apply(hcube, @(block) mean(gather(block), 3));Workflow
For functions fully documented in the Essential Syntax and Common Mistakes sections above, generate code directly — those sections provide complete API signatures and constraints.
Read a reference file ONLY when:
Using a function NOT covered in Essential Syntax (e.g.,
sharc,empiricalLine,sharpencnmf,spectralImageLabeler)Unsure about argument order or constraints for a complex workflow
The task involves the Spectral Image Labeler app or ground truth objects
Reference Files (consult only when needed):
references/spectral-io.md — I/O, band selection, cropping, block processing, colorize, enviwrite
references/spectral-calibration.md — Radiometric calibration, atmospheric correction, spectral correction, denoising, sharpening
references/spectral-analysis.md — PCA/MNF, unmixing, spectral matching, target/anomaly detection, indices, segmentation
references/spectral-deep-learning.md — Labeler app, groundTruthSpectralImage, deep learning pipelines
references/dl-classification.md — 3-D CNN, 1-D CNN, ground truth to training data workflows
references/dl-advanced.md — Unmixing autoencoder, transfer learning, DeepLabV3+ semantic segmentation
CRITICAL: Common Mistakes to Avoid
These are the most frequent errors. Violating any of these will cause runtime failures:
NEVER use
hypercube()— deprecated. Useimhypercube()orgeohypercube().cropData(hcube, 30:110, 30:110)— row/col INDEX VECTORS, not[x y w h]selectBands/removeBandsrequire Name=Value:selectBands(hcube, BandNumber=[1 10 20]),removeBands(hcube, Wavelength=[1350 1450]).removeBandserrors if range outside cube's actual wavelengths.customSpectralIndex(spcube, [800 670], @(nir,red) (nir-red)./(nir+red))— 3 args requiredapply(hcube, @(block) mean(gather(block), 3))— callback receives OBJECT, usegather()inverseProjection(pcaCube, coeff)— data first, coefficients secondspectralMatch(libData, hcube)— struct fromreadEcostressSigFIRST. For numeric: usesam(hcube, target)directly.L = hyperseganchor(hcube, 8)(1 output);[L, n] = hyperslic(hcube, 100)(2 outputs)immulticubedoes NOT support ENVI. Sentinel-2: passmanifest.safe(NOT.SAFEfolder). Landsat:*_MTL.txt. ASTER:.hdf.spectralIndices(hcube, "NDVI")→ struct with.IndexName/.IndexImage. Usendvi(hcube)for numeric.hyperslicwith 3 bands:hyperslic(data, 100, IsInputDimReduced=true). Only params:NumIterations(max 30),IsInputDimReduced. NOCompactness.detectTarget(hcube, target, "ACE")— method is POSITIONAL, not Name=ValuedenoiseNGMeet: needs spatial dims > 16. Crop large images to ≤1024x1024 first.flatField(hcube, [xmin ymin width height])— rect vector, NOT index vectors likecropDatacolorize(mcube)→ true RGB (NOMethodparam!).colorize(mcube, [b1 b2 b3])for false-color.colorize(hcube, Method="rgb")only works on hypercube.resampleBands(mcube, 30)= resizes all bands to target res.selectBands(mcube, "DataResolution", 30)= keeps only bands already at that res.NO
NumRows/NumColumns/NumBandsproperties. Usehcube.Metadata.Height/Width/Bands. Multicube:mcube.BandSize(1,1)/mcube.BandSize(1,2).NEVER manually compute indices. Use
ndvi(spcube),spectralIndices(spcube, "NDVI"), orcustomSpectralIndex(spcube, [wl1 wl2], @(b1,b2) formula).sam/sidrefSpectra must be C-element VECTOR, not matrix.assignData(hcube, rows, cols, bands, data)— 5 args with index rangesenviwrite(hcube, "output")— hypercube ONLY, not multicubegroundTruthSpectralImagelabelDefs: 6 columns required includingAttributeList. Property:LabelDefinitions(plural).
Key Rules
Pipeline: DN → radiance → reflectance → atmospheric correction. Smile correction BEFORE denoising.
L2 products already have surface reflectance — DN pipeline is for L1 only.
Research datasets (Indian Pines, PaviaU) lack calibration metadata.
hypercube ONLY:
denoiseNGMeet,hyperpca,hypermnf,inverseProjection,sharpencnmf,countEndmembersHFC,nfindr,ppi,estimateAbundanceLS,anomalyRX,sam,sid,spectralMatch,hyperslic,sharc,empiricalLine,reduceSmilehypercube + multicube:
dn2radiance,radiance2Reflectance,fastInScene,detectTarget,ndvi,spectralIndices,customSpectralIndex,hyperseganchor+ numeric array:
flatField,iarr,logResiduals,subtractDarkPixelDeep learning:
trainnet+dlnetwork(nottrainNetwork). Usehyperpcabefore CNN.Valid
spectralIndicesnames: ndvi, osavi, sr, evi, gvi, ndni, pri, cai, mcari, mtvi, msi, cmr, nbr, ndbi, ndmi, mndwi (NOT "ndwi")Labeler (R2026a+):
groundTruthSpectralImageproperties are read-only after creation
Copyright 2026 The MathWorks, Inc.
Files
- ATTRIBUTION.mdAdded by AutoGineer1.1 KiB
- LICENSELicence file added by AutoGineer1.4 KiB
- SKILL.md14.5 KiB
- manifest.yaml498 B
- references/dl-advanced.md7.3 KiB
- references/dl-classification.md7.7 KiB
- references/spectral-analysis.md14.5 KiB
- references/spectral-calibration.md10.0 KiB
- references/spectral-deep-learning.md10.9 KiB
- references/spectral-io.md17.0 KiB
references/spectral-deep-learning.md
Spectral Image Deep Learning Reference
Ground truth labeling and deep learning workflows using the Hyperspectral Imaging Library for Image Processing Toolbox.
Spectral Image Labeler App (Since R2026a)
% Launch
spectralImageLabeler % new session
spectralImageLabeler(spcube) % load hypercube or multicube object
spectralImageLabeler(cube) % load 3-D numeric array (limited features)
spectralImageLabeler(gTruth) % resume from existing groundTruthSpectralImage
spectralImageLabeler close % close all instancesApp Workflow
Load data — from file (formats supported by
imhypercube/immulticube/geohypercube/geomulticube), from workspace, or from MAT file containinggroundTruthSpectralImageVisualize — false color, RGB, CIR, or custom band composites; adjust brightness/contrast
Define labels — create label definitions with name, color, ID, group, description, and attributes (List, Numeric, String, Logical)
Label manually — draw polygon ROIs (click vertices, double-click to close); merge ROIs with Ctrl+select; erase portions
Automate labeling — select built-in or custom algorithm from Automate tab, configure parameters, run, review, undo if needed
Export — to workspace or MAT file as
groundTruthSpectralImage; to TIF image file; to shapefile (if geospatial, requires Mapping Toolbox)
Built-in Automation Algorithms
| Algorithm | Class Name | Type |
|---|---|---|
| K-means Clustering | hyperspectral.labeler.KMeansAutomationAlgorithm | Unsupervised |
| ISODATA Clustering | hyperspectral.labeler.ISODATAAutomationAlgorithm | Unsupervised |
| Anchor Graph Clustering | hyperspectral.labeler.HyperseganchorAutomationAlgorithm | Unsupervised |
| Spectral Indices | hyperspectral.labeler.SpectralIndicesAutomationAlgorithm | Signature-based |
| Spectral Match with ECOSTRESS | hyperspectral.labeler.SpectralMatchWithEcostress | Signature-based |
Blocked Image Support
Large images that exceed memory can be imported as blocked images. Limitations: spectral signature visualization and automated labeling are unavailable for blocked images.
Ground Truth Object (Since R2026a)
Creating groundTruthSpectralImage
gTruth = groundTruthSpectralImage(dataSource, labelDefs)
gTruth = groundTruthSpectralImage(dataSource, labelDefs, labelData)
gTruth = groundTruthSpectralImage(__, Resolution=resolution)Arguments:
dataSource— string/char file path (preferred) orhyper.labeler.loading.SpectralImageSourceobjectlabelDefs— table with ALL 6 required columns:LabelName(string),LabelColor(1x3, 0–1; use empty [] for auto-assigned),LabelID(integer 1–255; use 0 for auto-assigned),LabelGroup(string, e.g., "None"),Description(string),AttributeList(cell, use {} for no attributes). All columns must be present even if some values are empty.labelData— table where each column matches a label name; each cell contains a scalar struct withROI(polyshape) and optionalROIName(char; auto-assigned if omitted); multiple ROIs per label use multiple rows in the tableResolution— positive integer for multicube band resampling
AttributeList Column Format
Each attribute is a scalar struct. For multiple attributes per label, use cell indexing on the table column:
% Numeric attribute
numAttr.AttributeType = "Numeric";
numAttr.AttributeName = "score";
numAttr.DefaultValue = 10; % numeric scalar or []
numAttr.AttributeDescription = "";
% String attribute
strAttr.AttributeType = "String";
strAttr.AttributeName = "category";
strAttr.DefaultValue = "default";
strAttr.AttributeDescription = "";
% Logical attribute
logAttr.AttributeType = "Logical";
logAttr.AttributeName = "isValid";
logAttr.DefaultValue = true; % logical scalar or 'true'/'false'
logAttr.AttributeDescription = "";
% List attribute
listAttr.AttributeType = "List";
listAttr.AttributeName = "priority";
listAttr.ListItems = {'High'; 'Medium'; 'Low'};
listAttr.AttributeDescription = "";
% Add multiple attributes to labelDefs using cell indexing
labelDefs.AttributeList{1} = numAttr;
labelDefs.AttributeList{1,2} = strAttr;
labelDefs.AttributeList{1,3} = logAttr;Properties (all read-only)
| Property | Type | Description |
|---|---|---|
DataSource | hyper.labeler.loading.SpectralImageSource | Source of spectral image data |
LabelDefinitions | table | Label metadata (LabelName, LabelColor, LabelID, LabelGroup, Description, AttributeList) |
LabelData | table | ROI annotations per label |
Resolution | positive integer or [] | Band resolution for multicube |
SpectralImageSource (Since R2026a)
dataSource = hyper.labeler.loading.SpectralImageSource(filename)filename— path to file supported byimhypercube/geohypercube/immulticube/geomulticube, or MAT file containing a solehypercube/multicubevariableProperty:
Filename(read-only, char) — the resolved file pathAutomatically created internally when you pass a file path string to
groundTruthSpectralImagePreferred pattern: Pass the file path directly to
groundTruthSpectralImage— no need to createSpectralImageSourceexplicitly
Object Functions
% Merge multiple ground truth objects (must share same data source and resolution)
gTruthMerged = merge(gTruth1, gTruth2, ..., gTruthN)
% After merge: ROINames are regenerated to avoid duplicates; LabelIDs are reassigned to be unique
% Select labels by group
gTruthNew = selectLabelsByGroup(gTruth, labelGroups)
% labelGroups: string scalar, string array, char, or cell array of char
% Error: 'hyperspectral:groundTruthSpectralImage:GroupNotFound' if group doesn't exist
% Select labels by name
gTruthNew = selectLabelsByName(gTruth, labelNames)
% labelNames: string scalar, string array, char, or cell array of char
% Error: 'hyperspectral:groundTruthSpectralImage:LabelNameNotFound' if name doesn't exist
% Change file paths (for portability across machines)
unresolvedPaths = changeFilePaths(gTruth, alternateFilePaths)
% gTruth: single object or array of groundTruthSpectralImage objects
% alternateFilePaths: n-by-2 string array [currentFolderPath newFolderPath]
% Specify folder paths only (not filenames); data source file must be same
% Returns empty if all paths resolve; otherwise returns unresolved file pathsDeep Learning Workflows
Full workflow code: classification in
references/dl-classification.md, advanced (autoencoder, transfer learning, DeepLabV3+) inreferences/dl-advanced.md.
| Workflow | Description | Key Functions |
|---|---|---|
| 3-D CSCNN Classification | PCA reduction + 25x25 spatial patches + 3-D CNN | hyperpca, trainnet, dlnetwork, image3dInputLayer, convolution3dLayer |
| 1-D Spectral CNN | Per-pixel classification using spectral dimension only | image3dInputLayer([C 1 1]), convolution3dLayer([k 1 1], ...) |
| Ground Truth → Training Data | Convert groundTruthSpectralImage ROIs to pixel masks and patch arrays | poly2mask, gTruth.LabelDefinitions, gTruth.LabelData |
| Unmixing Autoencoder | Self-supervised encoder-decoder for abundance estimation | featureInputLayer, softmaxLayer, "mse" loss, net.Learnables |
| Transfer Learning | PCA to 3 bands + pretrained ResNet-18 fine-tuning | hyperpca(data, 3), imagePretrainedNetwork, replaceLayer |
| Semantic Segmentation (DeepLabV3+) | Full-tile segmentation of multispectral satellite imagery | deeplabv3plus, replaceLayer, pixelLabelDatastore, semanticseg, evaluateSemanticSegmentation, focalCrossEntropy |
Key API Pattern
% Modern training pipeline (use for all DL workflows)
net = dlnetwork(layers);
options = trainingOptions("adam", MaxEpochs=100, MiniBatchSize=256, ...);
net = trainnet(data, targets, net, "crossentropy", options);
% Modern inference pipeline
scores = minibatchpredict(net, dsTest);
YPred = scores2label(scores, categories(YTest));
accuracy = mean(YPred == YTest);
confusionchart(YTest, YPred);Key Rules
Labeler & Ground Truth
Spectral Image Labeler requires desktop MATLAB (not MATLAB Online/Mobile) and Hyperspectral Imaging Library add-on (Since R2026a)
All
groundTruthSpectralImageproperties are read-only after creationProperty name is
LabelDefinitions(plural with 's'), notLabelDefinitionLabelID,LabelColor, andROINameare auto-assigned if omitted or empty in the inputROIs within the same label must be non-overlapping (error:
OverlapPolyshape)mergerequires all objects share the sameDataSourceandResolution; after merge, ROINames are regenerated and LabelIDs reassigned to be uniquechangeFilePathstakes folder paths only (not filenames); supports arrays of gTruth objects; returns unresolved file paths or empty on successLabel/group/ROI/attribute names must be valid MATLAB variable names
LabelIDrange: 1–255 recommended (higher values work at API level but may cause issues during TIF export)LabelColorrange: 0–1 per channel (auto-assigned if omitted)AttributeListsupports 4 types: Numeric, String, Logical, List — each withAttributeType,AttributeName,AttributeDescription, and eitherDefaultValueorListItemsMultiple attributes per label: use cell indexing
labelDefs.AttributeList{row, col}— NOT struct arrays
Deep Learning Training
Use
trainnet(not deprecatedtrainNetwork) withdlnetworkobjectsUse
minibatchpredictfor inference (not deprecatedpredictonSeriesNetwork/DAGNetwork)Use
scores2labelto convert prediction scores to categorical labelsFor 3-D CNN: input shape is H-by-W-by-D (spectral)-by-Ch (typically 1)-by-N
For 1-D spectral CNN: treat spectrum as a 1-D "image" with
image3dInputLayer([C 1 1])Apply PCA (
hyperpca) before CNN to reduce spectral dimensionality and training timeNormalize per-band by standard deviation for stable training
Use
augmentedImageDatastorefor patch-based training with consistent input sizeUse
arrayDatastore+combinefor custom datastore pipelinesdividerandfor train/val/test splits;cvpartitionfor cross-validation
Unmixing Autoencoders
Softmax layer enforces sum-to-one abundance constraint (physical plausibility)
Decoder weights approximate endmember spectra
Self-supervised: input equals target (reconstruction loss)
Compare against
estimateAbundanceLSwithMethod="fcls"as baselineExtract decoder weights via
net.Learnablesfiltering by layer name and parameter type
Data Preparation
Unlabeled pixels (class 0 or
<undefined>) must be excluded from trainingPatch extraction: zero-pad image borders to handle edge pixels
For transfer learning: reduce to 3 bands via PCA to match pretrained RGB networks
Resize patches to 224x224 for standard pretrained architectures (ResNet, etc.)
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-analyze-spectral-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-analyze-spectral-images.zip