Package 'hyperspectR'

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

Help Index


Subset an hsi_cube Object

Description

Extract spatial and/or spectral subsets from a cube. Subsetting preserves the hsi_cube class.

Usage

## S3 method for class 'hsi_cube'
x[i, j, k, ...]

Arguments

x

An hsi_cube object.

i

Row indices (spatial).

j

Column indices (spatial).

k

Band indices (spectral).

...

Additional arguments (ignored).

Value

A subsetted hsi_cube object.

Examples

cube <- hs_example_cube()
sub <- cube[1:10, 1:10, 1:5]
dim(sub)

Convert hsi_cube to Tibble

Description

Convert hsi_cube to Tibble

Usage

## S3 method for class 'hsi_cube'
as_tibble(x, ..., long = TRUE, .name_repair = "unique")

Arguments

x

An hsi_cube object.

...

Additional arguments (ignored).

long

Logical. If TRUE (default), returns long format. See as.data.frame.hsi_cube() for details.

.name_repair

Name repair strategy (passed to tibble::as_tibble()).

Value

A tibble::tibble.

Examples

cube <- hs_example_cube()
tb <- tibble::as_tibble(cube[1:3, 1:3, 1:3])
head(tb)

Convert hsi_cube to Data Frame

Description

Convert hsi_cube to Data Frame

Usage

## S3 method for class 'hsi_cube'
as.data.frame(x, ..., long = FALSE)

Arguments

x

An hsi_cube object.

...

Additional arguments (ignored).

long

Logical. If TRUE, returns long format with columns x, y, wavelength, value. If FALSE, returns wide format with columns x, y, and one column per band. Default FALSE.

Value

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.

Examples

cube <- hs_example_cube()
df <- as.data.frame(cube[1:3, 1:3, 1:3], long = TRUE)
head(df)

Plot an hsi_cube Object

Description

Creates a ggplot2 visualization of a hyperspectral cube. Supports RGB composite, single-band images, and spectral profile plots.

Usage

## S3 method for class 'hsi_cube'
autoplot(
  object,
  type = c("rgb", "band", "spectra"),
  band = NULL,
  wavelength = NULL,
  r = NULL,
  g = NULL,
  b = NULL,
  ...
)

Arguments

object

An hsi_cube object.

type

Character. Plot type: "rgb" (default), "band", or "spectra".

band

Integer. Band index for single-band display. Used when type = "band".

wavelength

Numeric. Wavelength (nm) for single-band display. Alternative to band.

r, g, b

Numeric. Wavelengths for RGB channels. Defaults: 640, 550, 460.

...

Additional arguments passed to internal plot functions.

Value

A ggplot2::ggplot object.

Examples

cube <- hs_example_cube()
ggplot2::autoplot(cube, type = "rgb")

Get Dimensions of an hsi_cube

Description

Get Dimensions of an hsi_cube

Usage

## S3 method for class 'hsi_cube'
dim(x)

Arguments

x

An hsi_cube object.

Value

Integer vector c(rows, cols, bands).

Examples

cube <- hs_example_cube()
dim(cube)

Convert Reflectance to Absorbance

Description

Computes A(lambda) = -log10(R(lambda)). Values of R at or below zero are clamped to floor before log transformation.

Usage

hs_absorbance(cube, floor = 1e-06)

Arguments

cube

An hsi_cube object with reflectance values.

floor

Numeric. Minimum reflectance value to prevent log(0). Default 1e-6.

Value

An hsi_cube object with absorbance values.

Examples

cube <- hs_example_cube()
abs_cube <- hs_absorbance(cube)

Compute an Unscaled Spectral Band Ratio

Description

A scene-independent, dimensionless ratio of mean spectral values. It is not calibrated oxygen saturation, perfusion, concentration or water content.

Usage

hs_band_ratio(cube, numerator, denominator)

Arguments

cube

An hsi_cube object.

numerator, denominator

Numeric scalar wavelength or two-element range in nm.

Value

A spatial numeric matrix. Zero denominators and invalid pixels are NA.

Examples

cube <- hs_example_cube()
ratio <- hs_band_ratio(cube, numerator = c(650, 700), denominator = c(800, 850))
range(ratio, na.rm = TRUE)

Run and Resume a Manifest of Hyperspectral Recordings

Description

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.

Usage

hs_batch(
  manifest,
  recipe = hs_recipe(),
  out_dir,
  analysis = c("summary", "beer_lambert", "pca"),
  analysis_args = list(),
  resume = TRUE
)

Arguments

manifest

Data frame with distinct id and path columns. Optional reader_args list-column provides per-recording reader arguments.

recipe

A recipe from hs_recipe().

out_dir

Directory for per-recording RDS files and run-summary.csv.

analysis

One of "summary", "beer_lambert", or "pca".

analysis_args

Named list of arguments for the analysis function.

resume

Logical. Reuse intact results only if their fingerprint matches.

Value

Data frame of recording identifiers, statuses, result files and errors.

Examples

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)

