| Title: | Hyperspectral Imaging Analysis for Biomedical Applications |
|---|---|
| Description: | Reads, processes, analyses and visualizes hyperspectral imaging (HSI) data from Cubert snapshot cameras, Diaspective Vision 'TIVITA' recordings and standard 'ENVI' and 'TIFF' files. Provides calibration workflows (dark correction, white reference normalization), spectral preprocessing (Savitzky-Golay smoothing, standard normal variate (SNV), multiplicative scatter correction (MSC), derivatives), dimensionless spectral indices, research haemoglobin fraction fitting, dimensionality reduction (principal component analysis (PCA), minimum noise fraction (MNF)), pixel classification (spectral angle mapper (SAM), support vector machines (SVM), random forest) and constrained spectral unmixing. Includes an interactive 'shiny' explorer, reproducible batch recipes and grouped evaluation tools. Results are research outputs; clinical or device-specific accuracy is not established by the included synthetic examples. |
| Authors: | R. Heller [aut, cre, cph], V. Forstmeier [aut] |
| Maintainer: | R. Heller <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.3.0 |
| Built: | 2026-12-02 08:53:24 UTC |
| Source: | https://github.com/CTTIR/hyperspectR |
Extract spatial and/or spectral subsets from a cube. Subsetting preserves
the hsi_cube class.
## S3 method for class 'hsi_cube' x[i, j, k, ...]## S3 method for class 'hsi_cube' x[i, j, k, ...]
x |
An hsi_cube object. |
i |
Row indices (spatial). |
j |
Column indices (spatial). |
k |
Band indices (spectral). |
... |
Additional arguments (ignored). |
A subsetted hsi_cube object.
cube <- hs_example_cube() sub <- cube[1:10, 1:10, 1:5] dim(sub)cube <- hs_example_cube() sub <- cube[1:10, 1:10, 1:5] dim(sub)
Convert hsi_cube to Tibble
## S3 method for class 'hsi_cube' as_tibble(x, ..., long = TRUE, .name_repair = "unique")## S3 method for class 'hsi_cube' as_tibble(x, ..., long = TRUE, .name_repair = "unique")
x |
An hsi_cube object. |
... |
Additional arguments (ignored). |
long |
Logical. If |
.name_repair |
Name repair strategy (passed to |
cube <- hs_example_cube() tb <- tibble::as_tibble(cube[1:3, 1:3, 1:3]) head(tb)cube <- hs_example_cube() tb <- tibble::as_tibble(cube[1:3, 1:3, 1:3]) head(tb)
Convert hsi_cube to Data Frame
## S3 method for class 'hsi_cube' as.data.frame(x, ..., long = FALSE)## S3 method for class 'hsi_cube' as.data.frame(x, ..., long = FALSE)
x |
An hsi_cube object. |
... |
Additional arguments (ignored). |
long |
Logical. If |
A data.frame. Wide columns are named band_<wavelength> with the
wavelength rounded to whole nm, or the full wavelength when rounding
would give two bands the same name.
cube <- hs_example_cube() df <- as.data.frame(cube[1:3, 1:3, 1:3], long = TRUE) head(df)cube <- hs_example_cube() df <- as.data.frame(cube[1:3, 1:3, 1:3], long = TRUE) head(df)
Creates a ggplot2 visualization of a hyperspectral cube. Supports RGB composite, single-band images, and spectral profile plots.
## S3 method for class 'hsi_cube' autoplot( object, type = c("rgb", "band", "spectra"), band = NULL, wavelength = NULL, r = NULL, g = NULL, b = NULL, ... )## S3 method for class 'hsi_cube' autoplot( object, type = c("rgb", "band", "spectra"), band = NULL, wavelength = NULL, r = NULL, g = NULL, b = NULL, ... )
object |
An hsi_cube object. |
type |
Character. Plot type: |
band |
Integer. Band index for single-band display. Used when
|
wavelength |
Numeric. Wavelength (nm) for single-band display.
Alternative to |
r, g, b
|
Numeric. Wavelengths for RGB channels. Defaults: 640, 550, 460. |
... |
Additional arguments passed to internal plot functions. |
A ggplot2::ggplot object.
cube <- hs_example_cube() ggplot2::autoplot(cube, type = "rgb")cube <- hs_example_cube() ggplot2::autoplot(cube, type = "rgb")
Get Dimensions of an hsi_cube
## S3 method for class 'hsi_cube' dim(x)## S3 method for class 'hsi_cube' dim(x)
x |
An hsi_cube object. |
Integer vector c(rows, cols, bands).
cube <- hs_example_cube() dim(cube)cube <- hs_example_cube() dim(cube)
Computes A(lambda) = -log10(R(lambda)). Values of R at or below zero
are clamped to floor before log transformation.
hs_absorbance(cube, floor = 1e-06)hs_absorbance(cube, floor = 1e-06)
cube |
An hsi_cube object with reflectance values. |
floor |
Numeric. Minimum reflectance value to prevent log(0). Default |
An hsi_cube object with absorbance values.
cube <- hs_example_cube() abs_cube <- hs_absorbance(cube)cube <- hs_example_cube() abs_cube <- hs_absorbance(cube)
A scene-independent, dimensionless ratio of mean spectral values. It is not calibrated oxygen saturation, perfusion, concentration or water content.
hs_band_ratio(cube, numerator, denominator)hs_band_ratio(cube, numerator, denominator)
cube |
An hsi_cube object. |
numerator, denominator
|
Numeric scalar wavelength or two-element range in nm. |
A spatial numeric matrix. Zero denominators and invalid pixels are NA.
cube <- hs_example_cube() ratio <- hs_band_ratio(cube, numerator = c(650, 700), denominator = c(800, 850)) range(ratio, na.rm = TRUE)cube <- hs_example_cube() ratio <- hs_band_ratio(cube, numerator = c(650, 700), denominator = c(800, 850)) range(ratio, na.rm = TRUE)
Each recording is isolated: failures are recorded without discarding successful
results. Resume requires matching input checksums, recipe, analysis parameters,
package implementation, R version and dependency versions, plus an intact
versioned output record. Legacy or damaged records are recomputed. The output
checksum detects accidental changes; it does not authenticate an untrusted
file. Failed recomputation leaves the previous result file unchanged. Input and output
paths are local; no network or hardware acquisition is performed.
TIVITA input identity includes the consumed metadata log and the names/paths
of reference images returned by the reader. Reference image bytes are not
read by the analysis and are not checksummed.
For Cubert sessions, file bytes and explicit reader arguments are tracked,
but external vendor SDK settings and assets are not enumerated. Use
resume = FALSE when that external configuration may have changed.
hs_batch( manifest, recipe = hs_recipe(), out_dir, analysis = c("summary", "beer_lambert", "pca"), analysis_args = list(), resume = TRUE )hs_batch( manifest, recipe = hs_recipe(), out_dir, analysis = c("summary", "beer_lambert", "pca"), analysis_args = list(), resume = TRUE )
manifest |
Data frame with distinct |
recipe |
A recipe from |
out_dir |
Directory for per-recording RDS files and |
analysis |
One of |
analysis_args |
Named list of arguments for the analysis function. |
resume |
Logical. Reuse intact results only if their fingerprint matches. |
Data frame of recording identifiers, statuses, result files and errors.
dir <- file.path(tempdir(), "hs-batch-example") hdr <- hs_example_files(tempdir()) manifest <- data.frame(id = "example", path = hdr) first <- hs_batch(manifest, out_dir = dir) first$status # A second run reuses the intact result hs_batch(manifest, out_dir = dir)$status unlink(dir, recursive = TRUE)dir <- file.path(tempdir(), "hs-batch-example") hdr <- hs_example_files(tempdir()) manifest <- data.frame(id = "example", path = hdr) first <- hs_batch(manifest, out_dir = dir) first$status # A second run reuses the intact result hs_batch(manifest, out_dir = dir)$status unlink(dir, recursive = TRUE)
Fits decadic absorbance to reference extinction coefficients with NNLS. Without a known optical pathlength, coefficients are concentration-pathlength products. The haemoglobin fraction is a research model estimate; diffuse tissue scattering and camera response can bias it.
hs_beer_lambert( cube, chromophores = c("HbO2", "Hb"), wavelength_range = c(500, 600), input = c("auto", "reflectance", "absorbance"), pathlength_cm = NULL, response = c("point", "gaussian"), keep_residuals = FALSE )hs_beer_lambert( cube, chromophores = c("HbO2", "Hb"), wavelength_range = c(500, 600), input = c("auto", "reflectance", "absorbance"), pathlength_cm = NULL, response = c("point", "gaussian"), keep_residuals = FALSE )
cube |
An hsi_cube object with an explicit reflectance or absorbance domain. |
chromophores |
Character vector. Default |
wavelength_range |
Numeric vector of length 2. Fitting range.
Default |
input |
|
pathlength_cm |
Positive scalar optical pathlength, or NULL (unknown). |
response |
|
keep_residuals |
Logical. Retain spectral residuals. Default FALSE. |
A list with class "hsi_chromophore_fit":
Named matrices of concentration-pathlength products (mol/L * cm).
Named matrices in mol/L when pathlength is supplied; otherwise NULL.
Matrix of oxygen saturation = HbO2 / (HbO2 + Hb) * 100.
Sum of HbO2 and Hb concentration-pathlength products.
Matrix of fit residuals.
cube <- hs_example_cube() fit <- hs_beer_lambert(cube) range(fit$sto2, na.rm = TRUE)cube <- hs_example_cube() fit <- hs_beer_lambert(cube) range(fit$sto2, na.rm = TRUE)
Applies dark current subtraction and white reference normalization:
R(x,y,lambda) = (raw - dark) / (white - dark). Values are clamped to
[0, 1] unless clamp = FALSE. Nonfinite input or intermediate values
remain missing and are recorded as invalid; clamping never repairs them.
hs_calibrate(cube, dark, white, clamp = TRUE, saturation = NULL)hs_calibrate(cube, dark, white, clamp = TRUE, saturation = NULL)
cube |
An hsi_cube object with raw data. |
dark |
An hsi_cube object or 3D array representing the dark reference (lens cap measurement). |
white |
An hsi_cube object or 3D array representing the white reference (Spectralon panel measurement). |
clamp |
Logical. Clamp output to |
saturation |
Optional finite saturation threshold in raw data units.
Defaults to |
An hsi_cube object with reflectance values.
cube <- hs_simulate_cube(rows = 10, cols = 10, noise_sd = 0) dark <- hsi_cube(array(0.01, dim(cube$data)), cube$wavelengths) white <- hsi_cube(array(0.95, dim(cube$data)), cube$wavelengths) cal <- hs_calibrate(cube, dark, white) range(cal$data)cube <- hs_simulate_cube(rows = 10, cols = 10, noise_sd = 0) dark <- hsi_cube(array(0.01, dim(cube$data)), cube$wavelengths) white <- hsi_cube(array(0.95, dim(cube$data)), cube$wavelengths) cal <- hs_calibrate(cube, dark, white) range(cal$data)
Returns a pinned tabulation of decadic molar extinction coefficients for haemoglobin, compiled by Prahl and distributed with MNE-Python v1.10.2. Synthetic shapes are available separately for simulation only.
hs_chromophore_data( chromophore = c("HbO2", "Hb"), wavelength_range = c(400, 1000), source = c("reference", "synthetic") )hs_chromophore_data( chromophore = c("HbO2", "Hb"), wavelength_range = c(400, 1000), source = c("reference", "synthetic") )
chromophore |
Character vector. One or more of:
|
wavelength_range |
Numeric vector of length 2. Wavelength range in nm.
Default |
source |
|
A tibble::tibble with columns wavelength (nm) and one column per
requested chromophore (extinction coefficient in cm^-1 / (mol/L)).
hb_data <- hs_chromophore_data() head(hb_data)hb_data <- hs_chromophore_data() head(hb_data)
Trains a random forest on labelled pixels and classifies all pixels.
Requires the ranger package.
hs_classify_rf( cube, training_labels, training_mask = NULL, num.trees = 500L, mtry = NULL, ... )hs_classify_rf( cube, training_labels, training_mask = NULL, num.trees = 500L, mtry = NULL, ... )
cube |
An hsi_cube object. |
training_labels |
Character or factor matrix with class labels.
|
training_mask |
Logical matrix. Default |
num.trees |
Integer. Number of trees. Default |
mtry |
Integer. Variables per split. Default |
... |
Additional arguments passed to |
A list with class "hsi_classification" containing class_map.
# Requires ranger package cube <- hs_example_cube() labels <- matrix(NA_character_, 30, 30) labels[1:10, 1:10] <- "class_a" labels[20:30, 20:30] <- "class_b" if (requireNamespace("ranger", quietly = TRUE)) { result <- hs_classify_rf(cube, labels) }# Requires ranger package cube <- hs_example_cube() labels <- matrix(NA_character_, 30, 30) labels[1:10, 1:10] <- "class_a" labels[20:30, 20:30] <- "class_b" if (requireNamespace("ranger", quietly = TRUE)) { result <- hs_classify_rf(cube, labels) }
Trains a Support Vector Machine on labelled pixels and classifies all pixels.
Requires the e1071 package.
hs_classify_svm( cube, training_labels, training_mask = NULL, kernel = "radial", cost = 10, gamma = NULL, ... )hs_classify_svm( cube, training_labels, training_mask = NULL, kernel = "radial", cost = 10, gamma = NULL, ... )
cube |
An hsi_cube object. |
training_labels |
Character or factor matrix (same spatial dims as cube)
with class labels. |
training_mask |
Logical matrix. Alternative to NA in labels. Default |
kernel |
Character. SVM kernel: |
cost |
Numeric. Cost parameter. Default |
gamma |
Numeric. Gamma parameter. Default |
... |
Additional arguments passed to |
A list with class "hsi_classification" containing class_map.
# Requires e1071 package cube <- hs_example_cube() labels <- matrix(NA_character_, 30, 30) labels[1:10, 1:10] <- "class_a" labels[20:30, 20:30] <- "class_b" if (requireNamespace("e1071", quietly = TRUE)) { result <- hs_classify_svm(cube, labels) }# Requires e1071 package cube <- hs_example_cube() labels <- matrix(NA_character_, 30, 30) labels[1:10, 1:10] <- "class_a" labels[20:30, 20:30] <- "class_b" if (requireNamespace("e1071", quietly = TRUE)) { result <- hs_classify_svm(cube, labels) }
Convenience function that computes StO2, NPI, THI, and TWI (if wavelength range permits) and returns them as a named list of matrices.
hs_clinical_indices(cube)hs_clinical_indices(cube)
cube |
An hsi_cube object with reflectance data. |
A named list of numeric matrices: sto2, npi, thi, twi
(TWI may be NA matrix if wavelengths are insufficient).
cube <- hs_example_cube() indices <- hs_clinical_indices(cube) names(indices)cube <- hs_example_cube() indices <- hs_clinical_indices(cube) names(indices)
Removes the spectral continuum (convex hull) from each spectrum. Useful for enhancing absorption features and normalizing baseline variations.
hs_continuum_removal(cube, method = c("division", "subtraction"))hs_continuum_removal(cube, method = c("division", "subtraction"))
cube |
An hsi_cube object. |
method |
Character. |
An hsi_cube object with continuum-removed spectra.
Clark, R. N. and Roush, T. L. (1984). Reflectance spectroscopy:
quantitative analysis techniques for remote sensing applications.
Journal of Geophysical Research: Solid Earth, 89(B7), 6329-6340.
doi:10.1029/JB089iB07p06329
cube <- hs_example_cube() cr <- hs_continuum_removal(cube, method = "division")cube <- hs_example_cube() cr <- hs_continuum_removal(cube, method = "division")
Subtracts a dark reference from the cube data.
hs_dark_correct(cube, dark)hs_dark_correct(cube, dark)
cube |
An hsi_cube object. |
dark |
An hsi_cube object or 3D array representing the dark reference. |
An hsi_cube object with dark-corrected values.
cube <- hs_simulate_cube(rows = 10, cols = 10, noise_sd = 0) dark <- hsi_cube(array(0.01, dim(cube$data)), cube$wavelengths) corrected <- hs_dark_correct(cube, dark)cube <- hs_simulate_cube(rows = 10, cols = 10, noise_sd = 0) dark <- hsi_cube(array(0.01, dim(cube$data)), cube$wavelengths) corrected <- hs_dark_correct(cube, dark)
Computes the spectral derivative using Savitzky-Golay differentiation.
Shorthand for hs_smooth() with deriv > 0.
hs_derivative(cube, order = 1L, window = 5L)hs_derivative(cube, order = 1L, window = 5L)
cube |
An hsi_cube object. |
order |
Integer. Derivative order. Default |
window |
Integer (odd). SG window size. Default |
An hsi_cube object with derivative spectra.
cube <- hs_example_cube() d1 <- hs_derivative(cube, order = 1)cube <- hs_example_cube() d1 <- hs_derivative(cube, order = 1)
Extracts endmember spectra from specified pixel locations.
hs_endmembers(cube, pixels, labels = NULL)hs_endmembers(cube, pixels, labels = NULL)
cube |
An hsi_cube object. |
pixels |
Data.frame or matrix with columns |
labels |
Character vector of class labels for each pixel. Default |
A named matrix with endmember spectra (rows = endmembers, cols = bands).
cube <- hs_example_cube() pixels <- data.frame(x = c(5, 25), y = c(5, 25)) em <- hs_endmembers(cube, pixels, labels = c("region_1", "region_2")) dim(em)cube <- hs_example_cube() pixels <- data.frame(x = c(5, 25), y = c(5, 25)) em <- hs_endmembers(cube, pixels, labels = c("region_1", "region_2")) dim(em)
Generates a small pre-configured synthetic cube for quick examples and documentation. The cube simulates a 30x30 pixel tissue scene with four regions of different synthetic spectra. Region names do not identify tissue diagnoses, and the example does not establish quantitative accuracy.
hs_example_cube()hs_example_cube()
An hsi_cube object (30 x 30 x 61 bands, 430-910 nm).
cube <- hs_example_cube() print(cube) dim(cube)cube <- hs_example_cube() print(cube) dim(cube)
Writes a minimal ENVI header + binary pair for testing I/O functions.
hs_example_files(dir = tempdir())hs_example_files(dir = tempdir())
dir |
Character. Directory to write to. Default |
Character. Path to the written .hdr file (invisibly).
hdr_path <- hs_example_files() file.exists(hdr_path)hdr_path <- hs_example_files() file.exists(hdr_path)
Exports a single band or index map from an HSI cube as a PNG image.
hs_export_png( data, path, palette = "viridis", range = NULL, width = NULL, height = NULL )hs_export_png( data, path, palette = "viridis", range = NULL, width = NULL, height = NULL )
data |
Numeric matrix to export (rows x cols). |
path |
Character. Output file path (should end in .png). |
palette |
Character. Colour palette: |
range |
Numeric vector of length 2. Data range for colour mapping.
Default |
width |
Integer. Image width in pixels. Default |
height |
Integer. Image height in pixels. Default |
Invisible path to the written file.
cube <- hs_example_cube() mat <- cube$data[, , 30] path <- file.path(tempdir(), "band30.png") hs_export_png(mat, path)cube <- hs_example_cube() mat <- cube$data[, , 30] path <- file.path(tempdir(), "band30.png") hs_export_png(mat, path)
Identifies dead/hot pixels by statistical deviation from spatial neighbourhood median/MAD and replaces with neighbourhood interpolation. Detection uses the immutable image; replacement excludes every detected defect. Defects occupying most of a neighbourhood may not be distinguishable.
hs_fix_bad_pixels(cube, threshold = 3, method = "median")hs_fix_bad_pixels(cube, threshold = 3, method = "median")
cube |
An hsi_cube object. |
threshold |
Numeric. Robust standard deviation (scaled MAD) threshold.
Default |
method |
Character. Replacement method: |
An hsi_cube object with corrected pixels.
cube <- hs_example_cube() # Introduce a hot pixel cube$data[15, 15, ] <- 999 fixed <- hs_fix_bad_pixels(cube, threshold = 3)cube <- hs_example_cube() # Introduce a hot pixel cube$data[15, 15, ] <- 999 fixed <- hs_fix_bad_pixels(cube, threshold = 3)
First averages observations within each independent group, then computes an equally weighted mean across groups. Bootstrap samples resample whole groups. Pixel or repeated-recording counts do not inflate the independent sample size.
hs_group_summary( data, value = "value", group = "subject_id", bootstrap = 1000L, seed = 1L )hs_group_summary( data, value = "value", group = "subject_id", bootstrap = 1000L, seed = 1L )
data |
Data frame containing a numeric outcome and a group identifier. |
value |
Column name containing the outcome. |
group |
Column name identifying independent subjects or sampling units. |
bootstrap |
Number of bootstrap samples. Default 1000. |
seed |
Random seed. Default 1. |
List containing group means, independent group count, overall estimate, percentile interval and number of excluded nonfinite observations.
roi <- data.frame( subject_id = rep(c("s1", "s2", "s3"), times = c(5, 3, 4)), value = c(0.61, 0.63, 0.60, 0.62, 0.64, 0.55, 0.57, 0.56, 0.70, 0.71, 0.69, 0.72) ) res <- hs_group_summary(roi, bootstrap = 200) res$estimate res$intervalroi <- data.frame( subject_id = rep(c("s1", "s2", "s3"), times = c(5, 3, 4)), value = c(0.61, 0.63, 0.60, 0.62, 0.64, 0.55, 0.57, 0.56, 0.70, 0.71, 0.69, 0.72) ) res <- hs_group_summary(roi, bootstrap = 200) res$estimate res$interval
Splits by subject (or another independent sampling unit), fits preprocessing only on training spectra, and predicts held-out groups. Hyperparameters must be chosen before evaluation; this function does not tune on validation data. Group accuracy is conditional on valid predictions; prediction coverage and unevaluated group counts are reported separately. Per-class recall treats withheld predictions as missed labels. Accuracy intervals resample whole groups, not pixels. These intervals summarize out-of-fold predictions and do not include uncertainty from refitting models.
hs_grouped_evaluate( spectra, wavelengths, labels, groups, folds = NULL, n_folds = 5L, method = c("svm", "rf"), recipe = hs_recipe(), model_args = list(), seed = 1L, bootstrap = 1000L )hs_grouped_evaluate( spectra, wavelengths, labels, groups, folds = NULL, n_folds = 5L, method = c("svm", "rf"), recipe = hs_recipe(), model_args = list(), seed = 1L, bootstrap = 1000L )
spectra |
Numeric matrix, observations in rows and wavelengths in columns. |
wavelengths |
Numeric band centres in nm. |
labels |
Character class labels for each observation. |
groups |
Independent group identifiers, usually subject identifiers. |
folds |
Optional named integer vector mapping every group to a fold. |
n_folds |
Number of folds when no mapping is supplied. Default 5. |
method |
Classifier, |
recipe |
Processing recipe. Learned references are fitted inside each fold. |
model_args |
Named list of fixed classifier parameters. |
seed |
Random seed for fold assignment and model fitting. |
bootstrap |
Number of group bootstrap samples for the accuracy interval. |
List of out-of-fold predictions, group metrics, confusion matrix, group-mean accuracy and interval, fold assignments and fitted recipes.
if (requireNamespace("e1071", quietly = TRUE)) { spectra <- rbind(c(1, 2, 1), c(2, 1, 2), c(1.1, 2, 1), c(2.1, 1, 2), c(1, 2.1, 1), c(2, 1.1, 2), c(1, 2, 1.1), c(2, 1, 2.1)) result <- hs_grouped_evaluate( spectra, wavelengths = c(500, 600, 700), labels = rep(c("a", "b"), 4), groups = rep(letters[1:4], each = 2), n_folds = 2, model_args = list(kernel = "linear"), bootstrap = 50 ) result$accuracy result$group_metrics }if (requireNamespace("e1071", quietly = TRUE)) { spectra <- rbind(c(1, 2, 1), c(2, 1, 2), c(1.1, 2, 1), c(2.1, 1, 2), c(1, 2.1, 1), c(2, 1.1, 2), c(1, 2, 1.1), c(2, 1, 2.1)) result <- hs_grouped_evaluate( spectra, wavelengths = c(500, 600, 700), labels = rep(c("a", "b"), 4), groups = rep(letters[1:4], each = 2), n_folds = 2, model_args = list(kernel = "linear"), bootstrap = 50 ) result$accuracy result$group_metrics }
Orders components by signal-to-noise ratio rather than variance. Estimates noise covariance from spatial first-differences.
hs_mnf(cube, n_components = 5L)hs_mnf(cube, n_components = 5L)
cube |
An hsi_cube object. |
n_components |
Integer. Number of components. Default |
A list with class "hsi_mnf" (same structure as hs_pca()).
Green, A. A., Berman, M., Switzer, P. and Craig, M. D. (1988). A
transformation for ordering multispectral data in terms of image quality
with implications for noise removal. IEEE Transactions on Geoscience and
Remote Sensing, 26(1), 65-74. doi:10.1109/36.3001
cube <- hs_example_cube() mnf <- hs_mnf(cube, n_components = 3) dim(mnf$scores)cube <- hs_example_cube() mnf <- hs_mnf(cube, n_components = 3) dim(mnf$scores)
Corrects spectra for multiplicative and additive scatter effects by regressing each spectrum against a reference spectrum (default: mean spectrum).
hs_msc(cube, reference = NULL)hs_msc(cube, reference = NULL)
cube |
An hsi_cube object. |
reference |
Numeric vector. Reference spectrum. Default |
An hsi_cube object with MSC-corrected spectra.
Geladi, P., MacDougall, D. and Martens, H. (1985). Linearization and
scatter-correction for near-infrared reflectance spectra of meat.
Applied Spectroscopy, 39(3), 491-500. doi:10.1366/0003702854248656
cube <- hs_example_cube() msc_cube <- hs_msc(cube)cube <- hs_example_cube() msc_cube <- hs_msc(cube)
NDI = (R_band1 - R_band2) / (R_band1 + R_band2). A flexible building block for any two-band ratio index.
hs_ndi(cube, band1, band2)hs_ndi(cube, band1, band2)
cube |
An hsi_cube object. |
band1 |
Numeric. Centre wavelength or range |
band2 |
Numeric. Centre wavelength or range |
A numeric matrix, in [-1, 1] for nonnegative input spectra.
Zero denominators are NA; transformed signed spectra can exceed these bounds.
cube <- hs_example_cube() ndi <- hs_ndi(cube, band1 = 540, band2 = 660) range(ndi, na.rm = TRUE)cube <- hs_example_cube() ndi <- hs_ndi(cube, band1 = 540, band2 = 660) range(ndi, na.rm = TRUE)
Legacy name for a dimensionless NIR band ratio. It is not a validated perfusion measurement or an implementation of a vendor index.
hs_npi(cube, band1 = c(655, 735), band2 = c(825, 910))hs_npi(cube, band1 = c(655, 735), band2 = c(825, 910))
cube |
An hsi_cube object with reflectance data. |
band1 |
Numeric vector of length 2. Default |
band2 |
Numeric vector of length 2. Default |
A numeric matrix of unscaled dimensionless band ratios.
cube <- hs_example_cube() npi <- hs_npi(cube)cube <- hs_example_cube() npi <- hs_npi(cube)
Performs Principal Component Analysis on the spectral dimension of an HSI cube. Reduces the spectral bands to a smaller number of orthogonal components ordered by explained variance.
hs_pca(cube, n_components = 5L, center = TRUE, scale = FALSE)hs_pca(cube, n_components = 5L, center = TRUE, scale = FALSE)
cube |
An hsi_cube object. |
n_components |
Integer. Number of components to retain. Default |
center |
Logical. Centre bands before PCA. Default |
scale |
Logical. Scale bands to unit variance. Default |
A list with class "hsi_pca":
3D array (rows x cols x n_components) of component score maps.
Matrix (bands x n_components) of spectral loadings.
Numeric vector of proportion of variance per component.
Centring vector used (or FALSE).
Scaling vector used (or FALSE).
Wavelength vector from input cube.
cube <- hs_example_cube() pca <- hs_pca(cube, n_components = 3) pca$variance_explainedcube <- hs_example_cube() pca <- hs_pca(cube, n_components = 3) pca$variance_explained
Displays RGB, fitted haemoglobin fraction and dimensionless band ratios. These research outputs are not equivalent to vendor clinical indices.
hs_plot_clinical( cube, indices = c("sto2", "npi", "thi"), mask_background = TRUE, threshold = 0.05, ncol = NULL )hs_plot_clinical( cube, indices = c("sto2", "npi", "thi"), mask_background = TRUE, threshold = 0.05, ncol = NULL )
cube |
An hsi_cube object with reflectance data. |
indices |
Character vector. Which indices to display.
Default |
mask_background |
Logical. Mask non-tissue pixels. Default |
threshold |
Numeric. Masking threshold on mean reflectance. Default |
ncol |
Integer. Number of panel columns. Default |
A patchwork composite ggplot2::ggplot object.
cube <- hs_example_cube() hs_plot_clinical(cube)cube <- hs_example_cube() hs_plot_clinical(cube)
Displays a single spectral band as a spatial image using a pseudocolour palette.
hs_plot_image(cube, wavelength = NULL, band = NULL, palette = "viridis")hs_plot_image(cube, wavelength = NULL, band = NULL, palette = "viridis")
cube |
An hsi_cube object. |
wavelength |
Numeric. Centre wavelength to display (nearest band selected).
Default |
band |
Integer. Band index. Alternative to |
palette |
Character. Colour palette name: |
A ggplot2::ggplot object using ggplot2::geom_raster(). Masked
and nonfinite pixels are drawn in grey.
cube <- hs_example_cube() hs_plot_image(cube, wavelength = 550)cube <- hs_example_cube() hs_plot_image(cube, wavelength = 550)
Displays a single tissue index as a pseudocolour spatial map with colour scales selected for research visualization.
hs_plot_index( index_matrix, title = "", palette = "sto2", range = NULL, mask = NULL )hs_plot_index( index_matrix, title = "", palette = "sto2", range = NULL, mask = NULL )
index_matrix |
Numeric matrix (rows x cols) from an index function. A logical matrix is drawn as 0/1. |
title |
Character. Map title (e.g., "StO2 (%)"). Default |
palette |
Character. |
range |
Numeric vector of length 2. Display range. Default |
mask |
Logical matrix. Pixels to mask (FALSE = masked). Default |
A ggplot2::ggplot object.
cube <- hs_example_cube() sto2 <- hs_sto2(cube) hs_plot_index(sto2, title = "Fitted Hb fraction (%)", palette = "sto2")cube <- hs_example_cube() sto2 <- hs_sto2(cube) hs_plot_index(sto2, title = "Fitted Hb fraction (%)", palette = "sto2")
Creates a pseudo-colour RGB composite by mapping three wavelength bands to the red, green, and blue channels.
hs_plot_rgb(cube, r = 640, g = 550, b = 460, stretch = "linear")hs_plot_rgb(cube, r = 640, g = 550, b = 460, stretch = "linear")
cube |
An hsi_cube object. |
r, g, b
|
Numeric. Centre wavelengths for R, G, B channels. Defaults: r=640, g=550, b=460. |
stretch |
Character. Histogram stretch: |
A ggplot2::ggplot object.
cube <- hs_example_cube() hs_plot_rgb(cube)cube <- hs_example_cube() hs_plot_rgb(cube)
Displays spectral profiles from an HSI cube. Can show mean spectrum, random pixel spectra, or spectra from specific pixel locations.
hs_plot_spectra(cube, pixels = "mean", n = 100L, show_sd = TRUE)hs_plot_spectra(cube, pixels = "mean", n = 100L, show_sd = TRUE)
cube |
An hsi_cube object. |
pixels |
Character or data.frame. |
n |
Integer. Number of random spectra if |
show_sd |
Logical. Show the mean +/- SD ribbon. Default |
A ggplot2::ggplot object. The value axis is labelled with the cube's processing mode (for example "Reflectance"). Spectra of selected pixels are drawn in the colour-blind-safe Okabe-Ito palette for up to eight pixels and in viridis colours beyond that, with the legend in the order the pixels were supplied.
cube <- hs_example_cube() hs_plot_spectra(cube) hs_plot_spectra(cube, pixels = data.frame(x = c(5, 25), y = c(5, 25)))cube <- hs_example_cube() hs_plot_spectra(cube) hs_plot_spectra(cube, pixels = data.frame(x = c(5, 25), y = c(5, 25)))
Predict Classes in a New Cube Using a Fitted Classifier
hs_predict(model, cube)hs_predict(model, cube)
model |
Classification result from |
cube |
New hsi_cube on the same wavelength grid and preprocessing domain. |
Character matrix of predicted classes; invalid pixels are NA.
if (requireNamespace("e1071", quietly = TRUE)) { cube <- hs_example_cube() labels <- matrix(NA_character_, 30, 30) labels[1:10, 1:10] <- "class_a" labels[20:30, 20:30] <- "class_b" fit <- hs_classify_svm(cube, labels) new_cube <- hs_simulate_cube(rows = 10, cols = 10, seed = 7) table(hs_predict(fit, new_cube)) }if (requireNamespace("e1071", quietly = TRUE)) { cube <- hs_example_cube() labels <- matrix(NA_character_, 30, 30) labels[1:10, 1:10] <- "class_a" labels[20:30, 20:30] <- "class_b" fit <- hs_classify_svm(cube, labels) new_cube <- hs_simulate_cube(rows = 10, cols = 10, seed = 7) table(hs_predict(fit, new_cube)) }
Execute a Processing Recipe
hs_process(cube, recipe = hs_recipe(), learn = TRUE)hs_process(cube, recipe = hs_recipe(), learn = TRUE)
cube |
An hsi_cube object. |
recipe |
A recipe from |
learn |
Logical. Allow fitting an unspecified MSC reference on this cube. Set FALSE for validation or prediction data. |
List containing the processed cube and reusable fitted recipe.
recipe <- hs_recipe(list(list(method = "snv"), list(method = "msc"))) fitted <- hs_process(hs_example_cube(), recipe) # Reuse the MSC reference learned above on held-out data new_cube <- hs_simulate_cube(rows = 10, cols = 10, seed = 7) held_out <- hs_process(new_cube, fitted$recipe, learn = FALSE) dim(held_out$cube)recipe <- hs_recipe(list(list(method = "snv"), list(method = "msc"))) fitted <- hs_process(hs_example_cube(), recipe) # Reuse the MSC reference learned above on held-out data new_cube <- hs_simulate_cube(rows = 10, cols = 10, seed = 7) held_out <- hs_process(new_cube, fitted$recipe, learn = FALSE) dim(held_out$cube)
Auto-detects format from file extension and dispatches to the appropriate reader. Supported formats: ENVI (.hdr), TIFF (.tif/.tiff), Cubert (.cu3s).
hs_read_cube(path, ...)hs_read_cube(path, ...)
path |
Path to the hyperspectral data file. |
... |
Additional arguments passed to the format-specific reader. |
An hsi_cube object.
hdr_path <- hs_example_files() cube <- hs_read_cube(hdr_path, verbose = FALSE) dim(cube)hdr_path <- hs_example_files() cube <- hs_read_cube(hdr_path, verbose = FALSE) dim(cube)
Reads Cubert session files using the cuvis.r package, an R wrapper
for the Cubert CUVIS C SDK
(see https://github.com/CTTIR/cuvis.r).
hs_read_cubert( path, index = 1L, mode = c("reflectance", "spectral_radiance", "dark_subtract", "raw"), settings_dir = NULL, verbose = TRUE )hs_read_cubert( path, index = 1L, mode = c("reflectance", "spectral_radiance", "dark_subtract", "raw"), settings_dir = NULL, verbose = TRUE )
path |
Path to |
index |
Integer. Measurement index within session (1-based). Default |
mode |
Character. Processing mode: |
settings_dir |
Character or |
verbose |
Logical. Print progress messages. Default |
The processing context automatically loads dark/white references embedded in the session file, so separate reference files are typically not needed.
Cubert reflectance values are stored as uint16 scaled by 10000
(i.e. 10000 = 100% reflectance). This function automatically converts
to fractional reflectance (0-1) when mode = "reflectance".
An hsi_cube object. Reflectance data is in 0-1 range.
# Requires the cuvis.r package, the proprietary Cubert CUVIS SDK and the # vendor sample data; does nothing where any of them is missing. if (requireNamespace("cuvis.r", quietly = TRUE) && cuvis.r::cuvis_available() && !is.null(cuvis.r::cuvis_sample_data("test_mesu.cu3s"))) { cube <- hs_read_cubert(cuvis.r::cuvis_sample_data("test_mesu.cu3s")) dim(cube) }# Requires the cuvis.r package, the proprietary Cubert CUVIS SDK and the # vendor sample data; does nothing where any of them is missing. if (requireNamespace("cuvis.r", quietly = TRUE) && cuvis.r::cuvis_available() && !is.null(cuvis.r::cuvis_sample_data("test_mesu.cu3s"))) { cube <- hs_read_cubert(cuvis.r::cuvis_sample_data("test_mesu.cu3s")) dim(cube) }
Reads ENVI format hyperspectral data consisting of a .hdr header file
and a binary data file. Supports BSQ, BIL, and BIP interleave formats.
A declared data ignore value becomes NA in either backend. Signed
32-bit integer payloads retain their full range as R double values.
hs_read_envi( path, backend = "auto", bands = NULL, extent = NULL, verbose = TRUE )hs_read_envi( path, backend = "auto", bands = NULL, extent = NULL, verbose = TRUE )
path |
Path to the ENVI header file (.hdr) or binary file. |
backend |
Character. |
bands |
Integer vector of band indices to read. Default |
extent |
Numeric vector |
verbose |
Logical. Print progress messages. Default |
An hsi_cube object.
hdr_path <- hs_example_files() cube <- hs_read_envi(hdr_path, verbose = FALSE) dim(cube)hdr_path <- hs_example_files() cube <- hs_read_envi(hdr_path, verbose = FALSE) dim(cube)
Reads a multi-band TIFF file as a hyperspectral cube. Requires the terra
package for TIFF reading.
hs_read_tiff(path, wavelengths, fwhm = NULL, verbose = TRUE)hs_read_tiff(path, wavelengths, fwhm = NULL, verbose = TRUE)
path |
Path to multi-channel TIFF file. |
wavelengths |
Numeric vector of wavelengths (required for TIFF files as they lack spectral metadata). |
fwhm |
Numeric vector of FWHM values. Default |
verbose |
Logical. Print progress messages. Default |
An hsi_cube object.
if (requireNamespace("terra", quietly = TRUE)) { cube <- hs_example_cube() path <- file.path(tempdir(), "example_cube.tif") hs_write_tiff(cube, path, verbose = FALSE) back <- hs_read_tiff(path, wavelengths = cube$wavelengths, verbose = FALSE) dim(back) }if (requireNamespace("terra", quietly = TRUE)) { cube <- hs_example_cube() path <- file.path(tempdir(), "example_cube.tif") hs_write_tiff(cube, path, verbose = FALSE) back <- hs_read_tiff(path, wavelengths = cube$wavelengths, verbose = FALSE) dim(back) }
Reads a Diaspective Vision TIVITA *_SpecCube.dat recording through the
tivis.r package and returns it as an hsi_cube.
hs_read_tivita(path, bands = NULL, verbose = TRUE)hs_read_tivita(path, bands = NULL, verbose = TRUE)
path |
Path to a |
bands |
Optional integer vector of band indices to read. |
verbose |
Logical. Print progress messages. Default |
Unlike the Cubert reader, this needs no vendor SDK: the TIVITA container is a plain binary format and tivis.r is pure R.
Acquisition metadata from the Suite's *_meta.log is attached to the cube
when present, along with the paths of the parameter images the Suite
exported beside the recording (RGB rendering, oxygenation, NIR perfusion,
THI, TWI). Those are vendor outputs for comparison, not independent
physiological ground truth or equivalents of this package's research indices.
An hsi_cube object. Values are calibrated reflectance, normally
within [0, 1] but not clamped, since specular regions legitimately
exceed it.
hs_read_cube() for extension-based dispatch,
hs_read_cubert() for Cubert session files.
if (requireNamespace("tivis.r", quietly = TRUE)) { cube <- hs_read_tivita(tivis.r::tivis_example_file(), verbose = FALSE) dim(cube) }if (requireNamespace("tivis.r", quietly = TRUE)) { cube <- hs_read_tivita(tivis.r::tivis_example_file(), verbose = FALSE) dim(cube) }
Recipes contain ordered operations and their explicit parameters. A fitted MSC reference is stored in the returned recipe, allowing reuse on held-out data.
hs_recipe(steps = list(), seed = 1L)hs_recipe(steps = list(), seed = 1L)
steps |
List of steps, each with |
seed |
Integer random seed recorded with the recipe. |
An hsi_recipe object.
recipe <- hs_recipe(list( list(method = "snv"), list(method = "msc") )) length(recipe$steps)recipe <- hs_recipe(list( list(method = "snv"), list(method = "msc") )) length(recipe$steps)
Interpolates the spectral data to a new set of wavelength positions.
hs_resample(cube, target_wavelengths, method = "linear")hs_resample(cube, target_wavelengths, method = "linear")
cube |
An hsi_cube object. |
target_wavelengths |
Numeric vector. Target wavelength positions in nm. |
method |
Character. Interpolation method: |
Band-specific quality flags are not interpolated. Existing
calibration and absorbance flags move to metadata$source_spectral_qc,
where each record retains its original wavelengths and named flags.
Their former current-grid fields are removed. Repeated resampling without
new flags does not duplicate these records; spatial subsetting retains
aligned source flags without changing their original spectral axis.
An hsi_cube object with resampled spectra.
cube <- hs_example_cube() resampled <- hs_resample(cube, target_wavelengths = seq(450, 900, by = 10)) length(resampled$wavelengths)cube <- hs_example_cube() resampled <- hs_resample(cube, target_wavelengths = seq(450, 900, by = 10)) length(resampled$wavelengths)
Creates a polygon region of interest using point-in-polygon testing of integer pixel centres. A half-open ray-crossing rule handles boundaries; reversing the vertex order leaves the selected pixels unchanged.
hs_roi_polygon(cube, vertices)hs_roi_polygon(cube, vertices)
cube |
An hsi_cube object. |
vertices |
Matrix with columns |
A list with class "hsi_roi" containing the mask.
cube <- hs_example_cube() verts <- matrix(c(5, 5, 15, 15, 5, 20, 5, 20), ncol = 2, dimnames = list(NULL, c("x", "y"))) roi <- hs_roi_polygon(cube, verts)cube <- hs_example_cube() verts <- matrix(c(5, 5, 15, 15, 5, 20, 5, 20), ncol = 2, dimnames = list(NULL, c("x", "y"))) roi <- hs_roi_polygon(cube, verts)
Creates a rectangular region of interest on an HSI cube.
hs_roi_rect(cube, x_range, y_range)hs_roi_rect(cube, x_range, y_range)
cube |
An hsi_cube object. |
x_range |
Numeric vector of length 2 (column indices, min and max). |
y_range |
Numeric vector of length 2 (row indices, min and max). |
A list with class "hsi_roi" containing the mask and bounds.
cube <- hs_example_cube() roi <- hs_roi_rect(cube, x_range = c(5, 15), y_range = c(5, 15)) sum(roi$mask)cube <- hs_example_cube() roi <- hs_roi_rect(cube, x_range = c(5, 15), y_range = c(5, 15)) sum(roi$mask)
Computes per-band spectral statistics within a region of interest.
hs_roi_stats(cube, roi)hs_roi_stats(cube, roi)
cube |
An hsi_cube object. |
roi |
An |
A tibble::tibble with columns wavelength, mean, sd, median,
min, max, n_pixels, n_roi_pixels, valid_fraction, and
n_repaired_pixels. Counts and fractions are per band; SD describes
spatial variation, not uncertainty of an independent-group mean.
cube <- hs_example_cube() roi <- hs_roi_rect(cube, x_range = c(5, 15), y_range = c(5, 15)) stats <- hs_roi_stats(cube, roi) head(stats)cube <- hs_example_cube() roi <- hs_roi_rect(cube, x_range = c(5, 15), y_range = c(5, 15)) stats <- hs_roi_stats(cube, roi) head(stats)
Opens a Shiny application for interactive exploration of hyperspectral cubes. Provides band selection, spectral profiling, research index mapping, cancellable background processing and analysis, and export tools across six tabs.
hs_run_app( cube = NULL, port = NULL, launch.browser = TRUE, max_upload_mb = 256 )hs_run_app( cube = NULL, port = NULL, launch.browser = TRUE, max_upload_mb = 256 )
cube |
An hsi_cube object to explore. If |
port |
Integer. Port for Shiny server. Default |
launch.browser |
Logical. Open in browser. Default |
max_upload_mb |
Positive upload limit in MiB. Default 256. Uploaded cubes and background workers must also fit available memory. |
PNG downloads contain the current Viewer selection, including its mask, palette, band or RGB channels, and plot labels. ENVI downloads contain the complete current cube and a separate provenance record. Spectra CSV downloads contain the displayed random or clicked pixel coordinates and values; mean mode (or click mode before a selection) exports spatial summary statistics. Random samples remain fixed until the cube, sampling mode, or sample count changes. Cubes without measured wavelengths can be viewed by band index; wavelength-dependent operations, including RGB, require measured wavelengths.
Invisible NULL. Launches a Shiny application.
cube <- hs_example_cube() if (interactive()) { hs_run_app(cube) }cube <- hs_example_cube() if (interactive()) { hs_run_app(cube) }
Classifies each pixel by computing the spectral angle to a set of reference endmember spectra and assigning the class with the smallest angle.
hs_sam(cube, endmembers, threshold = 0.1)hs_sam(cube, endmembers, threshold = 0.1)
cube |
An hsi_cube object. |
endmembers |
Named matrix or data.frame. Rows = endmembers, cols = bands. Row names become class labels. |
threshold |
Numeric. Maximum angle (radians) for assignment. Pixels
exceeding this are classified as |
A list with class "hsi_classification":
Character matrix (rows x cols) of class labels.
3D array of angles to each endmember.
The endmember matrix used.
Kruse, F. A., Lefkoff, A. B., Boardman, J. W., Heidebrecht, K. B.,
Shapiro, A. T., Barloon, P. J. and Goetz, A. F. H. (1993). The spectral
image processing system (SIPS): interactive visualization and analysis of
imaging spectrometer data. Remote Sensing of Environment, 44(2-3),
145-163. doi:10.1016/0034-4257(93)90013-N
cube <- hs_example_cube() # Define endmembers from specific pixels em <- rbind( healthy = cube$data[5, 5, ], ischemic = cube$data[25, 5, ] ) result <- hs_sam(cube, em, threshold = 0.5) table(result$class_map)cube <- hs_example_cube() # Define endmembers from specific pixels em <- rbind( healthy = cube$data[5, 5, ], ischemic = cube$data[25, 5, ] ) result <- hs_sam(cube, em, threshold = 0.5) table(result$class_map)
Creates a realistic synthetic tissue hyperspectral cube with known ground truth. Simulates a tissue scene with regions of varying oxygenation, haemoglobin concentration, and a background (non-tissue) region.
hs_simulate_cube( rows = 50L, cols = 50L, wavelengths = seq(430, 910, by = 8), n_regions = 4L, sto2_range = c(0.3, 0.95), noise_sd = 0.01, seed = 42L )hs_simulate_cube( rows = 50L, cols = 50L, wavelengths = seq(430, 910, by = 8), n_regions = 4L, sto2_range = c(0.3, 0.95), noise_sd = 0.01, seed = 42L )
rows |
Integer. Spatial rows. Default |
cols |
Integer. Spatial columns. Default |
wavelengths |
Numeric vector. Wavelength grid in nm.
Default: |
n_regions |
Integer. Number of distinct tissue regions. Default |
sto2_range |
Numeric vector of length 2. Synthetic mixture fractions
(0 to 1), not validated tissue oxygenation measurements.
Default |
noise_sd |
Numeric. Gaussian noise standard deviation. Default |
seed |
Integer. Random seed for reproducibility. Default |
An hsi_cube object with known synthetic region_map. Legacy
sto2_ground_truth metadata records simulator parameters only; the generated
spectra are not an independent reference for quantitative tissue validation.
cube <- hs_simulate_cube(rows = 20, cols = 20) dim(cube)cube <- hs_simulate_cube(rows = 20, cols = 20) dim(cube)
Applies a Savitzky-Golay filter along the spectral dimension. Optionally computes derivatives per nanometer on a uniform wavelength grid. Only full-window centre bands are returned. Invalid spectra remain missing.
hs_smooth( cube, window = 5L, poly = 2L, deriv = 0L, backend = c("builtin", "prospectr", "signal") )hs_smooth( cube, window = 5L, poly = 2L, deriv = 0L, backend = c("builtin", "prospectr", "signal") )
cube |
An hsi_cube object. |
window |
Integer (odd). Filter window size in bands. Default |
poly |
Integer. Polynomial order. Must be less than |
deriv |
Integer. Derivative order (0 = smoothing only, 1 = first
derivative, 2 = second derivative). Default |
backend |
Character. Explicit backend: |
An hsi_cube object with smoothed/differentiated spectra.
Savitzky, A. and Golay, M. J. E. (1964). Smoothing and differentiation of
data by simplified least squares procedures. Analytical Chemistry,
36(8), 1627-1639. doi:10.1021/ac60214a047
cube <- hs_example_cube() smoothed <- hs_smooth(cube, window = 5, poly = 2) dim(smoothed)cube <- hs_example_cube() smoothed <- hs_smooth(cube, window = 5, poly = 2) dim(smoothed)
Normalizes each spectrum to zero mean and unit variance. Useful for reducing multiplicative scatter effects and baseline variation.
hs_snv(cube)hs_snv(cube)
cube |
An hsi_cube object. |
An hsi_cube object with SNV-corrected spectra.
Barnes, R. J., Dhanoa, M. S. and Lister, S. J. (1989). Standard normal
variate transformation and de-trending of near-infrared diffuse
reflectance spectra. Applied Spectroscopy, 43(5), 772-777.
doi:10.1366/0003702894202201
cube <- hs_example_cube() snv_cube <- hs_snv(cube)cube <- hs_example_cube() snv_cube <- hs_snv(cube)
Returns the fitted HbO2 fraction from hs_beer_lambert(). This is a
research model estimate and requires empirical validation for tissue use.
hs_sto2( cube, band1 = c(500, 650), band2 = c(700, 815), method = "beer_lambert" )hs_sto2( cube, band1 = c(500, 650), band2 = c(700, 815), method = "beer_lambert" )
cube |
An hsi_cube object with reflectance data. |
band1, band2
|
Retired ratio-method arguments. Supplying either raises a
migration error; use |
method |
|
A numeric matrix (rows x cols) with values 0-100 representing
estimated tissue oxygen saturation percentage. Returns NA for masked pixels.
cube <- hs_example_cube() sto2 <- hs_sto2(cube) range(sto2, na.rm = TRUE)cube <- hs_example_cube() sto2 <- hs_sto2(cube) range(sto2, na.rm = TRUE)
Legacy name for a dimensionless reference/Hb-band reflectance ratio. It is not a haemoglobin concentration measurement.
hs_thi(cube, band1 = c(530, 590), band2 = c(785, 825))hs_thi(cube, band1 = c(530, 590), band2 = c(785, 825))
cube |
An hsi_cube object. |
band1 |
Numeric vector of length 2. Default |
band2 |
Numeric vector of length 2. Default |
A numeric matrix of unscaled dimensionless band ratios.
cube <- hs_example_cube() thi <- hs_thi(cube)cube <- hs_example_cube() thi <- hs_thi(cube)
Applies saved PCA/MNF centring, scaling and loadings without refitting.
hs_transform(model, cube)hs_transform(model, cube)
model |
|
cube |
New hsi_cube with the same wavelength grid. |
Score array with spatial dimensions of the new cube; invalid pixels are NA.
pca <- hs_pca(hs_example_cube(), n_components = 3) new_cube <- hs_simulate_cube(rows = 10, cols = 10, seed = 7) scores <- hs_transform(pca, new_cube) dim(scores)pca <- hs_pca(hs_example_cube(), n_components = 3) new_cube <- hs_simulate_cube(rows = 10, cols = 10, seed = 7) scores <- hs_transform(pca, new_cube) dim(scores)
Legacy name for a dimensionless NIR reflectance ratio. The default 830-910 nm bands do not include the 970 nm water peak and do not measure water content.
hs_twi(cube, numerator = c(880, 910), denominator = c(830, 870))hs_twi(cube, numerator = c(880, 910), denominator = c(830, 870))
cube |
An hsi_cube object. |
numerator |
Numeric vector of length 2. Default |
denominator |
Numeric vector of length 2. Default |
A numeric matrix of unscaled dimensionless ratios, or an NA matrix with a warning if required wavelengths are unavailable.
cube <- hs_example_cube() twi <- hs_twi(cube)cube <- hs_example_cube() twi <- hs_twi(cube)
Computes a UMAP (Uniform Manifold Approximation and Projection) embedding
of the spectral data. Requires the uwot package.
hs_umap( cube, n_components = 2L, n_neighbors = 15L, min_dist = 0.1, pca_pre = 20L, seed = 1L )hs_umap( cube, n_components = 2L, n_neighbors = 15L, min_dist = 0.1, pca_pre = 20L, seed = 1L )
cube |
An hsi_cube object. |
n_components |
Integer. UMAP dimensions. Default |
n_neighbors |
Integer. Default |
min_dist |
Numeric. Default |
pca_pre |
Integer or NULL. PCA pre-reduction dimensionality. Default |
seed |
Integer random seed. Default 1; the caller's random state is restored. |
If the PCA dependency raises its known NULL-input error on older R,
UMAP retries with base SVD for PCA when supported by uwot and reports a
message of class hyperspectR_umap_pca_fallback. Other errors, including
failures in older uwot versions without this option, propagate unchanged.
A list with class "hsi_umap" containing embedding matrix and
spatial coordinates.
McInnes, L., Healy, J. and Melville, J. (2018). UMAP: Uniform manifold
approximation and projection for dimension reduction. arXiv:1802.03426.
doi:10.48550/arXiv.1802.03426
# Requires uwot package cube <- hs_example_cube() if (requireNamespace("uwot", quietly = TRUE)) { umap_result <- hs_umap(cube, n_components = 2) }# Requires uwot package cube <- hs_example_cube() if (requireNamespace("uwot", quietly = TRUE)) { umap_result <- hs_umap(cube, n_components = 2) }
Solves the linear mixing model per pixel using non-negative least squares.
hs_unmix_nnls( cube, endmembers, sum_to_one = FALSE, backend = c("builtin", "nnls"), keep_residuals = TRUE, chunk_size = 10000L )hs_unmix_nnls( cube, endmembers, sum_to_one = FALSE, backend = c("builtin", "nnls"), keep_residuals = TRUE, chunk_size = 10000L )
cube |
An hsi_cube object (reflectance or absorbance). |
endmembers |
Numeric matrix. Columns = endmember spectra. Rows = bands. Column names become abundance map labels. |
sum_to_one |
Logical. Apply sum-to-one constraint. Default |
backend |
Explicit solver: |
keep_residuals |
Logical. Retain the full residual cube. |
chunk_size |
Positive integer. Number of pixels per processing block. |
A list with class "hsi_unmix":
3D array (rows x cols x n_endmembers) of abundance maps.
3D array of reconstruction residuals.
Numeric matrix of per-pixel RMSE.
Character vector.
Lawson, C. L. and Hanson, R. J. (1995). Solving Least Squares Problems
(chapter 23, non-negative least squares). Society for Industrial and
Applied Mathematics. doi:10.1137/1.9781611971217
cube <- hs_example_cube() # Create simple endmembers em <- cbind( tissue = cube$data[5, 5, ], background = cube$data[25, 25, ] ) result <- hs_unmix_nnls(cube, em) dim(result$abundances)cube <- hs_example_cube() # Create simple endmembers em <- cbind( tissue = cube$data[5, 5, ], background = cube$data[25, 25, ] ) result <- hs_unmix_nnls(cube, em) dim(result$abundances)
Normalizes the cube by a white reference, optionally with dark correction.
hs_white_normalize(cube, white, dark = NULL)hs_white_normalize(cube, white, dark = NULL)
cube |
An hsi_cube object. |
white |
An hsi_cube object or 3D array representing the white reference. |
dark |
An hsi_cube object or 3D array representing the dark reference.
Default |
An hsi_cube object with normalized values.
cube <- hs_simulate_cube(rows = 10, cols = 10, noise_sd = 0) white <- hsi_cube(array(0.95, dim(cube$data)), cube$wavelengths) norm <- hs_white_normalize(cube, white)cube <- hs_simulate_cube(rows = 10, cols = 10, noise_sd = 0) white <- hsi_cube(array(0.95, dim(cube$data)), cube$wavelengths) norm <- hs_white_normalize(cube, white)
Writes an hsi_cube object as an ENVI header (.hdr) and binary (.dat) file pair.
hs_write_envi(cube, path, interleave = "bsq", data_type = 4L, verbose = TRUE)hs_write_envi(cube, path, interleave = "bsq", data_type = 4L, verbose = TRUE)
cube |
An hsi_cube object. |
path |
Character. Output path without extension. Files |
interleave |
Character. Data interleave format: |
data_type |
Integer. ENVI data type code. Default |
verbose |
Logical. Print progress. Default |
Invisible character vector of written file paths.
cube <- hs_example_cube() dir <- tempdir() paths <- hs_write_envi(cube, file.path(dir, "test_cube"), verbose = FALSE) file.exists(paths)cube <- hs_example_cube() dir <- tempdir() paths <- hs_write_envi(cube, file.path(dir, "test_cube"), verbose = FALSE) file.exists(paths)
Writes an hsi_cube object as a multi-band GeoTIFF file. Requires the
terra package. Values are stored as float64 to preserve the R double
range and precision; this can use more disk space than float32 TIFF.
A completed temporary TIFF replaces the target only after
encoding succeeds; ordinary write failures leave an existing target intact.
hs_write_tiff(cube, path, verbose = TRUE)hs_write_tiff(cube, path, verbose = TRUE)
cube |
An hsi_cube object. |
path |
Character. Output path (should end in .tif). |
verbose |
Logical. Print progress. Default |
Invisible path to the written file.
if (requireNamespace("terra", quietly = TRUE)) { cube <- hs_example_cube() path <- file.path(tempdir(), "example_cube.tif") hs_write_tiff(cube, path, verbose = FALSE) file.exists(path) }if (requireNamespace("terra", quietly = TRUE)) { cube <- hs_example_cube() path <- file.path(tempdir(), "example_cube.tif") hs_write_tiff(cube, path, verbose = FALSE) file.exists(path) }
Constructs a hyperspectral imaging data cube as an S3 object. The cube stores a 3D array of spectral data (rows x columns x bands) along with wavelength metadata, spatial mask, and additional metadata.
hsi_cube(data, wavelengths, fwhm = NULL, metadata = list(), mask = NULL)hsi_cube(data, wavelengths, fwhm = NULL, metadata = list(), mask = NULL)
data |
Numeric 3D array with dimensions (rows, cols, bands). |
wavelengths |
Numeric vector of band centre wavelengths in nanometers.
Length must match |
fwhm |
Numeric vector of full-width-at-half-maximum values per band in nm.
Default |
metadata |
Named list of metadata (camera model, integration time, processing mode, acquisition timestamp, etc.). Default empty list. |
mask |
Logical matrix matching spatial dimensions. |
An hsi_cube S3 object (a named list with class "hsi_cube").
# Create a small synthetic cube data <- array(runif(10 * 10 * 5), dim = c(10, 10, 5)) wavelengths <- c(500, 550, 600, 650, 700) cube <- hsi_cube(data, wavelengths) print(cube)# Create a small synthetic cube data <- array(runif(10 * 10 * 5), dim = c(10, 10, 5)) wavelengths <- c(500, 550, 600, 650, 700) cube <- hsi_cube(data, wavelengths) print(cube)
Displays a compact summary of the hyperspectral cube.
## S3 method for class 'hsi_cube' print(x, ...)## S3 method for class 'hsi_cube' print(x, ...)
x |
An hsi_cube object. |
... |
Additional arguments (ignored). |
Invisible x.
cube <- hs_example_cube() print(cube)cube <- hs_example_cube() print(cube)
Compact console overviews for the objects returned by the analysis
functions. Without these methods R prints every score map, residual cube
and fitted model in full. Each method shows the class, the dimensions and
the key settings, and returns its argument invisibly. The objects stay
plain lists: use names(), str() or $ to reach every element.
## S3 method for class 'summary.hsi_cube' print(x, ...) ## S3 method for class 'hsi_pca' print(x, ...) ## S3 method for class 'hsi_mnf' print(x, ...) ## S3 method for class 'hsi_umap' print(x, ...) ## S3 method for class 'hsi_unmix' print(x, ...) ## S3 method for class 'hsi_chromophore_fit' print(x, ...) ## S3 method for class 'hsi_classification' print(x, ...) ## S3 method for class 'hsi_roi' print(x, ...) ## S3 method for class 'hsi_recipe' print(x, ...)## S3 method for class 'summary.hsi_cube' print(x, ...) ## S3 method for class 'hsi_pca' print(x, ...) ## S3 method for class 'hsi_mnf' print(x, ...) ## S3 method for class 'hsi_umap' print(x, ...) ## S3 method for class 'hsi_unmix' print(x, ...) ## S3 method for class 'hsi_chromophore_fit' print(x, ...) ## S3 method for class 'hsi_classification' print(x, ...) ## S3 method for class 'hsi_roi' print(x, ...) ## S3 method for class 'hsi_recipe' print(x, ...)
x |
An object returned by |
... |
Additional arguments (ignored). |
Invisible x.
cube <- hs_example_cube() summary(cube) hs_pca(cube, n_components = 3) hs_roi_rect(cube, x_range = c(5, 15), y_range = c(5, 15)) hs_recipe(list(list(method = "snv"), list(method = "msc")))cube <- hs_example_cube() summary(cube) hs_pca(cube, n_components = 3) hs_roi_rect(cube, x_range = c(5, 15), y_range = c(5, 15)) hs_recipe(list(list(method = "snv"), list(method = "msc")))
Maps wavelength values to approximate visible light colours for spectral
line colouring. The default scale is fixed at 380-780 nm, so a wavelength
retains its colour when the plotted range changes. Values outside the
display limits use the scale's missing-value colour. Numeric increasing
limits supplied in ... may restrict or extend the displayed range while
preserving the wavelength mapping.
scale_color_wavelength(...) scale_colour_wavelength(...)scale_color_wavelength(...) scale_colour_wavelength(...)
... |
Additional arguments passed to |
A ggplot2::Scale object.
cube <- hs_example_cube() library(ggplot2) df <- data.frame( wavelength = cube$wavelengths, value = cube$data[15, 15, ] ) ggplot(df, aes(wavelength, value, color = wavelength)) + geom_line() + scale_color_wavelength() + labs(x = "Wavelength (nm)", y = "Reflectance", color = "Wavelength (nm)")cube <- hs_example_cube() library(ggplot2) df <- data.frame( wavelength = cube$wavelengths, value = cube$data[15, 15, ] ) ggplot(df, aes(wavelength, value, color = wavelength)) + geom_line() + scale_color_wavelength() + labs(x = "Wavelength (nm)", y = "Reflectance", color = "Wavelength (nm)")
Returns a named list of cube statistics including per-band means and standard deviations.
## S3 method for class 'hsi_cube' summary(object, ...)## S3 method for class 'hsi_cube' summary(object, ...)
object |
An hsi_cube object. |
... |
Additional arguments (ignored). |
A list of class summary.hsi_cube with elements dimensions,
wavelength_range, n_bands, data_range, band_means, band_sds,
band_counts (finite values per band), n_valid_pixels (pixels whose
whole spectrum is finite and unmasked), n_total_pixels and metadata.
Band statistics are named by rounded wavelength, or by the full
wavelength when rounding would give two bands the same name. Printing
the object shows a compact overview instead of the full list.
cube <- hs_example_cube() s <- summary(cube) s s$dimensionscube <- hs_example_cube() s <- summary(cube) s s$dimensions
A clean ggplot2 theme designed for hyperspectral image display. Uses minimal styling with a white background.
theme_hsi(base_size = 11)theme_hsi(base_size = 11)
base_size |
Numeric. Base font size. Default |
A ggplot2::theme object.
library(ggplot2) ggplot(data.frame(x = 1:10, y = 1:10), aes(x, y)) + geom_point() + theme_hsi()library(ggplot2) ggplot(data.frame(x = 1:10, y = 1:10), aes(x, y)) + geom_point() + theme_hsi()