Skip to content

Image containers API

SpectralImage stores an already loaded NumPy image with its actual axis order and optional detector and spatial metadata. It does not open files, infer axes, or run unmixing. unfold() turns detector data into an observations-by-channels matrix while retaining enough layout information to fold results back.

Axes and metadata

Measured and reconstructed images use C for detector channels; abundance images use K for fitted components. All images include Y and X, with optional T and Z axes. axes describes the array's actual dimension order, so for example CZYX means channel, depth, row, column. Array values and dtype are retained; no normalization or resampling is performed.

wavelengths_nm and detection_bands_nm describe detector channels and must match the C dimension. They are not attached directly to abundance K maps. Abundance images can carry component names and an optional unmixing mapping with the exact K × C spectra and their detector metadata. pixel_sizes_um records available spatial calibration. Metadata is copied when a container is created, though NumPy arrays and mapping values remain mutable.

Practical flow

from lumic import SpectralImage

# A measured volume with four detector channels and three Z planes.
image = SpectralImage(data, axes="CZYX", wavelengths_nm=wavelengths)
plane = image.slice(z=1)       # CYX; copies the selected plane.
unfolded = plane.unfold()      # (Y * X, C), one observation per pixel.

# After fitting a full matrix in the same row order:
maps = unfolded.fold_abundances(
    coefficients, component_names=["A", "B"], spectra=effective_spectra,
    normalization="L1",
)
restored_signal = maps.reconstruct()

When T or Z remains in the image, unfolding includes those positions as observations in NumPy C order. If you fit all observations together with fixed references, the same reference matrix is used for every observation. Fold methods require every original observation in its original row order; shape checks cannot detect reordered rows. For reader-based selective loading and ownership, see the Image I/O API. For full workflows, see Unmix a ternary image and Save images and spectra.

Loaded images

SpectralImage dataclass

SpectralImage(data, axes, wavelengths_nm=None, detection_bands_nm=None, pixel_sizes_um=dict(), provenance=dict(), kind='measured', component_names=None, unmixing=None)

Pixels with explicit axes and optional channel and spatial metadata.

Use this for images produced by readers, simulations or external NumPy code. axes describes the actual array order, not OME storage DimensionOrder. kind is immutable and describes what pixel values represent:

  • "measured" (default): detector-channel intensities, including simulated detector data. Requires C/Y/X with optional T/Z, in any order.
  • "reconstructed": predicted detector-channel intensities after fitting, with the same C/Y/X rules and optional channel metadata.
  • "abundance": estimated component contributions. Uses K instead of C; optional component_names follow K order. No detector metadata on K. Optional unmixing metadata stores the exact K×C component spectra, their C-channel coordinates/names, normalization label and abundance units. These labels describe the saved scale; no normalization is applied. See fold_abundances() and reconstruct().

X/Y/Z denote space and T time; each axis appears once. Channel wavelengths need not be uniformly spaced. Detection bounds describe recorded windows, not measured filter transmission. Pixel sizes are in micrometres. Abundances are not automatically fractions or counts; their units depend on the fitting method and spectral normalization. Nothing is rescaled.

The pixel array is retained without copying or changing its dtype. Attributes cannot be rebound, but the NumPy array itself remains mutable. Metadata is copied at construction; callers should treat it as descriptive information. This object does not open files, infer axes, or perform unmixing.

Examples:

>>> image = SpectralImage(np.zeros((4, 2, 3)), axes="CYX")
>>> image.data.shape
(4, 2, 3)

data instance-attribute

data

axes instance-attribute

axes

wavelengths_nm class-attribute instance-attribute

wavelengths_nm = None

detection_bands_nm class-attribute instance-attribute

detection_bands_nm = None

pixel_sizes_um class-attribute instance-attribute

pixel_sizes_um = field(default_factory=dict)

provenance class-attribute instance-attribute

provenance = field(default_factory=dict)

kind class-attribute instance-attribute

kind = 'measured'

component_names class-attribute instance-attribute

component_names = None

unmixing class-attribute instance-attribute

unmixing = None

slice

slice(*, t=0, z=0)

Copy a selected T/Z plane or substack into a new SpectralImage.

Indices are zero-based and relative to this loaded image. By default select the first T/Z plane, as reader.read() does. Zero also works for an absent T/Z axis; other absent/out-of-range indices raise IndexError. None retains the corresponding axis in full, including singleton axes. Selected T/Z axes are removed; other axes keep their original order. This method accepts measured, reconstructed and abundance images.