Beer-Lambert Chromophore Fitting

Description

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.

Usage

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
)

Arguments

cube

An hsi_cube object with an explicit reflectance or absorbance domain.

chromophores

Character vector. Default c("HbO2", "Hb").

wavelength_range

Numeric vector of length 2. Fitting range. Default c(500, 600) (Hb Q-band region for best contrast).

input

"auto" reads the declared processing mode, or explicitly specify "reflectance" or "absorbance". Values never determine the domain.

pathlength_cm

Positive scalar optical pathlength, or NULL (unknown).

response

"point" (default) samples band centres; "gaussian" integrates reference coefficients using cube FWHM as Gaussian widths.

keep_residuals

Logical. Retain spectral residuals. Default FALSE.

Value

A list with class "hsi_chromophore_fit":

coefficients

Named matrices of concentration-pathlength products (mol/L * cm).

concentrations

Named matrices in mol/L when pathlength is supplied; otherwise NULL.

sto2

Matrix of oxygen saturation = HbO2 / (HbO2 + Hb) * 100.

total_hb

Sum of HbO2 and Hb concentration-pathlength products.

rmse

Matrix of fit residuals.

Examples

cube <- hs_example_cube()
fit <- hs_beer_lambert(cube)
range(fit$sto2, na.rm = TRUE)

Calibrate Raw HSI Data to Reflectance

Description

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.

Usage

hs_calibrate(cube, dark, white, clamp = TRUE, saturation = NULL)

Arguments

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 ⁠[0, 1]⁠. Default TRUE.

saturation

Optional finite saturation threshold in raw data units. Defaults to metadata$saturation_value when present; otherwise saturation remains an unresolved QC check.

Value

An hsi_cube object with reflectance values.

Examples

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)

Get Chromophore Extinction Coefficient Spectra

Description

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.

Usage

hs_chromophore_data(
  chromophore = c("HbO2", "Hb"),
  wavelength_range = c(400, 1000),
  source = c("reference", "synthetic")
)

Arguments

chromophore

Character vector. One or more of: "HbO2" (oxyhaemoglobin), "Hb" (deoxyhaemoglobin), "water", "melanin", "metHb" (methaemoglobin). Default c("HbO2", "Hb").

wavelength_range

Numeric vector of length 2. Wavelength range in nm. Default c(400, 1000).

source

"reference" (default) supports HbO2 and Hb; "synthetic" returns the legacy analytical shapes, unsuitable for quantitative fitting.

Value

A tibble::tibble with columns wavelength (nm) and one column per requested chromophore (extinction coefficient in cm^-1 / (mol/L)).

Examples

hb_data <- hs_chromophore_data()
head(hb_data)

Random Forest Pixel Classification

Description

Trains a random forest on labelled pixels and classifies all pixels. Requires the ranger package.

Usage

hs_classify_rf(
  cube,
  training_labels,
  training_mask = NULL,
  num.trees = 500L,
  mtry = NULL,
  ...
)

Arguments

cube

An hsi_cube object.

training_labels

Character or factor matrix with class labels. NA for unlabelled pixels.

training_mask

Logical matrix. Default NULL.

num.trees

Integer. Number of trees. Default 500.

mtry

Integer. Variables per split. Default NULL (auto).

...

Additional arguments passed to ranger::ranger().

Value

A list with class "hsi_classification" containing class_map.

Examples

# 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)
}

SVM Pixel Classification

Description

Trains a Support Vector Machine on labelled pixels and classifies all pixels. Requires the e1071 package.

Usage

hs_classify_svm(
  cube,
  training_labels,
  training_mask = NULL,
  kernel = "radial",
  cost = 10,
  gamma = NULL,
  ...
)

Arguments

cube

An hsi_cube object.

training_labels

Character or factor matrix (same spatial dims as cube) with class labels. NA for unlabelled pixels.

training_mask

Logical matrix. Alternative to NA in labels. Default NULL.

kernel

Character. SVM kernel: "radial" (default), "linear", "polynomial".

cost

Numeric. Cost parameter. Default 10.

gamma

Numeric. Gamma parameter. Default NULL (auto).

...

Additional arguments passed to e1071::svm().

Value

A list with class "hsi_classification" containing class_map.

Examples

# 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)
}

Compute All Available Clinical Indices

Description

Convenience function that computes StO2, NPI, THI, and TWI (if wavelength range permits) and returns them as a named list of matrices.

Usage

hs_clinical_indices(cube)

Arguments

cube

An hsi_cube object with reflectance data.

Value

A named list of numeric matrices: sto2, npi, thi, twi (TWI may be NA matrix if wavelengths are insufficient).

Examples

cube <- hs_example_cube()
indices <- hs_clinical_indices(cube)
names(indices)

Continuum Removal

Description

Removes the spectral continuum (convex hull) from each spectrum. Useful for enhancing absorption features and normalizing baseline variations.

Usage

hs_continuum_removal(cube, method = c("division", "subtraction"))

Arguments

cube

An hsi_cube object.

method

