Status: Needs Review
This page has not been reviewed for accuracy and completeness. Content may be outdated or contain errors.
Nodes API¶
This page is the current API index for node implementations shipped in this branch. It favors the live module docstrings over historical inventories.
Data And IO¶
Data Nodes¶
data
¶
Data preparation nodes for CU3S hyperspectral pipelines.
CU3SDataNode
¶
Bases: Node
General-purpose data node for CU3S hyperspectral sequences.
This node normalizes common CU3S batch inputs for pipelines:
- converts
cubefrom uint16 to float32 - passes optional
maskthrough unchanged - extracts 1D
wavelengthsfrom batched input
forward
¶
Normalize CU3S batch data for pipeline consumption.
Source code in cuvis_ai/node/data.py
LentilsAnomalyDataNode
¶
Bases: CU3SDataNode
Lentils-specific CU3S data node with binary anomaly label mapping.
Inherits shared CU3S normalization (cube + wavelengths) and additionally maps multi-class masks to binary anomaly masks.
Source code in cuvis_ai/node/data.py
forward
¶
Apply CU3S normalization and optional Lentils binary mask mapping.
Source code in cuvis_ai/node/data.py
JSON Readers¶
DetectionJsonReader
¶
Bases: Node
Read COCO detection JSON and emit tensors per frame.
Outputs per call:
- frame_id: int64 [1]
- bboxes: float32 [1, N, 4] (xyxy)
- category_ids: int64 [1, N]
- confidences: float32 [1, N]
- orig_hw: int64 [1, 2]
Source code in cuvis_ai/node/json_file.py
reset
¶
forward
¶
Emit detections for the next frame in the detection JSON stream.
Source code in cuvis_ai/node/json_file.py
TrackingResultsReader
¶
Bases: Node
Read tracking results JSON (bbox or mask format) and emit per-frame tensors.
Supports two JSON formats:
-
COCO bbox tracking —
images+annotationswithbboxandtrack_idfields. Emitsbboxes,category_ids,confidences,track_ids. -
Video COCO —
videos+annotationswithsegmentationslist of RLE dicts. Emitsmasklabel map andobject_ids.
Optional outputs are None when the format doesn't provide them.
Frame synchronization: When the optional frame_id input is connected
(e.g. from CU3SDataNode.mesu_index), the reader looks up detections for
that specific frame instead of cursor-advancing. This guarantees that the
emitted bboxes/masks correspond to the same frame as the cube data. When
frame_id is not connected, the reader uses the internal cursor (legacy
behavior).
Source code in cuvis_ai/node/json_file.py
reset
¶
forward
¶
Emit tracking tensors for an explicit frame or the next cursor frame.
Source code in cuvis_ai/node/json_file.py
NumPy Readers¶
numpy_reader
¶
Numpy-backed constant source node.
NpyReader
¶
Bases: Node
Load a .npy file once and return the same tensor every forward call.
Source code in cuvis_ai/node/numpy_reader.py
forward
¶
Video Nodes¶
video
¶
Video utilities: frame iteration, datasets, Lightning DataModule, and export nodes.
ToVideoNode
¶
ToVideoNode(
output_video_path,
frame_rate=10.0,
frame_rotation=None,
codec="mp4v",
overlay_title=None,
**kwargs,
)
Bases: Node
Write incoming RGB frames directly to a video file.
This node opens a single OpenCV VideoWriter and appends frames on each
forward call. It is intended for streaming pipelines where frames arrive
incrementally.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_video_path
|
str
|
Output path for the generated video file (for example |
required |
frame_rate
|
float
|
Video frame rate in frames per second. Must be positive. Default is |
10.0
|
frame_rotation
|
int | None
|
Optional frame rotation in degrees. Supported values are |
None
|
codec
|
str
|
FourCC codec string (length 4). Default is |
'mp4v'
|
overlay_title
|
str | None
|
Optional static title rendered at the top center with its own slim
darkened background block. Default is |
None
|
Source code in cuvis_ai/node/video.py
forward
¶
Append incoming RGB frames to the configured video file.
Source code in cuvis_ai/node/video.py
VideoFrameNode
¶
Bases: Node
Passthrough source node that receives RGB frames from the batch.
forward
¶
Pass through RGB frames and optional frame IDs from the batch.
Source code in cuvis_ai/node/video.py
Preprocessing And Spectral Tools¶
Normalization¶
normalization
¶
Differentiable normalization nodes for BHWC hyperspectral data.
This module provides a collection of normalization nodes designed for hyperspectral imaging pipelines. All normalizers operate on BHWC format ([batch, height, width, channels]) and maintain gradient flow for end-to-end training.
Normalization strategies:
- MinMaxNormalizer: Scales data to [0, 1] range using min-max statistics
- ZScoreNormalizer: Standardizes data to zero mean and unit variance
- SigmoidNormalizer: Applies sigmoid transformation with median centering
- PerPixelUnitNorm: L2 normalization per pixel across channels
- IdentityNormalizer: No-op passthrough for testing or baseline comparisons
- SigmoidTransform: General-purpose sigmoid for logits→probabilities
Why Normalize?
Normalization is critical for stable anomaly detection and deep learning:
- Stable covariance estimation: RX detectors require well-conditioned covariance matrices
- Gradient stability: Prevents exploding/vanishing gradients during training
- Comparable scales: Ensures different spectral ranges contribute equally
- Faster convergence: Accelerates gradient-based optimization
BHWC Format Requirement
All normalizers expect BHWC input format. For HWC tensors, add batch dimension:
hwc_tensor = torch.randn(256, 256, 61) # [H, W, C] bhwc_tensor = hwc_tensor.unsqueeze(0) # [1, H, W, C]
IdentityNormalizer
¶
MinMaxNormalizer
¶
Bases: _ScoreNormalizerBase
Min-max normalization per sample and channel (keeps gradients).
Scales data to [0, 1] range using (x - min) / (max - min) transformation. Can operate in two modes:
- Per-sample normalization (use_running_stats=False): min/max computed per batch
- Global normalization (use_running_stats=True): uses running statistics from statistical initialization
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eps
|
float
|
Small constant for numerical stability, prevents division by zero (default: 1e-6) |
1e-06
|
use_running_stats
|
bool
|
If True, use global min/max from statistical_initialization(). If False, compute min/max per batch during forward pass (default: True) |
True
|
**kwargs
|
dict
|
Additional arguments passed to Node base class |
{}
|
Attributes:
| Name | Type | Description |
|---|---|---|
running_min |
Tensor
|
Global minimum value computed during statistical initialization |
running_max |
Tensor
|
Global maximum value computed during statistical initialization |
Examples:
>>> from cuvis_ai.node.normalization import MinMaxNormalizer
>>> from cuvis_ai_core.training import StatisticalTrainer
>>> import torch
>>>
>>> # Mode 1: Global normalization with statistical initialization
>>> normalizer = MinMaxNormalizer(eps=1.0e-6, use_running_stats=True)
>>> stat_trainer = StatisticalTrainer(pipeline=pipeline, datamodule=datamodule)
>>> stat_trainer.fit() # Computes global min/max from training data
>>>
>>> # Inference uses global statistics
>>> output = normalizer.forward(data=hyperspectral_cube)
>>> normalized = output["normalized"] # [B, H, W, C], values in [0, 1]
>>>
>>> # Mode 2: Per-sample normalization (no initialization required)
>>> normalizer_local = MinMaxNormalizer(use_running_stats=False)
>>> output = normalizer_local.forward(data=hyperspectral_cube)
>>> # Each sample normalized independently using its own min/max
See Also
ZScoreNormalizer : Z-score standardization SigmoidNormalizer : Sigmoid-based normalization docs/tutorials/rx-statistical.md : RX pipeline with MinMaxNormalizer
Notes
Global normalization (use_running_stats=True) is recommended for RX detectors to ensure consistent scaling between training and inference. Per-sample normalization can be useful for real-time processing when training data is unavailable.
Source code in cuvis_ai/node/normalization.py
statistical_initialization
¶
Compute global min/max from data iterator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterator yielding dicts matching INPUT_SPECS (port-based format) Expected format: {"data": tensor} where tensor is the scores/data |
required |
Source code in cuvis_ai/node/normalization.py
SigmoidNormalizer
¶
Bases: _ScoreNormalizerBase
Median-centered sigmoid squashing per sample and channel.
Applies sigmoid transformation centered at the median with standard deviation scaling:
sigmoid((x - median) / std)
Produces values in [0, 1] range with median mapped to 0.5.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
std_floor
|
float
|
Minimum standard deviation threshold to prevent division by zero (default: 1e-6) |
1e-06
|
**kwargs
|
dict
|
Additional arguments passed to Node base class |
{}
|
Examples:
>>> from cuvis_ai.node.normalization import SigmoidNormalizer
>>> import torch
>>>
>>> # Create sigmoid normalizer
>>> normalizer = SigmoidNormalizer(std_floor=1.0e-6)
>>>
>>> # Apply to hyperspectral data
>>> data = torch.randn(4, 256, 256, 61) # [B, H, W, C]
>>> output = normalizer.forward(data=data)
>>> normalized = output["normalized"] # [4, 256, 256, 61], values in [0, 1]
See Also
MinMaxNormalizer : Min-max scaling to [0, 1] ZScoreNormalizer : Z-score standardization
Notes
Sigmoid normalization is robust to outliers because extreme values are squashed asymptotically to 0 or 1. This makes it suitable for data with heavy-tailed distributions or sporadic anomalies.
Source code in cuvis_ai/node/normalization.py
ZScoreNormalizer
¶
Bases: _ScoreNormalizerBase
Z-score (standardization) normalization along specified dimensions.
Computes: (x - mean) / (std + eps) along specified dims. Per-sample normalization with no statistical initialization required.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dims
|
list[int]
|
Dimensions to compute statistics over (default: [1,2] for H,W in BHWC format) |
None
|
eps
|
float
|
Small constant for numerical stability (default: 1e-6) |
1e-06
|
keepdim
|
bool
|
Whether to keep reduced dimensions (default: True) |
True
|
Examples:
>>> # Normalize over spatial dimensions (H, W)
>>> zscore = ZScoreNormalizer(dims=[1, 2])
>>>
>>> # Normalize over all spatial and channel dimensions
>>> zscore_all = ZScoreNormalizer(dims=[1, 2, 3])
Source code in cuvis_ai/node/normalization.py
SigmoidTransform
¶
Bases: Node
Applies sigmoid transformation to convert logits to probabilities [0,1].
General-purpose sigmoid node for converting raw scores/logits to probability space. Useful for visualization or downstream nodes that expect bounded [0,1] values.
Examples:
>>> sigmoid = SigmoidTransform()
>>> # Route logits to both loss (raw) and visualization (sigmoid)
>>> graph.connect(
... (rx.scores, loss_node.predictions), # Raw logits to loss
... (rx.scores, sigmoid.data), # Logits to sigmoid
... (sigmoid.transformed, viz.scores), # Probabilities to viz
... )
Source code in cuvis_ai/node/normalization.py
forward
¶
Apply sigmoid transformation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "transformed" key containing sigmoid output |
Source code in cuvis_ai/node/normalization.py
PerPixelUnitNorm
¶
Bases: _ScoreNormalizerBase
Per-pixel mean-centering and L2 normalization across channels.
Source code in cuvis_ai/node/normalization.py
Preprocessors¶
preprocessors
¶
Preprocessing Nodes.
This module provides nodes for preprocessing hyperspectral data, including wavelength-based band selection and filtering. These nodes help reduce dimensionality and focus analysis on specific spectral regions of interest.
See Also
cuvis_ai.node.channel_selector : Advanced channel selection methods cuvis_ai.node.normalization : Normalization and standardization nodes
BandpassByWavelength
¶
Bases: Node
Select channels by wavelength interval from BHWC tensors.
This node filters hyperspectral data by keeping only channels within a specified wavelength range. Wavelengths must be provided via the input port.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_wavelength_nm
|
float
|
Minimum wavelength (inclusive) to keep, in nanometers |
required |
max_wavelength_nm
|
float | None
|
Maximum wavelength (inclusive) to keep. If None, selects all wavelengths
|
None
|
Examples:
>>> # Create bandpass node
>>> bandpass = BandpassByWavelength(
... min_wavelength_nm=500.0,
... max_wavelength_nm=700.0,
... )
>>> # Filter cube in BHWC format with wavelengths from input port
>>> wavelengths_tensor = torch.from_numpy(wavelengths).float()
>>> filtered = bandpass.forward(data=cube_bhwc, wavelengths=wavelengths_tensor)["filtered"]
>>>
>>> # For single HWC images, add a batch dimension first:
>>> # filtered = bandpass.forward(data=cube_hwc.unsqueeze(0), wavelengths=wavelengths_tensor)["filtered"]
>>>
>>> # Use with wavelengths from upstream node
>>> pipeline.connect(
... (data_node.outputs.cube, bandpass.data),
... (data_node.outputs.wavelengths, bandpass.wavelengths),
... )
Source code in cuvis_ai/node/preprocessors.py
forward
¶
Filter cube by wavelength range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
Tensor
|
Wavelengths tensor [C] in nanometers. |
required |
**kwargs
|
Any
|
Additional keyword arguments (unused). |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "filtered" key containing filtered cube [B, H, W, C_filtered] |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no channels are selected by the provided wavelength range |
Source code in cuvis_ai/node/preprocessors.py
SpatialRotateNode
¶
Bases: Node
Rotate spatial dimensions of cubes, masks, and RGB images.
Applies a fixed rotation (90, -90, or 180 degrees) to the H and W dimensions of all provided inputs. Wavelengths pass through unchanged.
Place immediately after a data node so all downstream consumers see correctly oriented data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rotation
|
int | None
|
Rotation in degrees. Supported: 90, -90, 180 (and aliases 270, -270, -180). None or 0 means passthrough. |
None
|
Source code in cuvis_ai/node/preprocessors.py
forward
¶
Apply the configured rotation to the cube, mask, and rgb_image tensors.
Source code in cuvis_ai/node/preprocessors.py
BBoxRoiCropNode
¶
Bases: Node
Differentiable bbox cropping via torchvision roi_align.
Accepts BHWC images and xyxy bboxes, outputs NCHW crops resized to a
fixed output_size. Padding rows (all coords <= 0) are filtered out,
so the output N equals the number of valid detections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_size
|
tuple[int, int]
|
Target crop size |
(256, 128)
|
aligned
|
bool
|
Use sub-pixel aligned roi_align (recommended). |
True
|
Source code in cuvis_ai/node/preprocessors.py
forward
¶
Crop and resize bounding-box regions from images.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
Tensor
|
|
required |
bboxes
|
Tensor
|
|
required |
Returns:
| Type | Description |
|---|---|
dict
|
|
Source code in cuvis_ai/node/preprocessors.py
ChannelNormalizeNode
¶
Bases: Node
Per-channel mean/std normalization for NCHW tensors.
Defaults to ImageNet statistics but accepts any per-channel values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean
|
tuple[float, ...]
|
Per-channel mean. |
IMAGENET_MEAN
|
std
|
tuple[float, ...]
|
Per-channel std. |
IMAGENET_STD
|
Source code in cuvis_ai/node/preprocessors.py
forward
¶
Normalize images per channel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
Tensor
|
|
required |
Returns:
| Type | Description |
|---|---|
dict
|
|
Source code in cuvis_ai/node/preprocessors.py
Occlusion¶
occlusion
¶
Synthetic occlusion nodes for tracking evaluation (pure PyTorch).
OcclusionNodeBase
¶
OcclusionNodeBase(
tracking_json_path,
track_ids,
occlusion_start_frame,
occlusion_end_frame,
**kwargs,
)
Bases: Node, ABC
Base class for synthetic occlusion from tracking masks.
Source code in cuvis_ai/node/occlusion.py
forward
¶
Conditionally occlude an RGB batch using tracking-derived masks.
Source code in cuvis_ai/node/occlusion.py
PoissonOcclusionNode
¶
PoissonOcclusionNode(
tracking_json_path,
track_ids,
occlusion_start_frame,
occlusion_end_frame,
fill_color="poisson",
*,
input_key=None,
max_iter=1000,
tol=1e-06,
occlusion_shape="bbox",
bbox_mode="static",
static_bbox_scale=1.2,
static_bbox_padding_px=0,
static_full_width_x=False,
**kwargs,
)
Bases: OcclusionNodeBase
Pure-PyTorch occlusion node for either RGB frames or hyperspectral cubes.
Source code in cuvis_ai/node/occlusion.py
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | |
forward
¶
Occlude either the provided RGB batch or cube batch for the current frame.
Source code in cuvis_ai/node/occlusion.py
SolidOcclusionNode
¶
SolidOcclusionNode(
tracking_json_path,
track_ids,
occlusion_start_frame,
occlusion_end_frame,
fill_color="poisson",
*,
input_key=None,
max_iter=1000,
tol=1e-06,
occlusion_shape="bbox",
bbox_mode="static",
static_bbox_scale=1.2,
static_bbox_padding_px=0,
static_full_width_x=False,
**kwargs,
)
Bases: PoissonOcclusionNode
Deprecated alias of PoissonOcclusionNode.
Source code in cuvis_ai/node/occlusion.py
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | |
PoissonCubeOcclusionNode
¶
PoissonCubeOcclusionNode(
tracking_json_path,
track_ids,
occlusion_start_frame,
occlusion_end_frame,
fill_color="poisson",
*,
input_key=None,
max_iter=1000,
tol=1e-06,
occlusion_shape="bbox",
bbox_mode="static",
static_bbox_scale=1.2,
static_bbox_padding_px=0,
static_full_width_x=False,
**kwargs,
)
Bases: PoissonOcclusionNode
Deprecated alias of PoissonOcclusionNode with cube-only ports.
Source code in cuvis_ai/node/occlusion.py
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | |
forward
¶
Apply cube-only occlusion using the parent implementation.
Source code in cuvis_ai/node/occlusion.py
Conversion¶
conversion
¶
Conversion nodes for anomaly and segmentation pipelines.
This module provides:
ScoreToLogit: affine conversion from anomaly scores to logitsDecisionToMask: combine binary decisions with identity IDs into masks
ScoreToLogit
¶
Bases: Node
Trainable head that converts RX scores to anomaly logits.
This node takes RX anomaly scores (typically Mahalanobis distances) and applies a learned affine transformation to produce logits suitable for binary classification with BCEWithLogitsLoss.
The transformation is: logit = scale * (score - bias)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
init_scale
|
float
|
Initial value for the scale parameter |
1.0
|
init_bias
|
float
|
Initial value for the bias parameter (threshold) |
0.0
|
Attributes:
| Name | Type | Description |
|---|---|---|
scale |
Parameter or Tensor
|
Scale factor applied to scores |
bias |
Parameter or Tensor
|
Bias (threshold) subtracted from scores before scaling |
Examples:
>>> # After RX detector
>>> rx = RXGlobal(eps=1e-6)
>>> logit_head = ScoreToLogit(init_scale=1.0, init_bias=5.0)
>>> logit_head.unfreeze() # Enable gradient training
>>> graph.connect(rx.scores, logit_head.scores)
Source code in cuvis_ai/node/conversion.py
statistical_initialization
¶
Initialize bias from statistics of RX scores using streaming approach.
Uses Welford's algorithm for numerically stable online computation of mean and standard deviation, similar to RXGlobal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterator yielding dicts matching INPUT_SPECS (port-based format) Expected format: {"scores": tensor} where tensor is the RX scores |
required |
Source code in cuvis_ai/node/conversion.py
update
¶
Update running statistics with a batch of scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
Tensor
|
Batch of RX scores in BHWC format |
required |
Source code in cuvis_ai/node/conversion.py
finalize
¶
Finalize statistics and set bias to mean + 2*std.
This threshold (mean + 2*std) is a common heuristic for anomaly detection, capturing ~95% of normal data under Gaussian assumption.
Source code in cuvis_ai/node/conversion.py
reset
¶
Reset all statistics and accumulators.
Source code in cuvis_ai/node/conversion.py
forward
¶
Transform RX scores to logits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
Tensor
|
Input RX scores with shape (B, H, W, 1) |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "logits" key containing transformed scores |
Source code in cuvis_ai/node/conversion.py
get_threshold
¶
Get the current anomaly threshold (bias value).
Returns:
| Type | Description |
|---|---|
float
|
Current threshold value |
set_threshold
¶
Set the anomaly threshold (bias value).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threshold
|
float
|
New threshold value |
required |
predict_anomalies
¶
Convert logits to binary anomaly predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Logits from forward pass, shape (B, H, W, 1) |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Binary predictions (0=normal, 1=anomaly), shape (B, H, W, 1) |
Source code in cuvis_ai/node/conversion.py
DecisionToMask
¶
Bases: Node
Combine binary decisions and identity labels into a single int32 mask.
The output mask keeps per-pixel identity IDs where the decision is True and sets all non-matching pixels to 0.
forward
¶
Apply decisions to identities and return the final segmentation mask.
Source code in cuvis_ai/node/conversion.py
Spectral Angle Mapper¶
spectral_angle_mapper
¶
Spectral Angle Mapper node.
SpectralAngleMapper
¶
Bases: Node
Compute per-pixel spectral angle against one or more reference spectra.
Source code in cuvis_ai/node/spectral_angle_mapper.py
forward
¶
Run spectral-angle scoring for all references.
Source code in cuvis_ai/node/spectral_angle_mapper.py
Spectral Extraction¶
spectral_extractor
¶
Spectral signature extraction nodes for hyperspectral cubes.
BBoxSpectralExtractor
¶
BBoxSpectralExtractor(
center_crop_scale=0.65,
min_crop_pixels=4,
trim_fraction=0.1,
l2_normalize=True,
aggregation="median",
**kwargs,
)
Bases: Node
Extract per-bbox spectral signatures with trimmed median/mean and std.
Given an HSI cube [B, H, W, C] and detection bboxes [B, N, 4]
(xyxy format), extracts a center-cropped spectral signature for each bbox.
Outputs the per-band aggregated signature, per-band std, and a binary
validity mask.
Source code in cuvis_ai/node/spectral_extractor.py
forward
¶
Extract per-bbox spectral signatures for the first batch element.
Source code in cuvis_ai/node/spectral_extractor.py
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | |
SpectralSignatureExtractor
¶
SpectralSignatureExtractor(
trim_fraction=0.1,
min_mask_pixels=10,
zero_norm_threshold=1e-08,
**kwargs,
)
Bases: Node
Extract per-object spectral signatures from SAM-style label masks.
Source code in cuvis_ai/node/spectral_extractor.py
forward
¶
Extract per-object signatures for the first batch element.
Source code in cuvis_ai/node/spectral_extractor.py
Selectors And Trainable Feature Blocks¶
Channel Selectors¶
channel_selector
¶
Channel selector nodes for HSI to RGB conversion.
This module provides port-based nodes for selecting spectral channels from hyperspectral cubes and composing RGB images for downstream processing (e.g., with AdaCLIP).
Selectors gate/reweight individual channels independently:
output[c] = weight[c] * input[c] (diagonal operation, preserves channel count).
For cross-channel linear projection (full matrix, reduces channel count),
see :mod:cuvis_ai.node.channel_mixer.
Normalization design
All channel selectors share a common RGB normalization strategy in
ChannelSelectorBase, controlled by NormMode:
-
Percentile bounds (not absolute min/max): SpectralRadiance data contains outlier pixels whose absolute max can be 10x the median, compressing 99% of the image into the bottom of the brightness range. Using the 0.5th / 99.5th percentile clips these outliers and preserves visual dynamic range.
-
Per-channel [3] bounds: Separate min/max per R/G/B channel preserves colour balance. A single scalar bound would distort hue if one channel has a wider range than the others.
-
Three modes (
NormMode):running(default) — warmup + percentile accumulation with optional freeze. The first warmup frames use per-frame normalization (visually good immediately) while accumulating global bounds. After warmup, accumulated bounds are used. By default, accumulation is frozen after 20 frames to prevent late outliers from changing brightness; setfreeze_running_bounds_after_frames=Noneto keep legacy unbounded accumulation.statistical— pre-computed global percentiles viaStatisticalTrainer. Use when exact global stats matter and a full first pass is acceptable.per_frame— each frame normalized independently; no inter-frame state. Use for unrelated images or single-frame pipelines. -
Why warmup + accumulation (not EMA): Exponential moving averages have recency bias — for long videos the early-frame statistics are forgotten. Min/max accumulation bounds only ever expand (min-of-lows, max-of-highs) during the accumulation window, giving stable normalization without recency drift. The warmup period ensures the first few frames look natural before enough data has been accumulated.
NormMode
¶
Bases: StrEnum
RGB normalization mode for channel selectors.
ChannelSelectorBase
¶
ChannelSelectorBase(
norm_mode=RUNNING,
apply_gamma=True,
freeze_running_bounds_after_frames=20,
running_warmup_frames=_WARMUP_FRAMES,
**kwargs,
)
Bases: Node
Base class for hyperspectral band selection strategies.
This base class defines the common input/output ports for band selection nodes and provides shared percentile-based RGB normalization (see module docstring for design rationale).
Subclasses should implement forward() and _compute_raw_rgb() (the
latter is used by statistical_initialization and _running_normalize).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
norm_mode
|
str | NormMode
|
RGB normalization mode. Default |
RUNNING
|
apply_gamma
|
bool
|
Apply sRGB gamma curve after normalization. Default |
True
|
freeze_running_bounds_after_frames
|
int | None
|
When |
20
|
running_warmup_frames
|
int
|
Number of initial |
_WARMUP_FRAMES
|
Ports
INPUT_SPECS
cube : float32, shape (-1, -1, -1, -1)
Hyperspectral cube in BHWC format.
wavelengths : float32, shape (-1,)
Wavelength array in nanometers.
OUTPUT_SPECS
rgb_image : float32, shape (-1, -1, -1, 3)
Composed RGB image in BHWC format (0-1 range).
band_info : dict
Metadata about selected bands.
Source code in cuvis_ai/node/channel_selector.py
statistical_initialization
¶
Compute global percentile bounds across the entire dataset.
Uses _compute_raw_rgb() to convert each batch, then accumulates
per-channel percentile bounds (min-of-lows, max-of-highs).
Source code in cuvis_ai/node/channel_selector.py
NDVISelector
¶
NDVISelector(
nir_nm=827.0,
red_nm=668.0,
colormap_min=-0.7,
colormap_max=0.5,
eps=1e-06,
**kwargs,
)
Bases: _NormalizedDifferenceIndexBase
Normalized Difference Vegetation Index renderer.
Computes:
(CUBE(nir_nm) - CUBE(red_nm)) / (CUBE(nir_nm) + CUBE(red_nm))
Bands are resolved by nearest available sensor wavelength. The raw NDVI map
is returned via index_image and rgb_image contains a colour-mapped
render. The scalar NDVI image is mapped with the HSV-style colormap used
by the Blood_OXY plugin XML.
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Compute NDVI plus colour-mapped RGB output.
Source code in cuvis_ai/node/channel_selector.py
FixedWavelengthSelector
¶
Bases: ChannelSelectorBase
Fixed wavelength band selection (e.g., 650, 550, 450 nm).
Selects bands nearest to the specified target wavelengths for R, G, B channels. This is the simplest band selection strategy that produces "true color-ish" images.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_wavelengths
|
tuple[float, float, float]
|
Target wavelengths for R, G, B channels in nanometers. Default: (650.0, 550.0, 450.0) |
(650.0, 550.0, 450.0)
|
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Select bands and compose RGB image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
Tensor
|
Wavelength array [C]. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" and "band_info" keys. |
Source code in cuvis_ai/node/channel_selector.py
RangeAverageFalseRGBSelector
¶
RangeAverageFalseRGBSelector(
red_range=(580.0, 650.0),
green_range=(500.0, 580.0),
blue_range=(420.0, 500.0),
**kwargs,
)
Bases: ChannelSelectorBase
Range-based false RGB selection by averaging bands per channel.
For each output channel (R/G/B), all spectral bands within the configured wavelength range are averaged per pixel. Channels with no matching bands are filled with zeros.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
red_range
|
tuple[float, float]
|
Inclusive wavelength range for red channel in nanometers. |
(580.0, 650.0)
|
green_range
|
tuple[float, float]
|
Inclusive wavelength range for green channel in nanometers. |
(500.0, 580.0)
|
blue_range
|
tuple[float, float]
|
Inclusive wavelength range for blue channel in nanometers. |
(420.0, 500.0)
|
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Average spectral bands inside RGB ranges and compose normalized RGB.
Source code in cuvis_ai/node/channel_selector.py
FastRGBSelector
¶
FastRGBSelector(
red_range=(580.0, 650.0),
green_range=(500.0, 580.0),
blue_range=(420.0, 500.0),
normalization_strength=0.75,
**kwargs,
)
Bases: ChannelSelectorBase
cuvis-next parity FastRGB renderer.
This selector mirrors the cuvis fast_rgb user-plugin behavior:
- Per-channel contiguous spectral range averaging.
- Dynamic per-frame normalization by global RGB mean when enabled.
- Static reflectance-style scaling when normalization is disabled.
- 8-bit quantization before returning float RGB in [0, 1].
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Render fast_rgb output with cuvis-next parity scaling.
Source code in cuvis_ai/node/channel_selector.py
HighContrastSelector
¶
Bases: ChannelSelectorBase
Data-driven band selection using spatial variance + Laplacian energy.
For each wavelength window, selects the band with the highest score based on: score = variance + alpha * Laplacian_energy
This produces "high contrast" images that may work better for visual anomaly detection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
windows
|
Sequence[tuple[float, float]]
|
Wavelength windows for Blue, Green, Red channels. Default: ((440, 500), (500, 580), (610, 700)) for visible spectrum. |
((440, 500), (500, 580), (610, 700))
|
alpha
|
float
|
Weight for Laplacian energy term. Default: 0.1 |
0.1
|
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Select high-contrast bands and compose RGB image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
Tensor
|
Wavelength array [C]. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" and "band_info" keys. |
Source code in cuvis_ai/node/channel_selector.py
CIRSelector
¶
Bases: ChannelSelectorBase
Color Infrared (CIR) false color composition.
Maps NIR to Red, Red to Green, Green to Blue for false-color composites. This is useful for highlighting vegetation and certain anomalies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nir_nm
|
float
|
Near-infrared wavelength in nm. Default: 860.0 |
860.0
|
red_nm
|
float
|
Red wavelength in nm. Default: 670.0 |
670.0
|
green_nm
|
float
|
Green wavelength in nm. Default: 560.0 |
560.0
|
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Select CIR bands and compose false-color image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
Tensor
|
Wavelength array [C]. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" and "band_info" keys. |
Source code in cuvis_ai/node/channel_selector.py
CIETristimulusFalseRGBSelector
¶
Bases: ChannelSelectorBase
CIE 1931 tristimulus-based false RGB rendering.
Converts a hyperspectral cube to sRGB by integrating each pixel's spectrum with the CIE 1931 2-degree standard observer color matching functions (x_bar, y_bar, z_bar), applying a D65 white point normalization, and converting from CIE XYZ to linear sRGB.
Normalization and sRGB gamma are handled by ChannelSelectorBase (see
apply_gamma parameter inherited from the base class).
This produces the most physically grounded false RGB and lands closest to the distribution SAM3's Perception Encoder expects.
For wavelengths outside the visible range (approx. >780 nm), the CMFs are zero, so NIR bands do not contribute to the output.
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Convert HSI cube to sRGB via CIE 1931 tristimulus integration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
Tensor | ndarray
|
Wavelength array [C] in nanometers. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" [B, H, W, 3] and "band_info". |
Source code in cuvis_ai/node/channel_selector.py
CameraEmulationFalseRGBSelector
¶
CameraEmulationFalseRGBSelector(
r_peak=610.0,
g_peak=540.0,
b_peak=460.0,
r_sigma=40.0,
g_sigma=35.0,
b_sigma=30.0,
**kwargs,
)
Bases: ChannelSelectorBase
Camera-emulation false RGB using smooth Gaussian sensitivity curves.
Defines three broad, smooth Gaussian weighting curves over the spectral
bands that mimic R/G/B camera sensitivity (peaks at configurable
wavelengths). The weight matrix W is [3, num_bands], applied as
rgb = W @ spectrum. Non-negativity is enforced by construction.
This is simple, stable, and requires no training. Good middle ground between single-band selection and learned mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r_peak
|
float
|
Red channel peak wavelength in nm. Default: 610.0 |
610.0
|
g_peak
|
float
|
Green channel peak wavelength in nm. Default: 540.0 |
540.0
|
b_peak
|
float
|
Blue channel peak wavelength in nm. Default: 460.0 |
460.0
|
r_sigma
|
float
|
Red channel Gaussian sigma in nm. Default: 40.0 |
40.0
|
g_sigma
|
float
|
Green channel Gaussian sigma in nm. Default: 35.0 |
35.0
|
b_sigma
|
float
|
Blue channel Gaussian sigma in nm. Default: 30.0 |
30.0
|
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Convert HSI cube to false RGB using Gaussian camera sensitivity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
Tensor | ndarray
|
Wavelength array [C] in nanometers. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" [B, H, W, 3] and "band_info". |
Source code in cuvis_ai/node/channel_selector.py
SupervisedSelectorBase
¶
SupervisedSelectorBase(
num_spectral_bands,
score_weights=(1.0, 1.0, 1.0),
lambda_penalty=0.5,
**kwargs,
)
Bases: ChannelSelectorBase
Base class for supervised band selection strategies.
This class adds an optional mask input port and implements common
logic for statistical initialization via :meth:fit.
The mask is assumed to be binary (0/1), where 1 denotes the positive class (e.g. stone) and 0 denotes the negative class (e.g. lentil/background).
Source code in cuvis_ai/node/channel_selector.py
requires_initial_fit
property
¶
Whether this node requires statistical initialization from training data.
Returns:
| Type | Description |
|---|---|
bool
|
Always True for supervised band selectors. |
statistical_initialization
¶
Initialize band selection using supervised scoring.
Computes Fisher, AUC, and MI scores for each band, delegates to
:meth:_select_bands for strategy-specific selection, and stores
the 3 selected bands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Training data stream with cube, mask, and wavelengths. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If band selection doesn't return exactly 3 bands. |
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Generate false-color RGB from selected bands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
ndarray
|
Wavelengths for each channel [C]. |
required |
mask
|
Tensor
|
Ground truth mask (unused in forward, required for initialization). |
None
|
context
|
Context
|
Pipeline execution context (unused). |
None
|
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" [B, H, W, 3] and "band_info" metadata. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the node has not been statistically initialized. |
Source code in cuvis_ai/node/channel_selector.py
SupervisedCIRSelector
¶
SupervisedCIRSelector(
windows=(
(840.0, 910.0),
(650.0, 720.0),
(500.0, 570.0),
),
score_weights=(1.0, 1.0, 1.0),
lambda_penalty=0.5,
**kwargs,
)
Bases: SupervisedSelectorBase
Supervised CIR/NIR band selection with window constraints.
Windows are typically set to:
- NIR: 840-910 nm
- Red: 650-720 nm
- Green: 500-570 nm
The selector chooses one band per window using a supervised score (Fisher + AUC + MI) with an mRMR-style redundancy penalty.
Source code in cuvis_ai/node/channel_selector.py
SupervisedWindowedSelector
¶
SupervisedWindowedSelector(
windows=(
(440.0, 500.0),
(500.0, 580.0),
(610.0, 700.0),
),
score_weights=(1.0, 1.0, 1.0),
lambda_penalty=0.5,
**kwargs,
)
Bases: SupervisedSelectorBase
Supervised band selection constrained to visible RGB windows.
Similar to :class:HighContrastSelector, but uses label-driven scores.
Default windows:
- Blue: 440-500 nm
- Green: 500-580 nm
- Red: 610-700 nm
Source code in cuvis_ai/node/channel_selector.py
SupervisedFullSpectrumSelector
¶
Bases: SupervisedSelectorBase
Supervised selection without window constraints.
Picks the top-3 discriminative bands globally with an mRMR-style redundancy penalty applied over the full spectrum.
Source code in cuvis_ai/node/channel_selector.py
SoftChannelSelector
¶
SoftChannelSelector(
n_select,
input_channels,
init_method="uniform",
temperature_init=5.0,
temperature_min=0.1,
temperature_decay=0.9,
hard=False,
eps=1e-06,
**kwargs,
)
Bases: Node
Soft channel selector with temperature-based Gumbel-Softmax selection.
This is a selector node — it gates/reweights individual channels independently:
output[c] = weight[c] * input[c] (diagonal operation, preserves channel count).
For cross-channel linear projection that reduces channel count, see
:class:cuvis_ai.node.channel_mixer.ConcreteChannelMixer or
:class:cuvis_ai.node.channel_mixer.LearnableChannelMixer.
This node learns to select a subset of input channels using differentiable channel selection with temperature annealing. Supports:
- Statistical initialization (uniform or importance-based)
- Gradient-based optimization with temperature scheduling
- Entropy and diversity regularization
- Hard selection at inference time
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_select
|
int
|
Number of channels to select |
required |
input_channels
|
int
|
Number of input channels |
required |
init_method
|
('uniform', 'variance')
|
Initialization method for channel weights (default: "uniform") |
"uniform"
|
temperature_init
|
float
|
Initial temperature for Gumbel-Softmax (default: 5.0) |
5.0
|
temperature_min
|
float
|
Minimum temperature (default: 0.1) |
0.1
|
temperature_decay
|
float
|
Temperature decay factor per epoch (default: 0.9) |
0.9
|
hard
|
bool
|
If True, use hard selection at inference (default: False) |
False
|
eps
|
float
|
Small constant for numerical stability (default: 1e-6) |
1e-06
|
Attributes:
| Name | Type | Description |
|---|---|---|
channel_logits |
Parameter or Tensor
|
Unnormalized channel importance scores [n_channels] |
temperature |
float
|
Current temperature for Gumbel-Softmax |
Source code in cuvis_ai/node/channel_selector.py
statistical_initialization
¶
Initialize channel selection weights from data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterator yielding dicts matching INPUT_SPECS (port-based format) Expected format: {"data": tensor} where tensor is BHWC |
required |
Source code in cuvis_ai/node/channel_selector.py
update_temperature
¶
Update temperature with decay schedule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
epoch
|
int
|
Current epoch number (used for per-epoch decay) |
None
|
step
|
int
|
Current training step (for more granular control) |
None
|
Source code in cuvis_ai/node/channel_selector.py
get_selection_weights
¶
Get current channel selection weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hard
|
bool
|
If True, use hard selection (top-k). If None, uses self.hard. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Selection weights [n_channels] summing to n_select |
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Apply soft channel selection to input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor [B, H, W, C] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "selected" key containing reweighted channels and optional "weights" key containing selection weights |
Source code in cuvis_ai/node/channel_selector.py
TopKIndices
¶
Bases: Node
Utility node that surfaces the top-k channel indices from selector weights.
This node extracts the indices of the top-k weighted channels from a selector's weight vector. Useful for introspection and reporting which channels were selected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
int
|
Number of top indices to return |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
k |
int
|
Number of top indices to return |
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Return the indices of the top-k weighted channels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
Tensor
|
Channel selection weights [n_channels] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "indices" key containing top-k indices |
Source code in cuvis_ai/node/channel_selector.py
Channel Mixers¶
channel_mixer
¶
Learnable channel mixer nodes for spectral data reduction.
Channel mixers project across channels using a full weight matrix:
output[k] = Σ_c W[k,c] * input[c], which can change the channel count.
Contrast with channel selectors (see :mod:cuvis_ai.node.channel_selector),
which gate/reweight individual channels independently (diagonal operation).
This module provides two mixer variants:
-
:class:
LearnableChannelMixer— 1×1 convolution-based mixer (DRCNN-style, Zeegers et al. 2020). -
:class:
ConcreteChannelMixer— Gumbel-Softmax differentiable band selection that learns soft-to-hard channel weighting via temperature annealing.
LearnableChannelMixer
¶
LearnableChannelMixer(
input_channels,
output_channels,
leaky_relu_negative_slope=0.01,
use_bias=True,
use_activation=True,
normalize_output=True,
inference_normalization="batchnorm_sigmoid",
init_method="xavier",
eps=1e-06,
reduction_scheme=None,
**kwargs,
)
Bases: Node
Learnable channel mixer for hyperspectral data reduction (DRCNN-style).
This node implements a learnable linear combination layer that reduces the number of spectral channels through spectral pixel-wise 1x1 convolutions. Based on the DRCNN approach, it uses:
- 1x1 convolution (linear combination across spectral dimension)
- Leaky ReLU activation (a=0.01)
- Bias parameters
- Optional PCA-based initialization
The mixer is designed to be trained end-to-end with a downstream model (e.g., AdaClip) while keeping the downstream model frozen. This allows the mixer to learn optimal spectral combinations for the specific task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_channels
|
int
|
Number of input spectral channels (e.g., 61 for hyperspectral cube) |
required |
output_channels
|
int
|
Number of output channels (e.g., 3 for RGB compatibility) |
required |
leaky_relu_negative_slope
|
float
|
Negative slope for Leaky ReLU activation (default: 0.01, as per DRCNN paper) |
0.01
|
use_bias
|
bool
|
Whether to use bias parameters (default: True, as per DRCNN paper) |
True
|
use_activation
|
bool
|
Whether to apply Leaky ReLU activation (default: True, as per DRCNN paper) |
True
|
normalize_output
|
bool
|
Whether to apply output normalization to [0, 1] range (default: True). During training this uses BatchNorm2d + sigmoid. |
True
|
inference_normalization
|
('batchnorm_sigmoid', 'per_frame_minmax', 'sigmoid_only', 'none')
|
Inference-time normalization mode used when |
"batchnorm_sigmoid"
|
init_method
|
('xavier', 'kaiming', 'pca', 'zeros')
|
Weight initialization method (default: "xavier")
|
"xavier"
|
eps
|
float
|
Small constant for numerical stability (default: 1e-6) |
1e-06
|
reduction_scheme
|
list[int] | None
|
Multi-layer reduction scheme for gradual channel reduction (default: None). If None, uses single-layer reduction (input_channels → output_channels). If provided, must start with input_channels and end with output_channels. Example: [61, 16, 8, 3] means:
|
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
conv |
Conv2d
|
1x1 convolutional layer performing spectral mixing |
activation |
LeakyReLU or None
|
Leaky ReLU activation function (if use_activation=True) |
Examples:
>>> # Create mixer: 61 channels → 3 channels (single-layer)
>>> mixer = LearnableChannelMixer(
... input_channels=61,
... output_channels=3,
... leaky_relu_negative_slope=0.01,
... init_method="xavier"
... )
>>>
>>> # Create mixer with multi-layer reduction (matches DRCNN paper)
>>> mixer = LearnableChannelMixer(
... input_channels=61,
... output_channels=3,
... reduction_scheme=[61, 16, 8, 3], # Gradual reduction
... leaky_relu_negative_slope=0.01,
... init_method="xavier"
... )
>>>
>>> # Optional: Initialize from PCA
>>> # mixer.statistical_initialization(input_stream)
>>>
>>> # Enable gradient training
>>> mixer.unfreeze()
>>>
>>> # Forward pass: [B, H, W, 61] → [B, H, W, 3]
>>> output = mixer.forward(data=hsi_cube)
>>> rgb_like = output["rgb"] # [B, H, W, 3]
Source code in cuvis_ai/node/channel_mixer.py
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | |
requires_initial_fit
property
¶
Whether this node requires statistical initialization.
statistical_initialization
¶
Initialize mixer weights from PCA components.
This method computes PCA on the input data and initializes the mixer weights to the top principal components. This provides a good starting point for gradient-based optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterator yielding dicts matching INPUT_SPECS (port-based format) Expected format: {"data": tensor} where tensor is [B, H, W, C_in] |
required |
Notes
This method is only used when init_method="pca". For other initialization methods, weights are set in init.
Source code in cuvis_ai/node/channel_mixer.py
freeze
¶
Disable gradient-based training of mixer weights.
unfreeze
¶
Enable gradient-based training of mixer weights.
forward
¶
Apply learnable channel mixing to input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor [B, H, W, C_in] in BHWC format |
required |
context
|
Context
|
Execution context with epoch, batch_idx, stage info |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "rgb" key containing reduced channels [B, H, W, C_out] |
Source code in cuvis_ai/node/channel_mixer.py
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 | |
ConcreteChannelMixer
¶
ConcreteChannelMixer(
input_channels,
output_channels=3,
tau_start=10.0,
tau_end=0.1,
max_epochs=20,
use_hard_inference=True,
eps=1e-06,
**kwargs,
)
Bases: Node
Concrete/Gumbel-Softmax channel mixer for hyperspectral cubes.
Learns K categorical distributions over T input bands,
and during training uses the Gumbel-Softmax trick to produce differentiable
approximate one-hot selection weights that become increasingly peaked as the
temperature :math:\tau is annealed.
For each output channel :math:c \in {1, \dots, K}, we learn logits
L_c in R^T and sample:
.. math::
w_c = \text{softmax}\left( \frac{L_c + g}{\tau} \right), \quad
g \sim \text{Gumbel}(0, 1)
The resulting weights are used to form K-channel RGB-like images:
.. math::
Y[:, :, c] = \sum_{t=1}^T w_c[t] \cdot X[:, :, t]
where X is the input hyperspectral cube in [0, 1].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_channels
|
int
|
Number of input spectral channels (e.g., 61 for hyperspectral cube). |
required |
output_channels
|
int
|
Number of output channels (default: 3 for RGB/AdaClip compatibility). |
3
|
tau_start
|
float
|
Initial temperature for Gumbel-Softmax (default: 10.0). |
10.0
|
tau_end
|
float
|
Final temperature for Gumbel-Softmax (default: 0.1). |
0.1
|
max_epochs
|
int
|
Number of epochs over which to exponentially anneal :math: |
20
|
use_hard_inference
|
bool
|
If True, uses hard argmax selection at inference/validation time (one-hot weights). If False, uses softmax over logits (default: True). |
True
|
eps
|
float
|
Small constant for numerical stability (default: 1e-6). |
1e-06
|
Notes
-
During training (
context.stage == 'train'), the node samples Gumbel noise and uses the Concrete relaxation with the current temperature :math:`\tau(\text{epoch})``. -
During validation/test/inference, it uses deterministic weights without Gumbel noise.
-
The node exposes
selection_weightsso that repulsion penalties (e.g., DistinctnessLoss) can be attached in the pipeline.
Source code in cuvis_ai/node/channel_mixer.py
get_selection_weights
¶
Return current selection weights without data dependency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
deterministic
|
bool
|
If True, uses softmax over logits (no Gumbel noise) at a
"midpoint" temperature (geometric mean of start/end). If False,
uses current logits with |
True
|
Source code in cuvis_ai/node/channel_mixer.py
get_selected_bands
¶
forward
¶
Apply Concrete/Gumbel-Softmax channel mixing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor [B, H, W, C_in] in BHWC format. |
required |
context
|
Context
|
Execution context with stage and epoch information. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with:
|
Source code in cuvis_ai/node/channel_mixer.py
Dimensionality Reduction¶
dimensionality_reduction
¶
PCA nodes for dimensionality reduction.
PCA
¶
Bases: Node
Project each frame independently onto its principal components.
Source code in cuvis_ai/node/dimensionality_reduction.py
forward
¶
Fit PCA independently on each frame and return the per-frame projection.
Source code in cuvis_ai/node/dimensionality_reduction.py
TrainablePCA
¶
Bases: PCA
Trainable PCA node with orthogonality regularization.
Source code in cuvis_ai/node/dimensionality_reduction.py
statistical_initialization
¶
Initialize PCA components from data using covariance eigen decomposition.
Source code in cuvis_ai/node/dimensionality_reduction.py
forward
¶
Project data onto statistically initialized global components.
Source code in cuvis_ai/node/dimensionality_reduction.py
AdaCLIP Nodes¶
adaclip
¶
AdaCLIP Anomaly Detection Nodes.
This module provides nodes for zero-shot anomaly detection using the AdaCLIP (Adaptive CLIP) model. Two implementations are available:
- AdaCLIPLocalNode: Loads and runs the CLIP vision model locally for inference
- AdaCLIPAPINode: Calls the AdaCLIP HuggingFace Space API for inference
AdaCLIP uses CLIP's vision features to detect anomalies based on text prompts, enabling zero-shot anomaly detection without training data.
See Also
cuvis_ai_core.node.huggingface : Base classes for HuggingFace model nodes
AdaCLIPLocalNode
¶
AdaCLIPLocalNode(
model_name="AdaCLIP",
cache_dir=None,
text_prompt="normal: lentils, anomaly: stones",
revision=None,
**kwargs,
)
Bases: HuggingFaceLocalNode
AdaCLIP anomaly detection with local HF loading.
Source code in cuvis_ai/node/adaclip.py
forward
¶
Run AdaCLIP anomaly detection with local CLIP model.
Processes images through CLIP vision encoder and generates anomaly scores based on feature norms. Supports gradient passthrough for training pipelines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Tensor
|
RGB image [B, H, W, 3] in range [0, 1] or [0, 255]. |
required |
text_prompt
|
str
|
Text description for anomaly detection. If None, uses self.text_prompt. Note: Current implementation uses feature norms; text prompts will be integrated in future versions. |
None
|
context
|
Any
|
Pipeline execution context (unused, for compatibility). |
None
|
**kwargs
|
Any
|
Additional keyword arguments (unused). |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary containing:
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If CLIP inference fails or model is not properly loaded. |
Source code in cuvis_ai/node/adaclip.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | |
AdaCLIPAPINode
¶
AdaCLIPAPINode(
space_url="Caoyunkang/AdaCLIP",
dataset_option="All",
text_prompt="normal: lentils, anomaly: stones",
**kwargs,
)
Bases: HuggingFaceAPINode
AdaCLIP anomaly detection via HuggingFace Spaces API.
This node calls the AdaCLIP Space for zero-shot anomaly detection. API backend is non-differentiable and suitable for inference only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
space_url
|
str
|
AdaCLIP Space URL (default: "Caoyunkang/AdaCLIP") |
'Caoyunkang/AdaCLIP'
|
dataset_option
|
str
|
Dataset selection option (default: "All") |
'All'
|
text_prompt
|
str
|
Text prompt for anomaly detection (default: "normal: lentils, anomaly: stones") |
'normal: lentils, anomaly: stones'
|
**kwargs
|
Additional arguments passed to HuggingFaceAPINode |
{}
|
Examples:
>>> # Create node
>>> adaclip = AdaCLIPAPINode()
>>>
>>> # Run inference
>>> rgb_image = torch.rand(1, 224, 224, 3) # BHWC format
>>> result = adaclip.forward(image=rgb_image)
>>> anomaly_mask = result["anomaly_mask"] # [B, H, W, 1]
Source code in cuvis_ai/node/adaclip.py
forward
¶
Run AdaCLIP anomaly detection via API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Tensor
|
RGB image [B, H, W, 3] in BHWC format |
required |
text_prompt
|
str
|
Text description of anomaly to detect. If None, uses self.text_prompt. |
None
|
**kwargs
|
Any
|
Additional arguments (unused) |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "anomaly_mask" and optionally "anomaly_scores" |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If API call fails |
ValueError
|
If image format is invalid |
Source code in cuvis_ai/node/adaclip.py
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 | |
Tracking, Prompting, And Sinks¶
Prompt Nodes¶
prompts
¶
Static nodes and helpers for frame-indexed text, mask, and bbox prompt schedules.
SpatialPromptSpec
dataclass
¶
One scheduled spatial (mask or bbox) prompt entry.
MaskPrompt
¶
Bases: Node
Emit a scheduled label-map prompt mask for the requested frame.
Source code in cuvis_ai/node/prompts.py
forward
¶
Emit the scheduled prompt label map for frame_id or an empty mask.
Source code in cuvis_ai/node/prompts.py
BBoxPrompt
¶
Bases: Node
Emit scheduled runtime bbox prompts plus overlay-friendly debug tensors.
Source code in cuvis_ai/node/prompts.py
forward
¶
Emit the scheduled bbox prompt list for frame_id or an empty list.
Source code in cuvis_ai/node/prompts.py
TextPrompt
¶
Bases: Node
Emit a runtime text prompt for the requested frame.
Source code in cuvis_ai/node/prompts.py
forward
¶
Emit the resolved prompt text for frame_id or an empty string.
Source code in cuvis_ai/node/prompts.py
parse_spatial_prompt_spec
¶
Parse <object_id>:<detection_id>@<frame_id> into a spatial prompt spec.
Source code in cuvis_ai/node/prompts.py
parse_text_prompt_spec
¶
Parse <text>@<frame_id> into a typed text spec.
Bare <text> is accepted as a backward-compatible alias for <text>@0.
Source code in cuvis_ai/node/prompts.py
load_text_prompt_schedule
¶
Build a per-frame text prompt schedule.
Multiple prompt frames are allowed. V1 rejects multiple distinct texts on the same frame.
Source code in cuvis_ai/node/prompts.py
normalize_text_prompt_mode
¶
Normalize and validate the text-prompt emission mode.
Source code in cuvis_ai/node/prompts.py
resolve_text_prompt_for_frame
¶
Resolve the runtime text prompt for frame_id.
scheduled emits only on exact prompt frames.
repeat keeps the latest scheduled prompt active until replaced.
Source code in cuvis_ai/node/prompts.py
load_detection_index
¶
Load a flat COCO or track-centric SAM3 detection JSON into frame-indexed metadata.
Source code in cuvis_ai/node/prompts.py
load_mask_prompt_schedule
¶
Load detection JSON and build per-frame label-map prompts.
Source code in cuvis_ai/node/prompts.py
load_bbox_prompt_schedule
¶
Load detection JSON and build per-frame bbox prompts.
Source code in cuvis_ai/node/prompts.py
JSON Writers¶
CocoTrackMaskWriter
¶
CocoTrackMaskWriter(
output_json_path,
default_category_name="object",
write_empty_frames=True,
atomic_write=True,
flush_interval=0,
**kwargs,
)
Bases: _BaseCocoTrackWriter
Write mask tracking outputs into video_coco JSON.
Source code in cuvis_ai/node/json_file.py
forward
¶
forward(
frame_id,
mask,
object_ids,
detection_scores,
category_ids=None,
category_semantics=None,
context=None,
**_,
)
Store one frame of tracked masks and metadata for later JSON export.
Source code in cuvis_ai/node/json_file.py
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 | |
CocoTrackBBoxWriter
¶
CocoTrackBBoxWriter(
output_json_path,
category_id_to_name=None,
write_empty_frames=True,
atomic_write=True,
flush_interval=0,
**kwargs,
)
Bases: _BaseCocoTrackWriter
Write tracked bbox outputs into COCO tracking JSON.
Source code in cuvis_ai/node/json_file.py
forward
¶
Store one frame of tracked bounding boxes for later export.
Source code in cuvis_ai/node/json_file.py
DetectionCocoJsonNode
¶
DetectionCocoJsonNode(
output_json_path,
category_id_to_name=None,
write_empty_frames=True,
atomic_write=True,
flush_interval=0,
**kwargs,
)
Bases: _BaseJsonWriterNode
Write frame-wise detections into COCO detection JSON.
Source code in cuvis_ai/node/json_file.py
forward
¶
Store one frame of detections for COCO JSON serialization.
Source code in cuvis_ai/node/json_file.py
NumPy Writers¶
numpy_writer
¶
Per-frame numpy feature writer node.
NumpyFeatureWriterNode
¶
Bases: Node
Save per-frame feature tensors to .npy files.
Writes one .npy file per frame, named
{prefix}_{frame_id:06d}.npy. Useful for offline analysis,
clustering, or evaluation of ReID embeddings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
str
|
Directory to write |
required |
prefix
|
str
|
Filename prefix (default |
'features'
|
Source code in cuvis_ai/node/numpy_writer.py
forward
¶
Write features to a .npy file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
Tensor
|
|
required |
frame_id
|
Tensor
|
|
required |
Returns:
| Type | Description |
|---|---|
dict
|
Empty dict (sink node). |
Source code in cuvis_ai/node/numpy_writer.py
Visualization, Losses, And Labels¶
Visualization Nodes¶
anomaly_visualization
¶
Anomaly detection visualization sink nodes for monitoring training progress.
ImageArtifactVizBase
¶
Bases: Node
Base class for visualization nodes that produce image artifacts.
Source code in cuvis_ai/node/anomaly_visualization.py
AnomalyMask
¶
Bases: Node
Visualize anomaly detection with GT and predicted masks.
Creates side-by-side visualizations showing ground truth masks, predicted masks, and overlay comparisons on hyperspectral cube images. The overlay shows:
- Green: True Positives (correct anomaly detection)
- Red: False Positives (false alarms)
- Yellow: False Negatives (missed anomalies)
Also displays IoU and other metrics. Returns a list of Artifact objects for logging to monitoring systems.
Executes during validation and inference stages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel
|
int
|
Channel index to use for cube visualization (required) |
required |
up_to
|
int
|
Maximum number of images to visualize. If None, visualizes all (default: None) |
None
|
Examples:
>>> decider = BinaryDecider(threshold=0.2)
>>> viz_mask = AnomalyMask(channel=30, up_to=5)
>>> tensorboard_node = TensorBoardMonitorNode(output_dir="./runs")
>>> graph.connect(
... (logit_head.logits, decider.data),
... (decider.decisions, viz_mask.decisions),
... (data_node.mask, viz_mask.mask),
... (data_node.cube, viz_mask.cube),
... (viz_mask.artifacts, tensorboard_node.artifacts),
... )
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
Create anomaly mask visualizations with GT/pred comparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
decisions
|
Tensor
|
Binary anomaly decisions [B, H, W, 1] |
required |
mask
|
Tensor | None
|
Ground truth anomaly mask [B, H, W, 1] (optional) |
None
|
cube
|
Tensor
|
Original cube [B, H, W, C] for visualization |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with "artifacts" key containing list of Artifact objects |
Source code in cuvis_ai/node/anomaly_visualization.py
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 | |
ScoreHeatmapVisualizer
¶
Bases: Node
Log LAD/RX score heatmaps as TensorBoard artifacts.
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
Generate heatmap visualizations of anomaly scores.
Creates color-mapped heatmaps of anomaly scores for visualization in TensorBoard. Optionally normalizes scores to [0, 1] range for consistent visualization across batches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
Tensor
|
Anomaly scores [B, H, W, 1] from detection nodes (e.g., RX, LAD). |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx information. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, list[Artifact]]
|
Dictionary with "artifacts" key containing list of heatmap artifacts. |
Source code in cuvis_ai/node/anomaly_visualization.py
RGBAnomalyMask
¶
Bases: Node
Visualize anomaly detection with GT and predicted masks on RGB images.
Similar to AnomalyMask but designed for RGB images (e.g., from band selectors). Creates side-by-side visualizations showing ground truth masks, predicted masks, and overlay comparisons on RGB images. The overlay shows:
- Green: True Positives (correct anomaly detection)
- Red: False Positives (false alarms)
- Yellow: False Negatives (missed anomalies)
Also displays IoU and other metrics. Returns a list of Artifact objects for logging to monitoring systems.
Executes during validation and inference stages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
up_to
|
int
|
Maximum number of images to visualize. If None, visualizes all (default: None) |
None
|
Examples:
>>> decider = BinaryDecider(threshold=0.2)
>>> viz_mask = RGBAnomalyMask(up_to=5)
>>> tensorboard_node = TensorBoardMonitorNode(output_dir="./runs")
>>> graph.connect(
... (decider.decisions, viz_mask.decisions),
... (data_node.mask, viz_mask.mask),
... (band_selector.rgb_image, viz_mask.rgb_image),
... (viz_mask.artifacts, tensorboard_node.artifacts),
... )
Initialize RGBAnomalyMask visualizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
up_to
|
int | None
|
Maximum number of images to visualize. If None, visualizes all (default: None) |
None
|
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
Create anomaly mask visualizations with GT/pred comparison on RGB images.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
decisions
|
Tensor
|
Binary anomaly decisions [B, H, W, 1] |
required |
rgb_image
|
Tensor
|
RGB image [B, H, W, 3] for visualization |
required |
mask
|
Tensor | None
|
Ground truth anomaly mask [B, H, W, 1] (optional) |
None
|
context
|
Context | None
|
Execution context with stage, epoch, batch_idx |
None
|
scores
|
Tensor | None
|
Optional anomaly logits/scores [B, H, W, 1] |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with "artifacts" key containing list of Artifact objects |
Source code in cuvis_ai/node/anomaly_visualization.py
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 | |
ChannelSelectorFalseRGBViz
¶
ChannelSelectorFalseRGBViz(
mask_overlay_alpha=0.4,
max_samples=4,
log_every_n_batches=1,
**kwargs,
)
Bases: ImageArtifactVizBase
Visualize false RGB output from channel selectors with optional mask overlay.
Produces per-sample image artifacts:
false_rgb_sample_{b}: Normalized false RGB image [H, W, 3]mask_overlay_sample_{b}: False RGB with red alpha-blend on foreground pixels (if mask provided)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_overlay_alpha
|
float
|
Alpha value for red mask overlay on foreground pixels (default: 0.4). |
0.4
|
max_samples
|
int
|
Maximum number of batch elements to visualize (default: 4). |
4
|
log_every_n_batches
|
int
|
Log every N-th batch (default: 1). |
1
|
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
Generate false RGB and mask overlay artifacts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rgb_output
|
Tensor
|
False RGB tensor [B, H, W, 3]. |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx. |
required |
mask
|
Tensor | None
|
Optional segmentation mask [B, H, W]. |
None
|
mesu_index
|
Tensor | None
|
Optional measurement indices [B] for frame-identified artifact naming. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, list[Artifact]]
|
Dictionary with "artifacts" key containing image artifacts. |
Source code in cuvis_ai/node/anomaly_visualization.py
MaskOverlayNode
¶
Bases: Node
Alpha-blend a coloured mask overlay onto RGB frames.
Pure PyTorch processing node (no matplotlib, no gradients). When mask is
None or entirely zero the input RGB is passed through unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha
|
float
|
Blend factor for the overlay colour (default: 0.4). |
0.4
|
overlay_color
|
tuple[float, float, float]
|
RGB overlay colour in [0, 1] (default: red |
(1.0, 0.0, 0.0)
|
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
Apply mask overlay to RGB frames.
Source code in cuvis_ai/node/anomaly_visualization.py
TrackingOverlayNode
¶
Bases: Node
Alpha-blend per-object coloured masks onto RGB frames.
Converts a SAM3-style label map (mask) into per-object binary masks and
renders a coloured overlay with optional contour lines and object-ID labels
using :func:cuvis_ai.utils.torch_draw.overlay_instances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha
|
float
|
Blend factor for the overlay colour (default 0.4). |
0.4
|
draw_contours
|
bool
|
Draw contour outlines on mask edges (default True). |
True
|
draw_ids
|
bool
|
Render numeric object-ID labels above each mask (default True). |
True
|
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
Render coloured per-object mask overlays onto rgb_image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rgb_image
|
Tensor
|
Single RGB frame |
required |
mask
|
Tensor
|
SAM3 label map |
required |
object_ids
|
Tensor or None
|
Active object IDs |
None
|
frame_id
|
Tensor or None
|
Frame / measurement index |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
|
Source code in cuvis_ai/node/anomaly_visualization.py
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 | |
TrackingPointerOverlayNode
¶
Bases: Node
Draw downward triangle pointers for all tracked objects.
The node is composable by design: it renders only the pointer markers on top
of an incoming RGB frame and does not perform any mask tinting itself.
Colours are derived from object IDs using the same palette as
:class:TrackingOverlayNode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha
|
float
|
Reserved for API compatibility with :class: |
0.4
|
draw_contours
|
bool
|
Reserved for API compatibility with :class: |
True
|
draw_ids
|
bool
|
Reserved for API compatibility with :class: |
True
|
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
Render pointer overlays for all objects onto rgb_image.
Source code in cuvis_ai/node/anomaly_visualization.py
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 | |
BBoxesOverlayNode
¶
BBoxesOverlayNode(
line_thickness=2,
draw_labels=False,
draw_sparklines=False,
sparkline_height=24,
hide_untracked=False,
**kwargs,
)
Bases: Node
Torch-only bounding-box overlay renderer for YOLO-style detections.
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
forward(
rgb_image,
bboxes,
category_ids,
frame_id=None,
confidences=None,
spectral_signatures=None,
**_,
)
Overlay bbox edges with deterministic per-class colors.
Source code in cuvis_ai/node/anomaly_visualization.py
ChannelWeightsViz
¶
Bases: ImageArtifactVizBase
Visualize channel mixer weights as a heatmap.
Produces a [K, C] mixing matrix heatmap with output channels on the
y-axis and input channels on the x-axis. Uses a diverging blue-white-red
colormap centred at zero so positive/negative contributions are immediately
visible.
Implemented in pure PyTorch (no matplotlib) so it adds negligible overhead to the training loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_samples
|
int
|
Ignored (weights are per-model, not per-sample). Kept for base class compatibility. Default: 1. |
1
|
log_every_n_batches
|
int
|
Log every N-th batch (default: 1). |
1
|
cell_height
|
int
|
Pixel height per matrix row (default: 40). |
60
|
cell_width
|
int
|
Pixel width per matrix column (default: 6). |
12
|
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
Generate mixing matrix heatmap artifact.
Pure-torch rendering with R/G/B indicator bars, grid lines, and a diverging colorbar — no matplotlib for training-loop speed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
Tensor
|
Mixing matrix |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx. |
required |
wavelengths
|
ndarray
|
Wavelengths |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, list[Artifact]]
|
Dictionary with |
Source code in cuvis_ai/node/anomaly_visualization.py
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 | |
render_bboxes_overlay_torch
¶
render_bboxes_overlay_torch(
rgb_image,
bboxes,
category_ids,
frame_id=None,
line_thickness=2,
draw_labels=False,
spectral_signatures=None,
sparkline_height=24,
)
Render bbox edges on RGB frames using pure torch drawing primitives.
Source code in cuvis_ai/node/anomaly_visualization.py
Pipeline Visualization¶
pipeline_visualization
¶
Pipeline and data visualization sink nodes for monitoring training progress.
CubeRGBVisualizer
¶
Bases: Node
Creates false-color RGB images from hyperspectral cube using channel weights.
Selects 3 channels with highest weights for R, G, B channels and creates a false-color visualization with wavelength annotations.
Source code in cuvis_ai/node/pipeline_visualization.py
forward
¶
Generate false-color RGB visualizations from hyperspectral cube.
Selects the 3 channels with highest weights and creates RGB images with wavelength annotations. Also generates a bar chart showing channel weights with the selected channels highlighted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
weights
|
Tensor
|
Channel selection weights [C] indicating importance of each channel. |
required |
wavelengths
|
Tensor
|
Wavelengths for each channel [C] in nanometers. |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx information. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, list[Artifact]]
|
Dictionary with "artifacts" key containing list of visualization artifacts. |
Source code in cuvis_ai/node/pipeline_visualization.py
PCAVisualization
¶
Bases: Node
Visualize PCA-projected data with scatter and image plots.
Creates visualizations for each batch element showing:
- Scatter plot of H*W points in 2D PC space (using first 2 PCs)
- Image representation of the 2D projection reshaped to [H, W, 2]
Points in scatter plot are colored by spatial position. Returns artifacts for monitoring systems.
Executes only during validation stage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
up_to
|
int
|
Maximum number of batch elements to visualize. If None, visualizes all (default: None) |
None
|
Examples:
>>> pca_viz = PCAVisualization(up_to=10)
>>> tensorboard_node = TensorBoardMonitorNode(output_dir="./runs")
>>> graph.connect(
... (pca.projected, pca_viz.data),
... (pca_viz.artifacts, tensorboard_node.artifacts),
... )
Source code in cuvis_ai/node/pipeline_visualization.py
forward
¶
Create PCA projection visualizations as Artifact objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
PCA-projected data tensor [B, H, W, C] (uses first 2 components) |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with "artifacts" key containing list of Artifact objects |
Source code in cuvis_ai/node/pipeline_visualization.py
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 | |
PipelineComparisonVisualizer
¶
Bases: Node
TensorBoard visualization node for comparing pipeline stages.
Creates image artifacts for logging to TensorBoard:
- Input HSI cube visualization (false-color RGB from selected channels)
- Mixer output (3-channel RGB-like image that downstream model sees)
- Ground truth anomaly mask
- Anomaly scores (as heatmap)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hsi_channels
|
list[int]
|
Channel indices to use for false-color RGB visualization of HSI input (default: [0, 20, 40] for a simple false-color representation) |
None
|
max_samples
|
int
|
Maximum number of samples to log per batch (default: 4) |
4
|
log_every_n_batches
|
int
|
Log images every N batches to reduce TensorBoard size (default: 1, log every batch) |
1
|
Source code in cuvis_ai/node/pipeline_visualization.py
forward
¶
Create image artifacts for TensorBoard logging.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hsi_cube
|
Tensor
|
Input HSI cube [B, H, W, C] |
required |
mixer_output
|
Tensor
|
Mixer output (RGB-like) [B, H, W, 3] |
required |
ground_truth_mask
|
Tensor
|
Ground truth anomaly mask [B, H, W, 1] |
required |
adaclip_scores
|
Tensor
|
Anomaly scores [B, H, W, 1] |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx info |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, list[Artifact]]
|
Dictionary with "artifacts" key containing list of Artifact objects |
Source code in cuvis_ai/node/pipeline_visualization.py
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 | |
Losses¶
losses
¶
Loss nodes for training pipeline (port-based architecture).
LossNode
¶
Bases: Node
Base class for loss nodes that restricts execution to training stages.
Loss nodes should not execute during inference - only during train, val, and test.
Source code in cuvis_ai/node/losses.py
OrthogonalityLoss
¶
Bases: LossNode
Orthogonality regularization loss for TrainablePCA.
Encourages PCA components to remain orthonormal during training. Loss = weight * ||W @ W.T - I||^2_F
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Weight for orthogonality loss (default: 1.0) |
1.0
|
Source code in cuvis_ai/node/losses.py
forward
¶
Compute weighted orthogonality loss from PCA components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
components
|
Tensor
|
PCA components matrix [n_components, n_features] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "loss" key containing weighted loss |
Source code in cuvis_ai/node/losses.py
AnomalyBCEWithLogits
¶
Bases: LossNode
Binary cross-entropy loss for anomaly detection with logits.
Computes BCE loss between predicted anomaly scores and ground truth masks. Uses BCEWithLogitsLoss for numerical stability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Overall weight for this loss component (default: 1.0) |
1.0
|
pos_weight
|
float
|
Weight for positive class (anomaly) to handle class imbalance (default: None) |
None
|
reduction
|
str
|
Reduction method: 'mean', 'sum', or 'none' (default: 'mean') |
'mean'
|
Source code in cuvis_ai/node/losses.py
forward
¶
Compute weighted BCE loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictions
|
Tensor
|
Predicted scores [B, H, W, 1] |
required |
targets
|
Tensor
|
Ground truth masks [B, H, W, 1] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "loss" key containing scalar loss |
Source code in cuvis_ai/node/losses.py
MSEReconstructionLoss
¶
Bases: LossNode
Mean squared error reconstruction loss.
Computes MSE between reconstruction and target. Useful for autoencoder-style architectures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Weight for this loss component (default: 1.0) |
1.0
|
reduction
|
str
|
Reduction method: 'mean', 'sum', or 'none' (default: 'mean') |
'mean'
|
Source code in cuvis_ai/node/losses.py
forward
¶
Compute MSE reconstruction loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reconstruction
|
Tensor
|
Reconstructed data |
required |
target
|
Tensor
|
Target for reconstruction |
required |
**_
|
Any
|
Additional arguments (e.g., context) - ignored but accepted for compatibility |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "loss" key containing scalar loss |
Source code in cuvis_ai/node/losses.py
DistinctnessLoss
¶
Bases: LossNode
Repulsion loss encouraging different selectors to choose different bands.
This loss is designed for band/channel selector nodes that output a
2D weight matrix [output_channels, input_channels]. It computes the
mean pairwise cosine similarity between all pairs of selector weight
vectors and penalizes high similarity:
.. math::
L_\text{repel} = \frac{1}{N_\text{pairs}} \sum_{i < j}
\cos(\mathbf{w}_i, \mathbf{w}_j)
Minimizing this loss encourages selectors to focus on different bands, preventing the common failure mode where all channels collapse onto the same band.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Overall weight for this loss component (default: 0.1). |
0.1
|
eps
|
float
|
Small constant for numerical stability when normalizing (default: 1e-6). |
1e-06
|
Source code in cuvis_ai/node/losses.py
forward
¶
Compute mean pairwise cosine similarity penalty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
selection_weights
|
Tensor
|
Weight matrix of shape [output_channels, input_channels]. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with a single key |
Source code in cuvis_ai/node/losses.py
SelectorEntropyRegularizer
¶
Bases: LossNode
Entropy regularization for SoftChannelSelector.
Encourages exploration by penalizing low-entropy (over-confident) selections. Computes entropy from selection weights and applies regularization.
Higher entropy = more uniform selection (encouraged early in training) Lower entropy = more peaked selection (emerges naturally as training progresses)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Weight for entropy regularization (default: 0.01) Positive weight encourages exploration (maximizes entropy) Negative weight encourages exploitation (minimizes entropy) |
0.01
|
target_entropy
|
float
|
Target entropy for regularization (default: None, no target) If set, uses squared error: (entropy - target)^2 |
None
|
eps
|
float
|
Small constant for numerical stability (default: 1e-6) |
1e-06
|
Source code in cuvis_ai/node/losses.py
forward
¶
Compute entropy regularization loss from selection weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
Tensor
|
Channel selection weights [n_channels] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "loss" key containing regularization loss |
Source code in cuvis_ai/node/losses.py
SelectorDiversityRegularizer
¶
Bases: LossNode
Diversity regularization for SoftChannelSelector.
Encourages diverse channel selection by penalizing concentration on few channels. Uses negative variance to encourage spread (higher variance = more diverse).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Weight for diversity regularization (default: 0.01) |
0.01
|
Source code in cuvis_ai/node/losses.py
forward
¶
Compute weighted diversity loss from selection weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
Tensor
|
Channel selection weights [n_channels] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "loss" key containing weighted loss |
Source code in cuvis_ai/node/losses.py
DeepSVDDSoftBoundaryLoss
¶
Bases: LossNode
Soft-boundary Deep SVDD objective operating on BHWD embeddings.
Source code in cuvis_ai/node/losses.py
forward
¶
Compute Deep SVDD soft-boundary loss.
The loss consists of the hypersphere radius R² plus a slack penalty for points outside the hypersphere. The radius R is learned via an unconstrained parameter with softplus activation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embeddings
|
Tensor
|
Embedded feature representations [B, H, W, D] from the network. |
required |
center
|
Tensor
|
Center of the hypersphere [D] computed during initialization. |
required |
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "loss" key containing the scalar loss value. |
Notes
The loss formula is: loss = weight * (R² + (1/ν) * mean(ReLU(dist - R²))) where dist is the squared distance from embeddings to the center.
Source code in cuvis_ai/node/losses.py
IoULoss
¶
Bases: LossNode
Differentiable IoU (Intersection over Union) loss.
Computes: 1 - (|A ∩ B| + smooth) / (|A U B| + smooth) Works directly on continuous scores (not binary decisions), preserving gradients.
The scores are normalized to [0, 1] range using sigmoid or clamp before computing IoU, ensuring differentiability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Overall weight for this loss component (default: 1.0) |
1.0
|
smooth
|
float
|
Small constant for numerical stability (default: 1e-6) |
1e-06
|
normalize_method
|
('sigmoid', 'clamp', 'minmax')
|
Method to normalize predictions to [0, 1] range (default: "sigmoid")
|
"sigmoid"
|
Examples:
>>> iou_loss = IoULoss(weight=1.0, smooth=1e-6)
>>> # Use with AdaClip scores directly (no thresholding needed)
>>> loss = iou_loss.forward(predictions=adaclip_scores, targets=ground_truth_mask)
Source code in cuvis_ai/node/losses.py
forward
¶
Compute differentiable IoU loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictions
|
Tensor
|
Predicted anomaly scores [B, H, W, 1] (any real values) |
required |
targets
|
Tensor
|
Ground truth binary masks [B, H, W, 1] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "loss" key containing scalar IoU loss |
Source code in cuvis_ai/node/losses.py
ForegroundContrastLoss
¶
ForegroundContrastLoss(
weight=1.0,
compactness_weight=0.0,
anchor_weight=0.0,
eps=1e-06,
color_space="rgb",
assume_srgb=True,
**kwargs,
)
Bases: LossNode
Maximize visual separation between foreground and background mean colors.
Loss per image::
-||mean_fg - mean_bg||_2
+ compactness_weight * Var_fg
+ anchor_weight * (||mean_fg - mean_img||^2 + ||mean_bg - mean_img||^2)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Overall weight for this loss component (default: 1.0). |
1.0
|
compactness_weight
|
float
|
Weight for foreground variance penalty (default: 0.0, disabled). |
0.0
|
anchor_weight
|
float
|
Anti-gaming penalty that keeps fg/bg means near the image mean, discouraging extreme color pushes (default: 0.0, disabled). |
0.0
|
eps
|
float
|
Small constant for numerical stability in sqrt (default: 1e-6). |
1e-06
|
color_space
|
``"rgb"`` or ``"oklab"``
|
Color space in which to compute the fg/bg distance (default: |
'rgb'
|
assume_srgb
|
bool
|
When |
True
|
Notes
-
When
color_space="oklab", the OKLab conversion expects linear RGB in [0, 1]. If the upstream RGB has no sRGB gamma curve applied (e.g. output ofLearnableChannelMixerwithnormalize_output=True), setassume_srgb=False. -
Vectorized over batch.
- Fallback loss uses
0.0 * rgb.sum()so it remains connected to the model graph.
Source code in cuvis_ai/node/losses.py
forward
¶
Compute foreground/background contrast loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rgb
|
Tensor
|
RGB image tensor of shape [B, H, W, 3]. |
required |
mask
|
Tensor
|
Segmentation mask of shape [B, H, W] where values > 0 are foreground. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with a single key |
Source code in cuvis_ai/node/losses.py
Labels¶
labels
¶
Label Mapping Nodes.
This module provides nodes for converting multi-class segmentation masks to binary anomaly labels. These nodes are useful when training with datasets that have multi-class annotations but the task requires binary anomaly detection.
The main node remaps class IDs to binary labels (0=normal, 1=anomaly) based on configurable normal and anomaly class ID lists.
See Also
cuvis_ai.deciders : Binary decision nodes for threshold-based classification
BinaryAnomalyLabelMapper
¶
Bases: Node
Convert multi-class segmentation masks to binary anomaly targets.
Masks are remapped to torch.long tensors with 0 representing normal pixels and 1 indicating anomalies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
normal_class_ids
|
Iterable[int]
|
Class IDs that should be considered normal (default: (0, 2)). |
required |
anomaly_class_ids
|
Iterable[int] | None
|
Explicit anomaly IDs. When |
None
|
Source code in cuvis_ai/node/labels.py
forward
¶
Map multi-class labels to binary anomaly labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Features/scores to pass through [B, H, W, C] |
required |
mask
|
Tensor
|
Multi-class segmentation masks [B, H, W, 1] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "cube" (pass-through) and "mask" (binary bool) keys |