Pixel storage is always copied, even when no dimensions are removed. Channel metadata, names, kind and spatial calibration are preserved; provenance is deep-copied and records the immediate-parent selection under image_slice. Existing image_slice information is retained as parent_slice when slicing repeatedly. Changing the result's pixels or metadata does not alter the original image.

This operates on already loaded data and allocates a copy. To limit file I/O/memory, request T/Z selections from the reader before loading. It does not resample pixels, select channels or perform unmixing.

Examples: image.slice(z=2) selects Z=2 at T=0; image.slice(t=1, z=None) copies all Z at T=1; image.slice(t=None, z=None) copies the complete loaded image.

to_rgb

to_rgb(*, limits=None)

Return a display-only RGBRendering using source channel order.

Average lower/middle/upper channel groups into blue/green/red, assuming shorter-to-longer wavelength order. This is a preview, not true color, fluorophore assignment or spectral unmixing. No wavelengths are needed, inspected or inferred. At least three finite channels are required. Abundance images require a separate component-color choice and are not accepted here. Original data and metadata are unchanged.

All colors and all loaded T/Z planes use one shared linear scale. limits=(low, high) maps group-mean intensities to 0..255 with clipping and rounding to uint8. With no limits, zero is black and the largest RGB group mean across the entire loaded image is white-level intensity. Negative values clip to black; all-zero/nonpositive images render black. For those images the automatic limits are (0, 1), reusable explicitly. No independent color or per-plane normalization is performed. Reuse the returned limits explicitly when comparing separate images.

Non-C axes retain their relative order; S (RGB samples) is appended: CZYX → ZYXS, YXC → YXS. A stack remains a stack; the caller chooses which plane to display. Rendering allocates output and temporary arrays for the loaded image; chunk selection remains the reader/user's decision.

Example: rendering = image.to_rgb(limits=(0, 1000)) followed by plt.imshow(rendering.data) for YXS, or rendering.data[z] for ZYXS.

unfold

unfold()

Return an UnfoldedImage with observations × channels and saved layout.

Non-channel axes retain their relative order. Observations enumerate those axes in NumPy C order (last non-channel axis varies fastest). A view is used where possible; some layouts require a full pixel copy. No normalization, selection or intensity conversion is performed. Only the loaded image is unfolded; loading/chunking remains the caller's responsibility. Fitting one matrix assumes shared spectra across its observations, including any retained Z or T dimensions. This operation accepts measured/reconstructed images; abundance maps are fitting outputs, not detector-channel inputs for the spectral workflow.

save_ome_tiff

save_ome_tiff(path, *, compression='deflate', bigtiff=None, overwrite=False)

Save quantitative pixels and supported metadata as lossless OME-TIFF.

Convenience form of lumic.io.save_ome_tiff(self, path); both use the same exporter and validation. Supports measured, reconstructed and abundance images. Abundance K axes are stored as ordinary OME C channels with component meaning/spectra in a versioned annotation. Deflate is the default; use "lzw" or None for lossless LZW or uncompressed output. Existing files are protected unless overwrite=True. Returns the destination Path.

Standard OME fields retain calibration/channel names; a versioned annotation preserves original axes, image kind, detector coordinates and JSON-compatible source provenance. Pixel values are not scaled. See lumic.io.save_ome_tiff for the full metadata/dtype contract and BigTIFF behavior. This saves the already loaded array, not a lazy or streamed dataset.

Example: image.save_ome_tiff("simulation.ome.tiff").

reconstruct

reconstruct()

Recreate the fitted spectral signal from abundance maps and a saved basis.

Requires kind="abundance" and unmixing['spectra'], in the same K order and exact scale used to estimate these coefficients. Replace K with C in the image axes, preserve spatial calibration, and attach the basis's detector coordinates/names to the resulting kind="reconstructed" image. Neither coefficients nor spectra are normalized or clipped here.

This recovers the model prediction, not measured residuals/noise or a unique biological solution. Abundance units depend on basis scaling; a stored normalization label is descriptive, not a request to rescale. Arrays/metadata are mutable, so the current basis is validated again. Reconstruction allocates a full output array and may copy coefficients.

Example: reloaded_maps.reconstruct() after an OME-TIFF round trip.

Fold results into images

UnfoldedImage.data has shape (number of observations, C). It retains source_axes and source_shape so it can restore the original dimension order. fold_spectra() restores detector-channel pixels as a SpectralImage; fold_abundances() replaces C with K and returns an abundance image. Optional spectra must be the effective K × C basis used for the supplied coefficients if later reconstruction is needed.