Character. "division" (default) divides by the continuum, "subtraction" subtracts the continuum.

Value

An hsi_cube object with continuum-removed spectra.

References

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

Examples

cube <- hs_example_cube()
cr <- hs_continuum_removal(cube, method = "division")

Apply Dark Current Correction

Description

Subtracts a dark reference from the cube data.

Usage

hs_dark_correct(cube, dark)

Arguments

cube

An hsi_cube object.

dark

An hsi_cube object or 3D array representing the dark reference.

Value

An hsi_cube object with dark-corrected values.

Examples

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)

Spectral Derivative

Description

Computes the spectral derivative using Savitzky-Golay differentiation. Shorthand for hs_smooth() with deriv > 0.

Usage

hs_derivative(cube, order = 1L, window = 5L)

Arguments

cube

An hsi_cube object.

order

Integer. Derivative order. Default 1.

window

Integer (odd). SG window size. Default 5.

Value

An hsi_cube object with derivative spectra.

Examples

cube <- hs_example_cube()
d1 <- hs_derivative(cube, order = 1)

Extract Endmember Spectra from a Cube

Description

Extracts endmember spectra from specified pixel locations.

Usage

hs_endmembers(cube, pixels, labels = NULL)

Arguments

cube

An hsi_cube object.

pixels

Data.frame or matrix with columns x (col) and y (row).

labels

Character vector of class labels for each pixel. Default NULL (auto-generated).

Value

A named matrix with endmember spectra (rows = endmembers, cols = bands).

Examples

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)

Get Example HSI Cube

Description

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.

Usage

hs_example_cube()

Value

An hsi_cube object (30 x 30 x 61 bands, 430-910 nm).

Examples

cube <- hs_example_cube()
print(cube)
dim(cube)

Write Example ENVI Files to a Temporary Directory

Description

Writes a minimal ENVI header + binary pair for testing I/O functions.

Usage

hs_example_files(dir = tempdir())

Arguments

dir

Character. Directory to write to. Default tempdir().

Value

Character. Path to the written .hdr file (invisibly).

Examples

hdr_path <- hs_example_files()
file.exists(hdr_path)

Export a Single-Band Image as PNG

Description

Exports a single band or index map from an HSI cube as a PNG image.

Usage

hs_export_png(
  data,
  path,
  palette = "viridis",
  range = NULL,
  width = NULL,
  height = NULL
)

Arguments

data

Numeric matrix to export (rows x cols).

path

Character. Output file path (should end in .png).

palette

Character. Colour palette: "viridis", "magma", "inferno", "plasma", "grey". Default "viridis".

range

Numeric vector of length 2. Data range for colour mapping. Default NULL (auto from finite data). Finite ordered endpoints are required; a constant range uses the first palette colour. Non-finite pixels are black, including an image with no finite pixels.

width

Integer. Image width in pixels. Default NULL (matches data cols).

height

Integer. Image height in pixels. Default NULL (matches data rows).

Value

Invisible path to the written file.

Examples

cube <- hs_example_cube()
mat <- cube$data[, , 30]
path <- file.path(tempdir(), "band30.png")
hs_export_png(mat, path)

Detect and Correct Bad Pixels

Description

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.

Usage

hs_fix_bad_pixels(cube, threshold = 3, method = "median")

Arguments

cube

An hsi_cube object.

threshold

Numeric. Robust standard deviation (scaled MAD) threshold. Default 3.

method

Character. Replacement method: "mean" or "median" of spatial neighbours. Default "median".

Value

An hsi_cube object with corrected pixels.

Examples

cube <- hs_example_cube()
# Introduce a hot pixel
cube$data[15, 15, ] <- 999
fixed <- hs_fix_bad_pixels(cube, threshold = 3)

Summarize Repeated ROI Measurements with Group-Level Uncertainty

Description

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.

Usage

hs_group_summary(
  data,
  value = "value",
  group = "subject_id",
  bootstrap = 1000L,
  seed = 1L
)

Arguments

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.

Value

List containing group means, independent group count, overall estimate, percentile interval and number of excluded nonfinite observations.

Examples

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$interval

Evaluate Classification with Entire Groups Held Out

Description

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.

Usage

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
)

Arguments

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, "svm" or "rf".

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.

Value

List of out-of-fold predictions, group metrics, confusion matrix, group-mean accuracy and interval, fold assignments and fitted recipes.

Examples

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
}

Minimum Noise Fraction Transform

Description

Orders components by signal-to-noise ratio rather than variance. Estimates noise covariance from spatial first-differences.

Usage

hs_mnf(cube, n_components = 5L)

Arguments

cube

An hsi_cube object.

n_components

Integer. Number of components. Default 5.

Value

A list with class "hsi_mnf" (same structure as hs_pca()).

References

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

Examples

cube <- hs_example_cube()
mnf <- hs_mnf(cube, n_components = 3)
dim(mnf$scores)

Multiplicative Scatter Correction

Description

Corrects spectra for multiplicative and additive scatter effects by regressing each spectrum against a reference spectrum (default: mean spectrum).

Usage

hs_msc(cube, reference = NULL)

Arguments

cube

An hsi_cube object.

reference

Numeric vector. Reference spectrum. Default NULL = mean spectrum of the cube.

Value

An hsi_cube object with MSC-corrected spectra.

References

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

Examples

cube <- hs_example_cube()
msc_cube <- hs_msc(cube)

Compute Normalized Difference Index (General Purpose)

Description

NDI = (R_band1 - R_band2) / (R_band1 + R_band2). A flexible building block for any two-band ratio index.

Usage

hs_ndi(cube, band1, band2)

Arguments

cube

An hsi_cube object.

band1

Numeric. Centre wavelength or range c(min, max) for first band.

band2

Numeric. Centre wavelength or range c(min, max) for second band.

Value

A numeric matrix, in ⁠[-1, 1]⁠ for nonnegative input spectra. Zero denominators are NA; transformed signed spectra can exceed these bounds.

Examples

cube <- hs_example_cube()
ndi <- hs_ndi(cube, band1 = 540, band2 = 660)
range(ndi, na.rm = TRUE)

Compute Near-Infrared Perfusion Index (NPI)

Description

Legacy name for a dimensionless NIR band ratio. It is not a validated perfusion measurement or an implementation of a vendor index.

Usage

hs_npi(cube, band1 = c(655, 735), band2 = c(825, 910))

Arguments

cube

An hsi_cube object with reflectance data.

band1

Numeric vector of length 2. Default c(655, 735).

band2

Numeric vector of length 2. Default c(825, 910).

Value

A numeric matrix of unscaled dimensionless band ratios.

Examples

cube <- hs_example_cube()
npi <- hs_npi(cube)

PCA on Hyperspectral Cube

Description

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.

Usage

hs_pca(cube, n_components = 5L, center = TRUE, scale = FALSE)

Arguments

cube

An hsi_cube object.

n_components

Integer. Number of components to retain. Default 5.

center

Logical. Centre bands before PCA. Default TRUE.

scale

Logical. Scale bands to unit variance. Default FALSE.

Value

A list with class "hsi_pca":

scores

3D array (rows x cols x n_components) of component score maps.

loadings

Matrix (bands x n_components) of spectral loadings.

variance_explained

Numeric vector of proportion of variance per component.

center

Centring vector used (or FALSE).

scale

Scaling vector used (or FALSE).

wavelengths

Wavelength vector from input cube.

Examples

cube <- hs_example_cube()
pca <- hs_pca(cube, n_components = 3)
pca$variance_explained

Research HSI Panel Display

Description

Displays RGB, fitted haemoglobin fraction and dimensionless band ratios. These research outputs are not equivalent to vendor clinical indices.

Usage

hs_plot_clinical(
  cube,
  indices = c("sto2", "npi", "thi"),
  mask_background = TRUE,
  threshold = 0.05,
  ncol = NULL
)

Arguments

cube

An hsi_cube object with reflectance data.

indices

Character vector. Which indices to display. Default c("sto2", "npi", "thi"). TWI is included only if wavelengths permit.

mask_background

Logical. Mask non-tissue pixels. Default TRUE.

threshold

Numeric. Masking threshold on mean reflectance. Default 0.05.

ncol

Integer. Number of panel columns. Default NULL arranges the panels in a near-square grid (ceiling(sqrt(n)) columns, so two columns for the default four panels). Supply ncol = 4 with a wide device for a single row.

Value

A patchwork composite ggplot2::ggplot object.

Examples

cube <- hs_example_cube()
hs_plot_clinical(cube)

Plot Single-Band Spatial Image

Description

Displays a single spectral band as a spatial image using a pseudocolour palette.

Usage

hs_plot_image(cube, wavelength = NULL, band = NULL, palette = "viridis")

Arguments

cube

An hsi_cube object.

wavelength

Numeric. Centre wavelength to display (nearest band selected). Default NULL.

band

Integer. Band index. Alternative to wavelength. Default NULL.

palette

Character. Colour palette name: "viridis" (default), "magma", "inferno" or "plasma". Any other name falls back to "viridis".

Value

A ggplot2::ggplot object using ggplot2::geom_raster(). Masked and nonfinite pixels are drawn in grey.

Examples

cube <- hs_example_cube()
hs_plot_image(cube, wavelength = 550)

Plot Index Map with Clinical Colour Scale

Description

Displays a single tissue index as a pseudocolour spatial map with colour scales selected for research visualization.

Usage

hs_plot_index(
  index_matrix,
  title = "",
  palette = "sto2",
  range = NULL,
  mask = NULL
)

Arguments

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. "sto2" (blue-red diverging), "perfusion" (viridis), "hemoglobin" (magma), "water" (mako). Default "sto2".

range

Numeric vector of length 2. Display range. Default NULL (data range). An NA entry takes that limit from the data.

mask

Logical matrix. Pixels to mask (FALSE = masked). Default NULL.