UnfoldedImage dataclass

An observations × channels matrix with a reversible source layout.

Normally created by image.unfold(). source_axes and source_shape describe the image before unfolding. Rows enumerate the non-C axes in their original order, in NumPy C order. Numerical algorithms receive data as an ordinary NumPy matrix and need no image-specific logic.

fold_spectra restores measurement-channel data; fold_abundances restores component maps. Both require all observations in the original row order. A reduced convex-hull pool or reordered rows cannot be folded directly: first unmix the full loaded block with the learned spectra. Shape checks cannot detect a row permutation; preserving correspondence is the caller's responsibility. This object retains layout and metadata, not a separate reference to the original image. It does not load/chunk data or run fitting.

data instance-attribute

source_axes instance-attribute

source_shape instance-attribute

wavelengths_nm = None class-attribute instance-attribute

detection_bands_nm = None class-attribute instance-attribute

pixel_sizes_um = field(default_factory=dict) class-attribute instance-attribute

provenance = field(default_factory=dict) class-attribute instance-attribute

source_kind = 'measured' class-attribute instance-attribute

fold_spectra(data=None)

Restore the original SpectralImage layout and channel metadata.

With no argument, restore self.data. Pass a full reconstructed matrix (for example abundances @ spectra) to inspect a fitted reconstruction. The matrix must have the same observation/channel counts and ordering. Dtype is preserved; values are not clipped or normalized. Reshape may copy data depending on memory layout. With no argument, preserve source kind; an explicitly supplied matrix is labeled "reconstructed".

fold_abundances(data, *, component_names=None, spectra=None, normalization=None, abundance_units=None)

Restore component maps as a SpectralImage with kind="abundance".

Input is observations × components. Replace C in the source axes with K (CZYX → KZYX, YXC → YXK). Preserve calibration and source provenance; detector wavelengths/bands are never attached directly to components. Optional component_names follow matrix column order, without matching.

To reconstruct the fitted detector signal later, pass the same component spectra (K × C) used to fit the abundances, on the same scale. The image stores those spectra and the source detector metadata without rescaling the values.

When you supply spectra, you can also use normalization and abundance_units to describe their scale and the units of the fitted abundances. These labels do not change the values.

To save abundances fitted with L1-normalized reference spectra:

maps = unfolded.fold_abundances(
    abundances,
    spectra=reference_spectra,
    component_names=["A", "B"],
    normalization="L1",
)
maps.save_ome_tiff("abundances.ome.tif")

After loading the saved image, call reconstruct() to recover the fitted detector signal. Reconstruction requires the stored spectra.

Display rendering

to_rgb() returns RGBRendering, a display-only preview rather than measured spectral data. It averages groups of source channels into blue, green, and red in source order, assuming channels are ordered from shorter to longer emission wavelength. The method does not inspect wavelength metadata or accept abundance maps. The returned array is uint8, appends an S axis of length three, and records the source groups and shared intensity limits. For example, CYX becomes YXS, while CZYX becomes ZYXS; select a plane explicitly when displaying a stack. Supply limits=(low, high) to use the same scale for comparable images.

RGBRendering dataclass

Display pixels and the settings used to create a channel-order preview.

data is uint8 with RGB last. axes preserves the source non-C axis order and appends S for three color samples: CYX → YXS, CZYX → ZYXS. S means RGB display values, not measured spectral channels or components. channel_groups records source-channel indices in R, G, B order. limits records the one shared intensity interval mapped to [0, 255], applied to every color and every pixel/plane/time point. Clipping at either limit and 8-bit rounding can affect color balance at extremes.

No fluorophores are identified or unmixed. Colors are not calibrated human vision or true color: lower/middle/upper source-channel groups map to B/G/R respectively, assuming channels are ordered from shorter to longer emission wavelengths. No wavelength metadata is interpreted or channels reordered; overlapping windows and unordered channels need not yield spectral colors.

Spatial calibration and source provenance are descriptive, not display controls. Attributes are frozen; arrays and copied metadata remain mutable. The object has no unfolding, fitting or spectral-channel metadata API. Creating a stack does not select a plane; select explicitly when plotting.

data instance-attribute

axes instance-attribute

channel_groups instance-attribute

limits instance-attribute

pixel_sizes_um = field(default_factory=dict) class-attribute instance-attribute

provenance = field(default_factory=dict) class-attribute instance-attribute