Value

A ggplot2::ggplot object.

Examples

cube <- hs_example_cube()
sto2 <- hs_sto2(cube)
hs_plot_index(sto2, title = "Fitted Hb fraction (%)", palette = "sto2")

Synthesize RGB Image from Spectral Cube

Description

Creates a pseudo-colour RGB composite by mapping three wavelength bands to the red, green, and blue channels.

Usage

hs_plot_rgb(cube, r = 640, g = 550, b = 460, stretch = "linear")

Arguments

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: "linear" (default), "none".

Value

A ggplot2::ggplot object.

Examples

cube <- hs_example_cube()
hs_plot_rgb(cube)

Plot Spectral Profiles

Description

Displays spectral profiles from an HSI cube. Can show mean spectrum, random pixel spectra, or spectra from specific pixel locations.

Usage

hs_plot_spectra(cube, pixels = "mean", n = 100L, show_sd = TRUE)

Arguments

cube

An hsi_cube object.

pixels

Character or data.frame. "mean" for spatial mean, "random" for random pixel sample, or a data.frame with columns x and y. Default "mean".

n

Integer. Number of random spectra if pixels = "random". Default 100.

show_sd

Logical. Show the mean +/- SD ribbon. Default TRUE; used only when pixels = "mean".

Value

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.

Examples

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

Description

Predict Classes in a New Cube Using a Fitted Classifier

Usage

hs_predict(model, cube)

Arguments

model

Classification result from hs_classify_svm() or hs_classify_rf().

cube

New hsi_cube on the same wavelength grid and preprocessing domain.

Value

Character matrix of predicted classes; invalid pixels are NA.

Examples

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

Description

Execute a Processing Recipe

Usage

hs_process(cube, recipe = hs_recipe(), learn = TRUE)

Arguments

cube

An hsi_cube object.

recipe

A recipe from hs_recipe().

learn

Logical. Allow fitting an unspecified MSC reference on this cube. Set FALSE for validation or prediction data.

Value

List containing the processed cube and reusable fitted recipe.

Examples

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)

Read a Hyperspectral Data Cube from Any Supported Format

Description

Auto-detects format from file extension and dispatches to the appropriate reader. Supported formats: ENVI (.hdr), TIFF (.tif/.tiff), Cubert (.cu3s).

Usage

hs_read_cube(path, ...)

Arguments

path

Path to the hyperspectral data file.

...

Additional arguments passed to the format-specific reader.

Value

An hsi_cube object.

Examples

hdr_path <- hs_example_files()
cube <- hs_read_cube(hdr_path, verbose = FALSE)
dim(cube)

Read a Cubert .cu3s Session File

Description

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).

Usage

hs_read_cubert(
  path,
  index = 1L,
  mode = c("reflectance", "spectral_radiance", "dark_subtract", "raw"),
  settings_dir = NULL,
  verbose = TRUE
)

Arguments

path

Path to .cu3s Cubert session file.

index

Integer. Measurement index within session (1-based). Default 1. Must be a finite positive whole number within the session's measurements; fractional indices are rejected before SDK initialization.

mode

Character. Processing mode: "reflectance" (default), "spectral_radiance", "dark_subtract", "raw".

settings_dir

Character or NULL. Path to the CUVIS settings directory (e.g., "C:/ProgramData/cuvis"). If NULL (default), uses the CUVIS_SETTINGS environment variable or a temporary directory.

verbose

Logical. Print progress messages. Default TRUE.

Details

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".

Value

An hsi_cube object. Reflectance data is in 0-1 range.

Examples

# 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)
}

Read an ENVI Hyperspectral Image File

Description

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.

Usage

hs_read_envi(
  path,
  backend = "auto",
  bands = NULL,
  extent = NULL,
  verbose = TRUE
)

Arguments

path

Path to the ENVI header file (.hdr) or binary file.

backend

Character. "auto" (default) uses the deterministic built-in reader. "builtin" forces pure-R reader. "terra" forces terra (errors if not installed).

bands

Integer vector of band indices to read. Default NULL = all.

extent

Numeric vector c(row_start, row_end, col_start, col_end) for spatial subset. Default NULL = full image.

verbose

Logical. Print progress messages. Default TRUE.

Value

An hsi_cube object.

Examples

hdr_path <- hs_example_files()
cube <- hs_read_envi(hdr_path, verbose = FALSE)
dim(cube)

Read a Multi-Channel TIFF File

Description

Reads a multi-band TIFF file as a hyperspectral cube. Requires the terra package for TIFF reading.

Usage

hs_read_tiff(path, wavelengths, fwhm = NULL, verbose = TRUE)

Arguments

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 NULL.

verbose

Logical. Print progress messages. Default TRUE.

Value

An hsi_cube object.

Examples

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)
}

Read a TIVITA Suite Recording

Description

Reads a Diaspective Vision TIVITA ⁠*_SpecCube.dat⁠ recording through the tivis.r package and returns it as an hsi_cube.

Usage

hs_read_tivita(path, bands = NULL, verbose = TRUE)

Arguments

path

Path to a ⁠*_SpecCube.dat⁠ file.

bands

Optional integer vector of band indices to read. NULL (default) reads all bands.

verbose

Logical. Print progress messages. Default TRUE.

Details

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.

Value

An hsi_cube object. Values are calibrated reflectance, normally within ⁠[0, 1]⁠ but not clamped, since specular regions legitimately exceed it.

See Also

hs_read_cube() for extension-based dispatch, hs_read_cubert() for Cubert session files.

Examples

if (requireNamespace("tivis.r", quietly = TRUE)) {
  cube <- hs_read_tivita(tivis.r::tivis_example_file(), verbose = FALSE)
  dim(cube)
}

Define a Reproducible Processing Recipe

Description

Recipes contain ordered operations and their explicit parameters. A fitted MSC reference is stored in the returned recipe, allowing reuse on held-out data.

Usage

hs_recipe(steps = list(), seed = 1L)

Arguments

steps

List of steps, each with method and an optional args list. Methods: smooth, snv, msc, derivative, absorbance, resample, continuum_removal, calibrate, dark_correct, white_normalize, fix_bad_pixels.

seed

Integer random seed recorded with the recipe.

Value

An hsi_recipe object.

Examples

recipe <- hs_recipe(list(
  list(method = "snv"),
  list(method = "msc")
))
length(recipe$steps)

Resample Spectra to New Wavelength Grid

Description

Interpolates the spectral data to a new set of wavelength positions.

Usage

hs_resample(cube, target_wavelengths, method = "linear")

Arguments

cube

An hsi_cube object.

target_wavelengths

Numeric vector. Target wavelength positions in nm.

method

Character. Interpolation method: "linear" (default), "spline".

Details

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.

Value

An hsi_cube object with resampled spectra.

Examples

cube <- hs_example_cube()
resampled <- hs_resample(cube, target_wavelengths = seq(450, 900, by = 10))
length(resampled$wavelengths)

Define Polygon ROI

Description

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.

Usage

hs_roi_polygon(cube, vertices)

Arguments

cube

An hsi_cube object.

vertices

Matrix with columns x and y (polygon vertices in pixel coordinates).

Value

A list with class "hsi_roi" containing the mask.

Examples

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)

Define Rectangular ROI

Description

Creates a rectangular region of interest on an HSI cube.

Usage

hs_roi_rect(cube, x_range, y_range)

Arguments

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).

Value

A list with class "hsi_roi" containing the mask and bounds.

Examples

cube <- hs_example_cube()
roi <- hs_roi_rect(cube, x_range = c(5, 15), y_range = c(5, 15))
sum(roi$mask)

Compute ROI Statistics

Description

Computes per-band spectral statistics within a region of interest.

Usage

hs_roi_stats(cube, roi)

Arguments

cube

An hsi_cube object.

roi

An hsi_roi object (from hs_roi_rect() or hs_roi_polygon()), or a logical mask matrix.

Value

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.

Examples

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)

Launch Interactive Hyperspectral Image Explorer

Description

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.

Usage

hs_run_app(
  cube = NULL,
  port = NULL,
  launch.browser = TRUE,
  max_upload_mb = 256
)

Arguments

cube

An hsi_cube object to explore. If NULL (default), the app starts with the example cube.

port

Integer. Port for Shiny server. Default NULL (auto).

launch.browser

Logical. Open in browser. Default TRUE.

max_upload_mb

Positive upload limit in MiB. Default 256. Uploaded cubes and background workers must also fit available memory.

Details

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.

Value

Invisible NULL. Launches a Shiny application.

Examples

cube <- hs_example_cube()
if (interactive()) {
  hs_run_app(cube)
}

Spectral Angle Mapper Classification

Description

Classifies each pixel by computing the spectral angle to a set of reference endmember spectra and assigning the class with the smallest angle.

Usage

hs_sam(cube, endmembers, threshold = 0.1)

Arguments

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 "unclassified". Default 0.1.

Value

A list with class "hsi_classification":

class_map

Character matrix (rows x cols) of class labels.

angle_map

3D array of angles to each endmember.

endmembers

The endmember matrix used.

References

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⁠

Examples

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)

Generate a Synthetic HSI Cube for Testing and Examples

Description

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.

Usage

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
)

Arguments

rows

Integer. Spatial rows. Default 50.

cols

Integer. Spatial columns. Default 50.

wavelengths

Numeric vector. Wavelength grid in nm. Default: seq(430, 910, by = 8) matching Cubert Ultris X MR.

n_regions

Integer. Number of distinct tissue regions. Default 4.

sto2_range

Numeric vector of length 2. Synthetic mixture fractions (0 to 1), not validated tissue oxygenation measurements. Default c(0.3, 0.95).

noise_sd

Numeric. Gaussian noise standard deviation. Default 0.01.

seed

Integer. Random seed for reproducibility. Default 42.

Value

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.

Examples

cube <- hs_simulate_cube(rows = 20, cols = 20)
dim(cube)

Savitzky-Golay Spectral Smoothing

Description

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.

Usage

hs_smooth(
  cube,
  window = 5L,
  poly = 2L,
  deriv = 0L,
  backend = c("builtin", "prospectr", "signal")
)

Arguments

cube

An hsi_cube object.

window

Integer (odd). Filter window size in bands. Default 5.

poly

Integer. Polynomial order. Must be less than window. Default 2.

deriv

Integer. Derivative order (0 = smoothing only, 1 = first derivative, 2 = second derivative). Default 0.

backend

Character. Explicit backend: "builtin" (default), "prospectr", or "signal". All use the same band support and units.

Value

An hsi_cube object with smoothed/differentiated spectra.

References

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

Examples

cube <- hs_example_cube()
smoothed <- hs_smooth(cube, window = 5, poly = 2)
dim(smoothed)

Standard Normal Variate Correction

Description

Normalizes each spectrum to zero mean and unit variance. Useful for reducing multiplicative scatter effects and baseline variation.

Usage

hs_snv(cube)

Arguments

cube

An hsi_cube object.

Value

An hsi_cube object with SNV-corrected spectra.

References

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

Examples

cube <- hs_example_cube()
snv_cube <- hs_snv(cube)

Estimate the Oxygenated Haemoglobin Fraction for Research

Description

Returns the fitted HbO2 fraction from hs_beer_lambert(). This is a research model estimate and requires empirical validation for tissue use.

Usage

hs_sto2(
  cube,
  band1 = c(500, 650),
  band2 = c(700, 815),
  method = "beer_lambert"
)

Arguments

cube

An hsi_cube object with reflectance data.

band1, band2

Retired ratio-method arguments. Supplying either raises a migration error; use hs_band_ratio() or the fitting range in hs_beer_lambert().

method

"beer_lambert" (default). The former "ratio" method is rejected; use hs_band_ratio() for a relative band ratio.

Value

A numeric matrix (rows x cols) with values 0-100 representing estimated tissue oxygen saturation percentage. Returns NA for masked pixels.

Examples

cube <- hs_example_cube()
sto2 <- hs_sto2(cube)
range(sto2, na.rm = TRUE)

Compute Tissue Haemoglobin Index (THI)

Description

Legacy name for a dimensionless reference/Hb-band reflectance ratio. It is not a haemoglobin concentration measurement.

Usage

hs_thi(cube, band1 = c(530, 590), band2 = c(785, 825))

Arguments

cube

An hsi_cube object.

band1

Numeric vector of length 2. Default c(530, 590) (Hb Q-bands).

band2

Numeric vector of length 2. Default c(785, 825) (reference).

Value

A numeric matrix of unscaled dimensionless band ratios.

Examples

cube <- hs_example_cube()
thi <- hs_thi(cube)

Apply a Fitted Spectral Transform to Another Cube

Description

Applies saved PCA/MNF centring, scaling and loadings without refitting.

Usage

hs_transform(model, cube)

Arguments

model

Result from hs_pca() or hs_mnf().

cube

New hsi_cube with the same wavelength grid.

Value

Score array with spatial dimensions of the new cube; invalid pixels are NA.

Examples

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)

Compute Tissue Water Index (TWI)

Description

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.

Usage

hs_twi(cube, numerator = c(880, 910), denominator = c(830, 870))

Arguments

cube

An hsi_cube object.

numerator

Numeric vector of length 2. Default c(880, 910) (adapted for Cubert range).

denominator

Numeric vector of length 2. Default c(830, 870).

Value

A numeric matrix of unscaled dimensionless ratios, or an NA matrix with a warning if required wavelengths are unavailable.

Examples

cube <- hs_example_cube()
twi <- hs_twi(cube)

UMAP Embedding of Spectral Data

Description

Computes a UMAP (Uniform Manifold Approximation and Projection) embedding of the spectral data. Requires the uwot package.

Usage

hs_umap(
  cube,
  n_components = 2L,
  n_neighbors = 15L,
  min_dist = 0.1,
  pca_pre = 20L,
  seed = 1L
)

Arguments

cube

An hsi_cube object.

n_components

Integer. UMAP dimensions. Default 2.

n_neighbors

Integer. Default 15.

min_dist

Numeric. Default 0.1.

pca_pre

Integer or NULL. PCA pre-reduction dimensionality. Default 20.

seed

Integer random seed. Default 1; the caller's random state is restored.

Details

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.

Value

A list with class "hsi_umap" containing embedding matrix and spatial coordinates.

References

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

Examples

# Requires uwot package
cube <- hs_example_cube()
if (requireNamespace("uwot", quietly = TRUE)) {
  umap_result <- hs_umap(cube, n_components = 2)
}

Linear Spectral Unmixing via NNLS

Description

Solves the linear mixing model per pixel using non-negative least squares.

Usage

hs_unmix_nnls(
  cube,
  endmembers,
  sum_to_one = FALSE,
  backend = c("builtin", "nnls"),
  keep_residuals = TRUE,
  chunk_size = 10000L
)

Arguments

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 FALSE.

backend

Explicit solver: "builtin" (default) or "nnls".

keep_residuals

Logical. Retain the full residual cube.

chunk_size

Positive integer. Number of pixels per processing block.

Value

A list with class "hsi_unmix":

abundances

3D array (rows x cols x n_endmembers) of abundance maps.

residuals

3D array of reconstruction residuals.

rmse

Numeric matrix of per-pixel RMSE.

endmember_names

Character vector.

References

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

Examples

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)

Apply White Reference Normalization

Description

Normalizes the cube by a white reference, optionally with dark correction.

Usage

hs_white_normalize(cube, white, dark = NULL)

Arguments

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 NULL (no dark subtraction).

Value

An hsi_cube object with normalized values.

Examples

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)

Write an HSI Cube to ENVI Format

Description

Writes an hsi_cube object as an ENVI header (.hdr) and binary (.dat) file pair.

Usage

hs_write_envi(cube, path, interleave = "bsq", data_type = 4L, verbose = TRUE)

Arguments

cube

An hsi_cube object.

path

Character. Output path without extension. Files .hdr and .dat will be created.

interleave

Character. Data interleave format: "bsq" (default), "bil", or "bip".

data_type

Integer. ENVI data type code. Default 4 (float32). Float32 rounds values to single precision; finite values outside its non-zero range are rejected before replacing files. Use 5 (float64) to retain the full R double range. Missing and masked values require a floating-point output type.

verbose

Logical. Print progress. Default TRUE.

Value

Invisible character vector of written file paths.

Examples

cube <- hs_example_cube()
dir <- tempdir()
paths <- hs_write_envi(cube, file.path(dir, "test_cube"), verbose = FALSE)
file.exists(paths)

Write an HSI Cube to Multi-Band TIFF

Description

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.

Usage

hs_write_tiff(cube, path, verbose = TRUE)

Arguments

cube

An hsi_cube object.

path

Character. Output path (should end in .tif).

verbose

Logical. Print progress. Default TRUE.

Value

Invisible path to the written file.

Examples

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)
}

Create an HSI Cube Object

Description

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.

Usage

hsi_cube(data, wavelengths, fwhm = NULL, metadata = list(), mask = NULL)

Arguments

data

Numeric 3D array with dimensions (rows, cols, bands).

wavelengths

Numeric vector of band centre wavelengths in nanometers. Length must match dim(data)[3]; values must be finite, positive and unique. Unsorted wavelengths reorder data, FWHM and matching per-band quality arrays together. Factors, character values and arrays are rejected.

fwhm

Numeric vector of full-width-at-half-maximum values per band in nm. Default NULL (unknown). If scalar, recycled to all bands.

metadata

Named list of metadata (camera model, integration time, processing mode, acquisition timestamp, etc.). Default empty list.

mask

Logical matrix matching spatial dimensions. TRUE = valid pixel. Default NULL (all pixels valid).

Value

An hsi_cube S3 object (a named list with class "hsi_cube").

Examples

# 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)

Print an hsi_cube Object

Description

Displays a compact summary of the hyperspectral cube.

Usage

## S3 method for class 'hsi_cube'
print(x, ...)

Arguments

x

An hsi_cube object.

...

Additional arguments (ignored).

Value

Invisible x.

Examples

cube <- hs_example_cube()
print(cube)

Print hyperspectR Result Objects

Description

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.

Usage

## 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, ...)

Arguments

x

An object returned by summary.hsi_cube(), hs_pca(), hs_mnf(), hs_umap(), hs_unmix_nnls(), hs_beer_lambert(), hs_sam(), hs_classify_svm(), hs_classify_rf(), hs_roi_rect(), hs_roi_polygon() or hs_recipe().

...

Additional arguments (ignored).

Value

Invisible x.

Examples

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")))

Wavelength-to-Colour Scale for Spectral Plots

Description

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.

Usage

scale_color_wavelength(...)

scale_colour_wavelength(...)

Arguments

...

Additional arguments passed to ggplot2::scale_color_gradientn().

Value

A ggplot2::Scale object.

Examples

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)")

Summarize an hsi_cube Object

Description

Returns a named list of cube statistics including per-band means and standard deviations.

Usage

## S3 method for class 'hsi_cube'
summary(object, ...)

Arguments

object

An hsi_cube object.

...

Additional arguments (ignored).

Value

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.

Examples

cube <- hs_example_cube()
s <- summary(cube)
s
s$dimensions

Minimalist HSI Theme

Description

A clean ggplot2 theme designed for hyperspectral image display. Uses minimal styling with a white background.

Usage

theme_hsi(base_size = 11)

Arguments

base_size

Numeric. Base font size. Default 11.

Value

A ggplot2::theme object.

Examples

library(ggplot2)
ggplot(data.frame(x = 1:10, y = 1:10), aes(x, y)) +
  geom_point() +
  theme_hsi()