Nodes Catalog¶
Every node available in cuvis-ai pipelines, in one place. Built-in nodes ship
with the cuvis_ai package; plugin nodes and data modules come from
separately-installable plugin manifests — see
Plugin Development.

AdaCLIPFocalDiceLosscuvis_ai_adaclip.node.losseslossCombined Focal + Dice loss for AdaCLIP training.
Combined Focal + Dice loss for AdaCLIP training.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
predictions |
float32 |
[-1, -1, -1, 1] |
Aggregated anomaly scores [B, H, W, 1] for fallback path |
targets |
bool |
[-1, -1, -1, 1] |
Ground truth binary masks [B, H, W, 1] |
per_layer_scores optional |
float32 |
[-1, -1, -1, -1] |
Per-layer softmaxed maps [B, num_layers*2, H, W] |
image_score_2ch optional |
float32 |
[-1, -1] |
Image-level score [B, 2] in [normal, anomaly] order |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
loss |
float32 |
any |
Combined focal + dice loss |

AnomalyBCEWithLogitscuvis_ai.node.losseslossBinary cross-entropy loss for anomaly detection with logits.
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

CrossEntropyLosscuvis_ai.node.losseslossPixel-wise cross-entropy over dense segmentation logits (``K >= 2``).
CrossEntropyLoss
¶
Bases: LossNode
Pixel-wise cross-entropy over dense segmentation logits (K >= 2).
Consumes BHWC per-pixel class logits plus an integer class-index mask and
emits a scalar loss. The class count is the logits' last axis; no
num_classes hyperparameter is needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Scalar multiplier applied to the loss (default: 1.0) |
1.0
|
class_weights
|
list of float or None
|
Per-class rescaling passed to |
None
|
ignore_index
|
int
|
Target value excluded from the loss (default: -100, PyTorch's default) |
-100
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the logits carry a single class channel ( |
Examples:
>>> ce = CrossEntropyLoss(class_weights=[0.1, 1.0])
>>> loss = ce.forward(logits=logits_bhwk, targets=mask_bhw)["loss"]
Source code in cuvis_ai/node/losses.py
forward
¶
Compute the weighted cross-entropy from BHWC logits and a mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Per-pixel class logits [B, H, W, K] |
required |
targets
|
Tensor
|
Integer class-index mask [B, H, W] (a trailing singleton channel is squeezed) |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "loss" key containing the scalar cross-entropy |
Source code in cuvis_ai/node/losses.py

DeepSVDDSoftBoundaryLosscuvis_ai.node.losseslossSoft-boundary Deep SVDD objective operating on BHWD embeddings.
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

DiceLosscuvis_ai.node.losseslossSoft Dice loss over dense segmentation logits.
DiceLoss
¶
Bases: LossNode
Soft Dice loss over dense segmentation logits.
Consumes BHWC per-pixel class logits (last axis = classes; the class count
is inferred at runtime, K == 1 is treated as sigmoid binary, K > 1
as softmax multiclass over one-hot targets) plus an integer class-index
mask, and emits a scalar loss 1 - mean(dice). Dice is accumulated per
class over the whole batch (nnU-Net-style batch Dice) rather than averaged
per sample. Multiclass targets outside [0, K) that are not
ignore_index raise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Scalar multiplier applied to the loss, for combining several losses (default: 1.0) |
1.0
|
ignore_index
|
int or None
|
Target value excluded from both prediction and target, or |
None
|
include_background
|
bool
|
Whether class 0 contributes to the per-class Dice mean; multiclass only (default: True). Disabling it is the standard choice for heavily imbalanced segmentation, where the background Dice term is saturated and dilutes the foreground signal. |
True
|
eps
|
float
|
Smoothing constant for the Dice ratio (default: 1e-6) |
1e-06
|
Examples:
>>> dice = DiceLoss(weight=1.0, include_background=False)
>>> loss = dice.forward(logits=logits_bhwk, targets=mask_bhw)["loss"]
Source code in cuvis_ai/node/losses.py
forward
¶
Compute the weighted soft Dice loss from BHWC logits and a mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Per-pixel class logits [B, H, W, K] |
required |
targets
|
Tensor
|
Integer class-index mask [B, H, W] (a trailing singleton channel is squeezed) |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "loss" key containing the scalar Dice loss |
Source code in cuvis_ai/node/losses.py

DinomalyTrainLossBridgecuvis_ai_dinomaly.node.dinomaly_train_loss_bridgelossPasses through the scalar reconstruction loss from :class:`DinomalyDetector`.
Passes through the scalar reconstruction loss from :class:DinomalyDetector.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
raw_loss optional |
float32 |
any |
Scalar training loss from DinomalyDetector |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
loss |
float32 |
any |
Weighted loss for backprop |

DistinctnessLosscuvis_ai.node.losseslossRepulsion loss encouraging different selectors to choose different bands.
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:
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

ForegroundContrastLosscuvis_ai.node.losseslossMaximize visual separation between foreground and background mean colors.
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

IoULosscuvis_ai.node.losseslossDifferentiable IoU (Intersection over Union) loss.
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 anomaly scores directly (no thresholding needed)
>>> loss = iou_loss.forward(predictions=anomaly_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

LossNodecuvis_ai.node.losseslossBase class for loss nodes that restricts execution to training stages.
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

MSEReconstructionLosscuvis_ai.node.losseslossMean squared error reconstruction loss.
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

WeightedCrossEntropyLosscuvis_ai_inspecscrap.node.lossesloss

AnomalyAUROCMetricscuvis_ai_dinomaly.node.auroc_metricsmetricStreaming pixel/image AUROC via torchmetrics (val/test only).
Streaming pixel/image AUROC via torchmetrics (val/test only).
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
scores |
float32 |
[-1, -1, -1, 1] |
Raw anomaly map [B, H, W, 1] |
targets |
bool |
[-1, -1, -1, 1] |
Ground-truth pixel masks [B, H, W, 1] |
anomaly_score |
float32 |
[-1] |
Per-image anomaly score [B] |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
metrics |
any |
any |
List of Metric objects (running AUROC) |

AnomalyDetectionMetricscuvis_ai.node.metricsmetricCompute anomaly detection metrics (precision, recall, F1, etc.).
AnomalyDetectionMetrics
¶
Bases: Node
Compute anomaly detection metrics (precision, recall, F1, etc.).
Uses torchmetrics for GPU-optimized, robust metric computation. Expects binary decisions and targets to be binary masks. Executes only during validation and test stages.
Source code in cuvis_ai/node/metrics.py
forward
¶
Compute anomaly detection metrics using torchmetrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
decisions
|
Tensor
|
Binary anomaly decisions [B, H, W, 1] |
required |
targets
|
Tensor
|
Ground truth binary masks [B, H, W, 1] |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "metrics" key containing list of Metric objects |
Source code in cuvis_ai/node/metrics.py
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 | |
pooled_metrics
¶
Live torchmetrics objects for the epoch-pooled metrics, keyed by name.
average_precision accumulates across the epoch (reset only at the
(stage, epoch) boundary), so the trainer logs this object with
on_epoch=True and Lightning computes the single pooled AP and resets
it at epoch end, exact and batch-size-invariant. Returns an empty mapping
until at least one batch with logits has been seen, so nothing is
logged for a run that never produced scores.
Source code in cuvis_ai/node/metrics.py

AnomalyPixelStatisticsMetriccuvis_ai.node.metricsmetricCompute anomaly pixel statistics from binary decisions.
AnomalyPixelStatisticsMetric
¶
Bases: Node
Compute anomaly pixel statistics from binary decisions.
Calculates total pixels, anomalous pixels count, and anomaly percentage. Useful for monitoring the proportion of detected anomalies in batches. Executes only during validation and test stages.
Source code in cuvis_ai/node/metrics.py
forward
¶
Compute anomaly pixel statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
decisions
|
Tensor
|
Binary anomaly decisions [B, H, W, 1] |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "metrics" key containing list of Metric objects |
Source code in cuvis_ai/node/metrics.py

CLEARMetricNodecuvis_ai_trackeval.nodemetricAccumulate per-frame tracking data and compute CLEAR metrics in finalize().
Accumulate per-frame tracking data and compute CLEAR metrics in finalize().
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
frame_id |
int64 |
[1] |
|
pred_frame_id optional |
int64 |
[1] |
|
gt_bboxes |
float32 |
[1, -1, 4] |
|
gt_track_ids |
int64 |
[1, -1] |
|
pred_bboxes |
float32 |
[1, -1, 4] |
|
pred_track_ids |
int64 |
[1, -1] |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
mota |
float32 |
[1] |
MOTA |
motp |
float32 |
[1] |
MOTP |
fp |
int64 |
[1] |
False positives |
fn |
int64 |
[1] |
False negatives |
idsw |
int64 |
[1] |
ID switches |

ComponentOrthogonalityMetriccuvis_ai.node.metricsmetricTrack orthogonality of PCA components during training.
ComponentOrthogonalityMetric
¶
Bases: Node
Track orthogonality of PCA components during training.
Measures how close the component matrix is to being orthonormal. Executes only during validation and test stages.
Source code in cuvis_ai/node/metrics.py
forward
¶
Compute component orthogonality metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
components
|
Tensor
|
PCA components matrix [n_components, n_features] |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "metrics" key containing list of Metric objects |
Source code in cuvis_ai/node/metrics.py

DistinctLabelCountcuvis_ai.node.metricsmetricCount the distinct non-zero labels per frame in an integer label map.
DistinctLabelCount
¶
Bases: Node
Count the distinct non-zero labels per frame in an integer label map.
Reports how many separate segments a label map contains, e.g. how many compartments survived
a per-blob majority vote or how many clusters a frame holds. Emits the per-frame count both as
a count tensor (for pipeline reads / notebook printing) and as Metric objects for
training-time logging. Defaults to ExecutionStage.ALWAYS so it also runs under Predictor
inference, not only validation / test.
Source code in cuvis_ai/node/metrics.py
forward
¶
Count distinct non-zero labels in each frame of mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
|
Tensor
|
Integer label map [B, H, W]; 0 is background. |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
Source code in cuvis_ai/node/metrics.py

ExplainedVarianceMetriccuvis_ai.node.metricsmetricTrack explained variance ratio for PCA components.
ExplainedVarianceMetric
¶
Bases: Node
Track explained variance ratio for PCA components.
Executes only during validation and test stages.
Source code in cuvis_ai/node/metrics.py
forward
¶
Compute explained variance metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
explained_variance_ratio
|
Tensor
|
Explained variance ratios from PCA node |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "metrics" key containing list of Metric objects |
Source code in cuvis_ai/node/metrics.py

HOTAMetricNodecuvis_ai_trackeval.nodemetricAccumulate per-frame tracking data and compute HOTA in finalize().
Accumulate per-frame tracking data and compute HOTA in finalize().
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
frame_id |
int64 |
[1] |
|
pred_frame_id optional |
int64 |
[1] |
|
gt_bboxes |
float32 |
[1, -1, 4] |
|
gt_track_ids |
int64 |
[1, -1] |
|
pred_bboxes |
float32 |
[1, -1, 4] |
|
pred_track_ids |
int64 |
[1, -1] |
|
pred_scores optional |
float32 |
[1, -1] |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
hota |
float32 |
[1] |
Mean HOTA |
deta |
float32 |
[1] |
Mean DetA |
assa |
float32 |
[1] |
Mean AssA |
loca |
float32 |
[1] |
Mean LocA |

IdentityMetricNodecuvis_ai_trackeval.nodemetricAccumulate per-frame tracking data and compute ID metrics in finalize().
Accumulate per-frame tracking data and compute ID metrics in finalize().
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
frame_id |
int64 |
[1] |
|
pred_frame_id optional |
int64 |
[1] |
|
gt_bboxes |
float32 |
[1, -1, 4] |
|
gt_track_ids |
int64 |
[1, -1] |
|
pred_bboxes |
float32 |
[1, -1, 4] |
|
pred_track_ids |
int64 |
[1, -1] |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
idf1 |
float32 |
[1] |
IDF1 |
idp |
float32 |
[1] |
IDP |
idr |
float32 |
[1] |
IDR |

MulticlassSegmentationMetricscuvis_ai_inspecscrap.node.metricsmetric

PerClassAnomalyAUROCcuvis_ai_dinomaly.node.per_class_aurocmetricStreaming one-vs-background pixel AUROC per class (val/test only).
Streaming one-vs-background pixel AUROC per class (val/test only).
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
scores |
float32 |
[-1, -1, -1, 1] |
Raw anomaly map [B, H, W, 1] |
class_mask |
int32 |
[-1, -1, -1, 1] |
Multi-class ground-truth mask [B, H, W, 1] (background_id = normal) |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
metrics |
any |
any |
List of Metric objects (running per-class AUROC) |

ScoreStatisticsMetriccuvis_ai.node.metricsmetricCompute statistical properties of score distributions.
ScoreStatisticsMetric
¶
Bases: Node
Compute statistical properties of score distributions.
Tracks mean, std, min, max, median, and quantiles of scores. Executes only during validation and test stages.
Source code in cuvis_ai/node/metrics.py
forward
¶
Compute score statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
Tensor
|
Score values [B, H, W] |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "metrics" key containing list of Metric objects |
Source code in cuvis_ai/node/metrics.py
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 | |

SelectorDiversityMetriccuvis_ai.node.metricsmetricTrack diversity of channel selection.
SelectorDiversityMetric
¶
Bases: Node
Track diversity of channel selection.
Measures how spread out the selection weights are across channels. Uses Gini coefficient - lower values indicate more diverse selection.
Executes only during validation and test stages.
Source code in cuvis_ai/node/metrics.py
forward
¶
Compute diversity metrics for selection weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
Tensor
|
Channel selection weights [n_channels] |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "metrics" key containing list of Metric objects |
Source code in cuvis_ai/node/metrics.py

SelectorEntropyMetriccuvis_ai.node.metricsmetricTrack entropy of channel selection distribution.
SelectorEntropyMetric
¶
Bases: Node
Track entropy of channel selection distribution.
Measures the uncertainty/diversity in channel selection weights. Higher entropy indicates more uniform selection (less confident). Lower entropy indicates more peaked selection (more confident).
Executes only during validation and test stages.
Source code in cuvis_ai/node/metrics.py
forward
¶
Compute entropy of selection weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
Tensor
|
Channel selection weights [n_channels] |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "metrics" key containing list of Metric objects |
Source code in cuvis_ai/node/metrics.py

AdaCLIPDetectorcuvis_ai_adaclip.node.adaclip_nodemodelAdaCLIP zero-shot anomaly detector node (plugin version).
AdaCLIP zero-shot anomaly detector node (plugin version).
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
rgb_image |
float32 |
[-1, -1, -1, 3] |
RGB image [B, H, W, 3] in float32 (0-1 or 0-255 range) |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
scores |
float32 |
[-1, -1, -1, 1] |
Pixel-level anomaly scores [B, H, W, 1] |
anomaly_score |
float32 |
[-1] |
Image-level anomaly score [B] |
per_layer_scores optional |
float32 |
[-1, -1, -1, -1] |
Per-layer softmaxed anomaly maps stacked as [B, num_layers*2, H, W]. Only populated during training when training_aggregation=False. Empty (1×1) tensor otherwise. |
image_score_2ch optional |
float32 |
[-1, -1] |
Image-level 2-channel score [B, 2] (softmaxed [normal, anomaly]). Only populated during training when training_aggregation=False. |

ConcreteChannelMixercuvis_ai.node.channel_mixermodelConcrete/Gumbel-Softmax channel mixer for hyperspectral cubes.
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:
The resulting weights are used to form K-channel RGB-like images:
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

DeepSVDDProjectioncuvis_ai.node.anomaly.deep_svddmodelProjection head that maps per-pixel features to Deep SVDD embeddings.
DeepSVDDProjection
¶
DeepSVDDProjection(
*,
in_channels,
rep_dim=32,
hidden=128,
kernel="linear",
n_rff=2048,
gamma=None,
mlp_forward_batch_size=65536,
**kwargs,
)
Bases: Node
Projection head that maps per-pixel features to Deep SVDD embeddings.
Source code in cuvis_ai/node/anomaly/deep_svdd.py
forward
¶
Project BHWC features into a latent embedding space.
Source code in cuvis_ai/node/anomaly/deep_svdd.py

DeepSVDDScorescuvis_ai.node.anomaly.deep_svddmodelConvert Deep SVDD embeddings + center vector into anomaly scores.
DeepSVDDScores
¶
Bases: Node
Convert Deep SVDD embeddings + center vector into anomaly scores.
forward
¶
Compute anomaly scores as squared distance from center.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embeddings
|
Tensor
|
Deep SVDD embeddings [B, H, W, D] from projection network. |
required |
center
|
Tensor
|
Center vector [D] from DeepSVDDCenterTracker. |
required |
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "scores" key containing squared distances [B, H, W, 1]. |
Source code in cuvis_ai/node/anomaly/deep_svdd.py

DinomalyDetectorcuvis_ai_dinomaly.node.dinomaly_detectormodelPixel-level anomaly detection using Anomalib's ``DinomalyModel``.
Pixel-level anomaly detection using Anomalib's DinomalyModel.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
rgb_image |
float32 |
[-1, -1, -1, -1] |
Channel-stacked image [B, H, W, C] in float32 (0–1 or 0–255). C must equal the detector's input_channels (default 3). |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
scores |
float32 |
[-1, -1, -1, 1] |
Pixel-wise anomaly scores [B, H, W, 1] |
anomaly_score |
float32 |
[-1] |
Image-level anomaly score [B] |
training_loss optional |
float32 |
any |
Scalar Dinomaly training loss (train/val/test stages) |

GaussianMixtureClusterercuvis_ai.node.clustering.gmmmodelCluster pixel spectra with a Gaussian mixture model.
GaussianMixtureClusterer
¶
GaussianMixtureClusterer(
n_components=3,
covariance_type="full",
reg_covar=1e-06,
max_iter=100,
n_init=1,
random_state=0,
**kwargs,
)
Bases: _StatisticalFitNode
Cluster pixel spectra with a Gaussian mixture model.
The node is fitted once via statistical_initialization (scikit-learn's
GaussianMixture). The means, mixture weights, and Cholesky factors of
the precision matrices fully determine the Gaussian log-probabilities, so
they are frozen as torch buffers and the forward pass needs no sklearn.
Only covariance_type="full" is supported: the torch forward assumes a
[K, C, C] Cholesky factor, so __init__ rejects any other value with
ValueError rather than failing later at inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_components
|
int
|
Number of mixture components (default: 3). |
3
|
covariance_type
|
str
|
scikit-learn covariance parametrization; only |
'full'
|
reg_covar
|
float
|
Non-negative regularization added to the covariance diagonals at fit for numerical stability (default: 1e-6). |
1e-06
|
max_iter
|
int
|
Maximum EM iterations at fit (default: 100). |
100
|
n_init
|
int
|
Number of seeded EM re-initializations at fit (default: 1). |
1
|
random_state
|
int
|
Seed for the sklearn fit, for reproducible parameters (default: 0). |
0
|
**kwargs
|
Any
|
Forwarded to |
{}
|
Attributes:
| Name | Type | Description |
|---|---|---|
means |
Tensor
|
Component means, shape |
precisions_chol |
Tensor
|
Cholesky factors of the precision matrices, shape |
weights |
Tensor
|
Mixture weights, shape |
Store mixture hyperparameters and register the fitted-state buffers.
Source code in cuvis_ai/node/clustering/gmm.py
forward
¶
Evaluate the mixture posterior for every pixel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Input hyperspectral cube |
required |
**_
|
Any
|
Additional unused keyword arguments (e.g. the pipeline |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/clustering/gmm.py

KMeansClusterercuvis_ai.node.clustering.kmeansmodelPartition pixel spectra into ``n_clusters`` groups by nearest centroid.
KMeansClusterer
¶
KMeansClusterer(
n_clusters=8,
init="k-means++",
n_init=10,
max_iter=300,
random_state=0,
**kwargs,
)
Bases: _StatisticalFitNode
Partition pixel spectra into n_clusters groups by nearest centroid.
The node is fitted once via statistical_initialization (scikit-learn's
KMeans); the resulting centroids are stored as a torch buffer. At
inference each pixel is assigned to its nearest centroid in Euclidean
space, emitting the 0-based cluster id and the distance to that centroid.
Cluster ids are emitted directly in the range 0 .. n_clusters - 1 (no
background / -1 sentinel is used).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_clusters
|
int
|
Number of clusters to fit (default: 8). |
8
|
init
|
str
|
scikit-learn |
'k-means++'
|
n_init
|
int
|
Number of seeded re-initializations sklearn runs at fit (default: 10). |
10
|
max_iter
|
int
|
Maximum Lloyd iterations per run (default: 300). |
300
|
random_state
|
int
|
Seed for the sklearn fit, for reproducible centroids (default: 0). |
0
|
**kwargs
|
Any
|
Forwarded to |
{}
|
Attributes:
| Name | Type | Description |
|---|---|---|
centroids |
Tensor
|
Fitted cluster centers, shape |
Store K-means hyperparameters and register the centroid buffer.
Source code in cuvis_ai/node/clustering/kmeans.py
forward
¶
Assign each pixel to its nearest centroid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Input hyperspectral cube |
required |
**_
|
Any
|
Additional unused keyword arguments (e.g. the pipeline |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/clustering/kmeans.py

LADGlobalcuvis_ai.node.anomaly.lad_detectormodelLaplacian Anomaly Detector (global), variant 'C' (Cauchy), port-based.
LADGlobal
¶
Bases: Node
Laplacian Anomaly Detector (global), variant 'C' (Cauchy), port-based.
This is the new cuvis.ai v3 implementation of the LAD detector. It follows the
same mathematical definition as the legacy v2 LADGlobal, but exposes a
port-based interface compatible with CuvisPipeline, StatisticalTrainer,
and GradientTrainer.
Ports
INPUT_SPECS
data : float32, shape (-1, -1, -1, -1)
Input hyperspectral cube in BHWC format.
OUTPUT_SPECS
scores : float32, shape (-1, -1, -1, 1)
Per pixel anomaly scores in BHW1 format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eps
|
float
|
Small epsilon value for numerical stability in Laplacian construction. |
1e-8
|
normalize_laplacian
|
bool
|
If True, applies symmetric normalization: L = D^{-½} (D - A) D^{-½}. If False, uses unnormalized Laplacian: L = D - A. |
True
|
use_numpy_laplacian
|
bool
|
If True, constructs the Laplacian matrix using NumPy (float64, 1e-12 eps) for parity with reference implementations. If False, uses pure PyTorch. |
True
|
Training
After statistical initialization via statistical_initialization(), the node can be made trainable
by calling unfreeze(). This converts the mean M and Laplacian L buffers
to trainable nn.Parameter objects, enabling gradient-based fine-tuning.
Example
lad = LADGlobal(num_channels=61) stat_trainer = StatisticalTrainer(pipeline=pipeline, datamodule=datamodule) stat_trainer.fit() # Statistical initialization lad.unfreeze() # Enable gradient training grad_trainer = GradientTrainer(pipeline=pipeline, datamodule=datamodule, ...) grad_trainer.fit() # Gradient-based fine-tuning
Source code in cuvis_ai/node/anomaly/lad_detector.py
statistical_initialization
¶
Compute global mean M and Laplacian L from a port-based input stream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterator yielding dicts matching INPUT_SPECS.
Expected format: |
required |
Source code in cuvis_ai/node/anomaly/lad_detector.py
update
¶
Update running mean statistics from a BHWC batch.
Source code in cuvis_ai/node/anomaly/lad_detector.py
finalize
¶
Finalize mean and Laplacian from accumulated statistics.
Source code in cuvis_ai/node/anomaly/lad_detector.py
reset
¶
Reset all statistics and model parameters to initial state.
Clears the streaming mean accumulator (_mean_run), sample count (_count), global mean (M), and Laplacian matrix (L). After reset, the detector must be re-initialized via statistical_initialization() before inference.
Notes
Use this method to re-initialize the detector with different training data or when switching between different spectral distributions.
Source code in cuvis_ai/node/anomaly/lad_detector.py
forward
¶
Compute LAD anomaly scores for a BHWC cube.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor in BHWC format. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with key |
Source code in cuvis_ai/node/anomaly/lad_detector.py

LearnableChannelMixercuvis_ai.node.channel_mixermodelLearnable channel mixer for hyperspectral data reduction (DRCNN-style).
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
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 251 252 253 254 255 256 257 258 259 260 261 | |
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
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 477 478 479 480 481 482 483 484 485 486 487 | |

NMFUnmixingcuvis_ai.node.unmixing.nmfmodelBlind unmixing: learn endmembers by NMF, then solve per-pixel abundances.
NMFUnmixing
¶
NMFUnmixing(
n_components=3,
init="nndsvda",
beta_loss="frobenius",
max_iter=300,
random_state=0,
**kwargs,
)
Bases: _StatisticalFitNode
Blind unmixing: learn endmembers by NMF, then solve per-pixel abundances.
During statistical_initialization the node fits
:class:sklearn.decomposition.NMF on the collected training pixels and stores
the learned components [K, C] as a frozen buffer. At inference it solves
min_{x >= 0} ||A x - b|| per pixel against those frozen endmembers
(A = endmembers.T) with batched projected-gradient descent, emitting
abundances, the learned endmembers, the per-pixel reconstruction residual, and
a 1-based argmax class mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_components
|
int
|
Number of endmembers |
3
|
init
|
str
|
sklearn NMF initialization scheme (default: |
'nndsvda'
|
beta_loss
|
str
|
sklearn NMF beta-divergence loss (default: |
'frobenius'
|
max_iter
|
int
|
Maximum sklearn NMF solver iterations at fit time (default: 300). |
300
|
random_state
|
int
|
Seed for the sklearn NMF solver (default: 0). |
0
|
**kwargs
|
Any
|
Forwarded to :class: |
{}
|
Source code in cuvis_ai/node/unmixing/nmf.py
forward
¶
Solve per-pixel abundances against the frozen learned endmembers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/unmixing/nmf.py

NNLSUnmixingcuvis_ai.node.unmixing.nnlsmodelUnmix each pixel into non-negative abundances of known endmembers.
NNLSUnmixing
¶
Bases: Node
Unmix each pixel into non-negative abundances of known endmembers.
Given a hyperspectral cube [B, H, W, C] and a set of K endmember
spectra [K, C], solve min_{x >= 0} ||A x - b|| for every pixel, where
A = endmembers.T has shape [C, K] and b is the pixel spectrum.
The solve runs as batched projected-gradient descent, so the node is
stateless and runs entirely in torch on the inputs' device.
Only non-negativity (ANC) is enforced, not sum-to-one (ASC): abundances are not constrained to sum to 1 (this is not FCLS).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_iter
|
int
|
Maximum projected-gradient iterations per forward call (default: 500). Close or collinear endmembers may need more to converge. |
500
|
tol
|
float
|
Early-stop threshold on the per-iteration update norm (default: 1e-6). |
1e-06
|
min_total
|
float
|
Pixels whose summed abundance falls below this value are labelled
background (class 0) in |
0.0
|
**kwargs
|
Any
|
Forwarded to :class: |
{}
|
Source code in cuvis_ai/node/unmixing/nnls.py
forward
¶
Solve per-pixel non-negative least squares against the endmembers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube |
required |
endmembers
|
Tensor
|
Endmember spectra |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/unmixing/nnls.py

OSNetExtractorcuvis_ai_deepeiou.nodemodelOSNet x1.0 feature extractor (512-dim embeddings).
OSNet x1.0 feature extractor (512-dim embeddings).
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
crops |
float32 |
[-1, 3, -1, -1] |
Normalized crops [N, 3, crop_h, crop_w] in NCHW. |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
embeddings |
float32 |
[-1, -1, -1] |
L2-normalised embeddings [B, N, D]. |

OneClassSVMDetectorcuvis_ai.node.svmmodelOne-class SVM novelty detector (sklearn fit, pure-torch RBF forward).
OneClassSVMDetector
¶
Bases: _StatisticalFitNode
One-class SVM novelty detector (sklearn fit, pure-torch RBF forward).
During statistical_initialization the node collects background pixels
and fits a :class:sklearn.svm.OneClassSVM. The fitted estimator is reduced
to torch buffers (support vectors, dual coefficients, resolved gamma and
the offset) so that forward can evaluate the RBF decision function in
pure torch, chunked over the pixel axis to bound peak memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kernel
|
str
|
Kernel passed to scikit-learn at fit time. Only |
'rbf'
|
nu
|
float
|
Upper bound on the fraction of training outliers and lower bound on the
fraction of support vectors, in |
0.5
|
gamma
|
str or float
|
RBF kernel coefficient. Either a positive float or one of scikit-learn's
string presets ( |
'scale'
|
chunk_size
|
int
|
Number of pixels scored per chunk in |
65536
|
Attributes:
| Name | Type | Description |
|---|---|---|
support_vectors |
Tensor
|
Fitted support vectors |
dual_coef |
Tensor
|
Signed dual coefficients |
gamma_buf |
Tensor
|
Resolved scalar RBF |
offset_buf |
Tensor
|
Decision-function offset as a |
Examples:
>>> from cuvis_ai.node.svm import OneClassSVMDetector
>>> detector = OneClassSVMDetector(nu=0.1, gamma="scale")
>>> # detector.statistical_initialization(background_stream)
>>> # out = detector.forward(cube=cube)
>>> # scores, decisions = out["scores"], out["decisions"]
Store hyperparameters and register placeholder fit buffers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kernel
|
str
|
scikit-learn kernel; only |
'rbf'
|
nu
|
float
|
One-class SVM |
0.5
|
gamma
|
str or float
|
RBF kernel coefficient or a string preset (default: |
'scale'
|
chunk_size
|
int
|
Pixels scored per chunk in |
65536
|
**kwargs
|
Any
|
Forwarded to the statistical-fit base ( |
{}
|
Source code in cuvis_ai/node/svm.py
forward
¶
Score a cube with the signed RBF decision function, chunked over pixels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Input hyperspectral cube |
required |
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with:
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the node has not been initialized via
|
Source code in cuvis_ai/node/svm.py

RTSAM2BboxPropagationcuvis_ai_rtsam2.node.rtsam2_streaming_propagationmodelRTSAM2 propagation with runtime bbox prompts.
RTSAM2 propagation with runtime bbox prompts.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
rgb_image |
float32 |
[1, -1, -1, 3] |
RGB frame [1,H,W,3] in float32 with values in [0, 1]. |
frame_id optional |
int64 |
[1] |
Source frame index [1]. Preserved by upstream sinks. |
bboxes optional |
any |
any |
Optional per-frame list of bbox prompt dicts with keys element_id, object_id, x_min, y_min, x_max, y_max. |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
mask |
int32 |
[1, -1, -1] |
|
object_ids |
int64 |
[1, -1] |
|
detection_scores |
float32 |
[1, -1] |

RTSAM2MaskPropagationcuvis_ai_rtsam2.node.rtsam2_streaming_propagationmodelRTSAM2 propagation with runtime label-map prompts.
RTSAM2 propagation with runtime label-map prompts.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
rgb_image |
float32 |
[1, -1, -1, 3] |
RGB frame [1,H,W,3] in float32 with values in [0, 1]. |
frame_id optional |
int64 |
[1] |
Source frame index [1]. Preserved by upstream sinks. |
mask optional |
int32 |
[1, -1, -1] |
Optional int32 label map [1,H,W]. 0=background, each positive label is treated as an object ID prompt on that frame. |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
mask |
int32 |
[1, -1, -1] |
|
object_ids |
int64 |
[1, -1] |
|
detection_scores |
float32 |
[1, -1] |

RTSAM2PointExpansioncuvis_ai_rtsam2.node.rtsam2_point_expansionmodelExpand positive/negative click points into one object mask on a single frame.
Expand positive/negative click points into one object mask on a single frame.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
rgb_image |
float32 |
[1, -1, -1, 3] |
RGB frame [1,H,W,3] in float32 with values in [0, 1]. |
points optional |
any |
any |
Optional per-frame list of point prompt dicts with keys element_id, x, y, type (type in {positive, negative, neutral}). Positive=object, negative=background. |
frame_id optional |
int64 |
[1] |
Optional source frame index [1]; accepted for contract parity, unused. |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
mask |
int32 |
[1, -1, -1] |
|
object_ids |
int64 |
[1, -1] |
|
detection_scores |
float32 |
[1, -1] |

RXBasecuvis_ai.node.anomaly.rx_detectormodelBase class for RX anomaly detectors.

RXGlobalcuvis_ai.node.anomaly.rx_detectormodelRX anomaly detector with global background statistics.
RXGlobal
¶
Bases: RXBase
RX anomaly detector with global background statistics.
Uses global mean (μ) and covariance (Σ) estimated from training data to compute Mahalanobis distance scores. Supports two-phase training: statistical initialization followed by optional gradient-based fine-tuning.
The detector computes anomaly scores as:
RX(x) = (x - μ)ᵀ Σ⁻¹ (x - μ)
where x is a pixel spectrum, μ is the background mean, and Σ is the covariance matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_channels
|
int
|
Number of spectral channels in input data |
required |
eps
|
float
|
Small constant added to covariance diagonal for numerical stability (default: 1e-6) |
1e-06
|
cache_inverse
|
bool
|
If True, precompute and cache Σ⁻¹ for faster inference (default: True) |
True
|
**kwargs
|
dict
|
Additional arguments passed to Node base class |
{}
|
Attributes:
| Name | Type | Description |
|---|---|---|
mu |
Tensor or Parameter
|
Background mean spectrum, shape (C,). Initially a buffer, becomes Parameter after unfreeze() |
cov |
Tensor or Parameter
|
Background covariance matrix, shape (C, C) |
cov_inv |
Tensor or Parameter
|
Cached pseudo-inverse of covariance (if cache_inverse=True) |
_statistically_initialized |
bool
|
Flag indicating whether statistical_initialization() has been called |
Examples:
>>> from cuvis_ai.node.anomaly.rx_detector import RXGlobal
>>> from cuvis_ai_core.training import StatisticalTrainer
>>>
>>> # Create RX detector
>>> rx = RXGlobal(num_channels=61, eps=1.0e-6)
>>>
>>> # Phase 1: Statistical initialization
>>> stat_trainer = StatisticalTrainer(pipeline=pipeline, datamodule=datamodule)
>>> stat_trainer.fit() # Computes μ and Σ from training data
>>>
>>> # Inference with frozen statistics
>>> output = rx.forward(data=hyperspectral_cube)
>>> scores = output["scores"] # [B, H, W, 1]
>>>
>>> # Phase 2: Optional gradient-based fine-tuning
>>> rx.unfreeze() # Convert buffers to nn.Parameters
>>> # Now μ and Σ can be updated with gradient descent
See Also
RXPerBatch : Per-batch RX variant without training MinMaxNormalizer : Recommended preprocessing before RX ScoreToLogit : Convert scores to logits for classification docs/usecases/rx-statistical.md : Complete RX pipeline tutorial
Notes
After statistical_initialization(), mu and cov are stored as buffers (frozen by default). Call unfreeze() to convert them to trainable nn.Parameters for gradient-based optimization.
Source code in cuvis_ai/node/anomaly/rx_detector.py
statistical_initialization
¶
Initialize mu and Sigma 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 BHWC |
required |
Source code in cuvis_ai/node/anomaly/rx_detector.py
update
¶
Update streaming statistics with a new batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_bhwc
|
Tensor
|
Input batch in BHWC format, shape (B, H, W, C) |
required |
Source code in cuvis_ai/node/anomaly/rx_detector.py
finalize
¶
Compute final mean and covariance from accumulated streaming statistics.
This method converts the running accumulators (_mean, _M2) into the final mean (mu) and covariance (cov) matrices. The covariance is regularized with eps * I for numerical stability, and optionally caches the pseudo-inverse.
Returns:
| Type | Description |
|---|---|
RXGlobal
|
Returns self for method chaining |
Raises:
| Type | Description |
|---|---|
ValueError
|
If fewer than 2 samples were accumulated (insufficient for covariance estimation) |
Notes
After finalization, mu and cov are stored as buffers (frozen by default). Call unfreeze() to convert them to nn.Parameters for gradient-based training.
Source code in cuvis_ai/node/anomaly/rx_detector.py
reset
¶
Reset all statistics and accumulators to empty state.
Clears mu, cov, cov_inv, and all streaming accumulators (_mean, _M2, _n). After reset, the detector must be re-initialized via statistical_initialization() before it can be used for inference.
Notes
Use this method when you need to re-initialize the detector with different training data or when switching between different dataset distributions.
Source code in cuvis_ai/node/anomaly/rx_detector.py
forward
¶
Forward pass computing anomaly scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor in BHWC format |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "scores" key containing BHW1 anomaly scores |
Source code in cuvis_ai/node/anomaly/rx_detector.py

RXPerBatchcuvis_ai.node.anomaly.rx_detectormodelComputes μ, Σ per image in the batch on the fly; no fit/finalize.
RXPerBatch
¶
Bases: RXBase
Computes μ, Σ per image in the batch on the fly; no fit/finalize.
Source code in cuvis_ai/node/anomaly/rx_detector.py
forward
¶
Forward pass computing per-batch anomaly scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor in BHWC format |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "scores" key containing BHW1 anomaly scores |
Source code in cuvis_ai/node/anomaly/rx_detector.py

ResNetExtractorcuvis_ai_deepeiou.nodemodelResNet-50 feature extractor (2048-dim embeddings).
ResNet-50 feature extractor (2048-dim embeddings).
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
crops |
float32 |
[-1, 3, -1, -1] |
Normalized crops [N, 3, crop_h, crop_w] in NCHW. |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
embeddings |
float32 |
[-1, -1, -1] |
L2-normalised embeddings [B, N, D]. |

SAM3BboxPropagationcuvis_ai_sam3.nodemodelSAM3 streaming propagation with runtime bbox prompts.
SAM3 streaming propagation with runtime bbox prompts.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
rgb_image |
float32 |
[1, -1, -1, 3] |
|
frame_id optional |
int64 |
[1] |
Source frame index [1]. If omitted, local stream index is used. |
bboxes optional |
any |
any |
Optional per-frame list of bbox prompt dicts with keys element_id, object_id, x_min, y_min, x_max, y_max. |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
mask |
int32 |
[1, -1, -1] |
|
object_ids |
int64 |
[1, -1] |
|
detection_scores |
float32 |
[1, -1] |

SAM3MaskPropagationcuvis_ai_sam3.nodemodelSAM3 streaming propagation with runtime label-map prompts.
SAM3 streaming propagation with runtime label-map prompts.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
rgb_image |
float32 |
[1, -1, -1, 3] |
|
frame_id optional |
int64 |
[1] |
Source frame index [1]. If omitted, local stream index is used. |
mask optional |
int32 |
[1, -1, -1] |
Optional int32 label map [1,H,W]. 0=background, each positive label is treated as an object ID prompt on that frame. |
text_prompt optional |
any |
any |
Optional text description applied only while injecting the runtime mask prompt on the current frame. |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
mask |
int32 |
[1, -1, -1] |
|
object_ids |
int64 |
[1, -1] |
|
detection_scores |
float32 |
[1, -1] |

SAM3PointExpansioncuvis_ai_sam3.nodemodelExpand positive/negative click points into one object mask on a single frame.
Expand positive/negative click points into one object mask on a single frame.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
rgb_image |
float32 |
[1, -1, -1, 3] |
RGB frame [1,H,W,3] in float32 with values in [0,1]. |
points optional |
any |
any |
Optional per-frame list of point prompt dicts with keys element_id, x, y, type (type in {positive, negative, neutral}). Positive=object, negative=background. |
frame_id optional |
int64 |
[1] |
Optional source frame index [1]; keys the image-embedding cache. |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
mask |
int32 |
[1, -1, -1] |
|
object_ids |
int64 |
[1, -1] |
|
detection_scores |
float32 |
[1, -1] |

SAM3PointPropagationcuvis_ai_sam3.nodemodelSAM3 streaming propagation with a point prompt.
SAM3 streaming propagation with a point prompt.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
rgb_image |
float32 |
[1, -1, -1, 3] |
|
frame_id optional |
int64 |
[1] |
Source frame index [1]. If omitted, local stream index is used. |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
mask |
int32 |
[1, -1, -1] |
|
object_ids |
int64 |
[1, -1] |
|
detection_scores |
float32 |
[1, -1] |

SAM3SegmentEverythingcuvis_ai_sam3.nodemodelSegment everything on one RGB frame using SAM3 point-grid prompting.
Segment everything on one RGB frame using SAM3 point-grid prompting.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
rgb_image |
float32 |
[1, -1, -1, 3] |
RGB frame [1,H,W,3] in float32 with values in [0,1]. |
frame_id optional |
int64 |
[1] |
Optional source frame index [1]. Ignored by this stateless node. |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
mask |
int32 |
[1, -1, -1] |
|
object_ids |
int64 |
[1, -1] |
|
detection_scores |
float32 |
[1, -1] |

SAM3TextPropagationcuvis_ai_sam3.nodemodelSAM3 streaming propagation with a text/concept prompt.
SAM3 streaming propagation with a text/concept prompt.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
rgb_image |
float32 |
[1, -1, -1, 3] |
|
frame_id optional |
int64 |
[1] |
Source frame index [1]. If omitted, local stream index is used. |
text_prompt optional |
any |
any |
Optional text prompt applied on the current frame. |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
mask |
int32 |
[1, -1, -1] |
|
object_ids |
int64 |
[1, -1] |
|
detection_scores |
float32 |
[1, -1] |
|
category_ids |
int64 |
[1, -1] |
Category IDs [1,N], aligned with object_ids. |
category_semantics |
uint8 |
[-1] |
UTF-8 JSON bytes of the cumulative category-id-to-text mapping, for example {"1":"person","2":"car"}. |

SoftChannelSelectorcuvis_ai.node.channel_selectormodelSoft channel selector with temperature-based Gumbel-Softmax selection.
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

SpatialSpectralCNN2Dcuvis_ai_inspecscrap.node.classification.cnn2dmodel

SpectralAngleMappercuvis_ai.node.spectral_angle_mappermodelCompute per-pixel spectral angle against one or more reference spectra.
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

SpectralMLPClassifiercuvis_ai_inspecscrap.node.classification.mlpmodel

SpectralSpatialCNN3Dcuvis_ai_inspecscrap.node.classification.cnn3dmodel

SupervisedCIRSelectorcuvis_ai.node.channel_selectormodelSupervised CIR/NIR band selection with window constraints.
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

SupervisedFullSpectrumSelectorcuvis_ai.node.channel_selectormodelSupervised selection without window constraints.
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

SupervisedSelectorBasecuvis_ai.node.channel_selectormodelBase class for supervised band selection strategies.
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

SupervisedWindowedSelectorcuvis_ai.node.channel_selectormodelSupervised band selection constrained to visible RGB windows.
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

TrainablePCAcuvis_ai.node.dimensionality_reductionmodelTrainable PCA node with orthogonality regularization.
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

YOLO26Detectioncuvis_ai_ultralytics.nodemodelRun YOLO26 raw tensor inference on a stride-aligned CHW BGR batch.
Run YOLO26 raw tensor inference on a stride-aligned CHW BGR batch.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
preprocessed |
float32 |
[-1, 3, -1, -1] |
Channel-first BGR [B, 3, H', W'] from YOLOPreprocess |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
raw_preds |
float32 |
[-1, -1, -1] |
Raw YOLO prediction tensor |

_StatisticalFitNodecuvis_ai.node._statistical_fitmodelBase for nodes fitted once during statistical initialization.
_StatisticalFitNode
¶
Bases: Node
Base for nodes fitted once during statistical initialization.
Subclasses either implement _fit(pixels) (and let the default
statistical_initialization collect the pixel matrix), or override
statistical_initialization entirely (streaming-moment nodes) while
reusing _require_initialized / _reject_if_insufficient /
_mark_initialized from this base.
Store the fit-subsample budget and register the persistent fit flag.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_fit_pixels
|
int
|
Upper bound on training pixels gathered by |
20000
|
fit_seed
|
int
|
Seed for the subsample permutation, for reproducible fits (default: 0). |
0
|
Source code in cuvis_ai/node/_statistical_fit.py
is_initialized
property
¶
Whether statistical_initialization has successfully fitted state.
statistical_initialization
¶
Collect training pixels, reject empties, fit, and mark initialized.
Subclasses that fit from a raw [N, C] matrix implement _fit;
streaming-moment subclasses override this method instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterable of port-keyed batch dicts matching |
required |
Source code in cuvis_ai/node/_statistical_fit.py

OrthogonalityLosscuvis_ai.node.lossesregularizerOrthogonality regularization loss for TrainablePCA.
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

SelectorDiversityRegularizercuvis_ai.node.lossesregularizerDiversity regularization for SoftChannelSelector.
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

SelectorEntropyRegularizercuvis_ai.node.lossesregularizerEntropy regularization for SoftChannelSelector.
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

ClassMapAccumulatorcuvis_ai.node.patch_inferencesinkScatter chunked patch predictions back into per-frame ``[H, W]`` class maps (sink).
ClassMapAccumulator
¶
Bases: Node
Scatter chunked patch predictions back into per-frame [H, W] class maps (sink).
Consumes the provenance contract emitted by a patch-tiler data module (not by
:class:PatchSampler): a tiler streams a frame's pixels through a classifier in batches, each
patch tagged with its provenance (frame_id, y, x) plus the source frame height/width.
This sink argmaxes the per-batch logits and writes each prediction into the right pixel of a
per-frame map. After the run the finished maps are read from :attr:class_maps.
The run lifecycle is reset() (clear maps at the start) -> forward() per batch ->
close() (no external resource; maps stay available via :attr:class_maps). One [H, W]
map is retained per distinct frame_id until the next :meth:reset, so memory grows with the
number of frames in a run; call reset() between runs. Per-frame eviction on long streams is
out of scope.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
background_value
|
int
|
Fill value for pixels no patch wrote to (default |
-1
|
Store the background fill and start with an empty map set.
Source code in cuvis_ai/node/patch_inference.py
class_maps
property
¶
Finished per-frame class maps {frame_id: [H, W] int64} (background = background_value).
reset
¶
forward
¶
Argmax the batch's logits and scatter each prediction into its frame's class map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Per-patch class logits |
required |
frame_id
|
Tensor
|
Per-patch provenance |
required |
y
|
Tensor
|
Per-patch provenance |
required |
x
|
Tensor
|
Per-patch provenance |
required |
height
|
Tensor
|
Per-patch provenance |
required |
width
|
Tensor
|
Per-patch provenance |
required |
**_
|
Any
|
Additional unused keyword arguments (e.g. the pipeline |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Empty dict (sink node); results accumulate in :attr: |
Raises:
| Type | Description |
|---|---|
IndexError
|
If a patch's |
Source code in cuvis_ai/node/patch_inference.py

ClassMapAccumulatorcuvis_ai_inspecscrap.node.class_map_accumulatorsink

CocoTrackBBoxWritercuvis_ai.node.json_filesinkWrite tracked bbox outputs into COCO tracking JSON.
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

CocoTrackMaskWritercuvis_ai.node.json_filesinkWrite mask tracking outputs as COCO JSON in one of two dialects.
CocoTrackMaskWriter
¶
CocoTrackMaskWriter(
output_json_path,
dialect="image",
default_category_name="object",
write_empty_frames=True,
atomic_write=True,
flush_interval=0,
**kwargs,
)
Bases: _BaseCocoTrackWriter
Write mask tracking outputs as COCO JSON in one of two dialects.
The default dialect="image" emits standard image-keyed COCO: per-frame images
records plus one annotation per (track, frame) carrying an RLE segmentation,
bbox/area, and additive track_id/score keys — readable by pycocotools
and every image-keyed COCO consumer. dialect="video" emits the legacy
YouTube-VIS-shaped track dialect (top-level videos, one annotation per track with
per-frame parallel arrays) for external video-COCO tooling.
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
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 | |

DetectionCocoJsonNodecuvis_ai.node.json_filesinkWrite frame-wise detections into COCO detection JSON.
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

MontageColumnSinkcuvis_ai_inspecscrap.node.montage_sinksink

NumpyFeatureWriterNodecuvis_ai.node.numpy_filesinkSave per-frame feature tensors to ``.npy`` files.
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_file.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_file.py

PngWritercuvis_ai.node.image_filesinkWrite RGB frames to PNG files on disk.
PngWriter
¶
Bases: Node
Write RGB frames to PNG files on disk.
A sink node (no output ports): it consumes an rgb_image and writes one
PNG per frame via :func:torchvision.io.write_png, so the final composite
image drops straight out of the pipeline. Input is the canonical
[B, H, W, 3] float32 in [0, 1]; it is scaled to uint8 and
written channels-first.
Naming. A single frame with no frame_id is written to output_path
verbatim. With a frame_id (per-frame streaming) the index is appended as
{stem}_{frame_id:06d}{suffix}; a multi-frame batch is written as
{stem}_{i:06d}{suffix} per frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
str
|
Destination PNG path. Its parent directory is created on construction. |
required |
compression_level
|
int
|
zlib compression level 0-9 forwarded to |
6
|
Source code in cuvis_ai/node/image_file.py
forward
¶
Write each RGB frame to a PNG file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rgb_image
|
Tensor
|
|
required |
frame_id
|
Tensor or None
|
|
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Empty dict (sink node). |
Source code in cuvis_ai/node/image_file.py

TensorBoardMonitorNodecuvis_ai.node.monitorsinkTensorBoard monitoring node for logging artifacts and metrics.
TensorBoardMonitorNode
¶
Bases: Node
TensorBoard monitoring node for logging artifacts and metrics.
This is a SINK node that logs visualizations (artifacts) and metrics to TensorBoard. Accepts optional inputs for artifacts and metrics, allowing predecessors to be filtered by execution_stage without causing errors.
Executes during all stages (ALWAYS).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
str
|
Directory for TensorBoard logs (default: "./runs") |
'./runs'
|
comment
|
str
|
Comment to append to log directory name (default: "") |
''
|
flush_secs
|
int
|
How often to flush pending events to disk (default: 120) |
120
|
Examples:
>>> heatmap_viz = AnomalyHeatmap(cmap='hot', up_to=10)
>>> tensorboard_node = TensorBoardMonitorNode(output_dir="./runs")
>>> graph.connect(
... (heatmap_viz.artifacts, tensorboard_node.artifacts),
... )
Source code in cuvis_ai/node/monitor.py
forward
¶
Log artifacts and metrics to TensorBoard.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
Context
|
Execution context with stage, epoch, batch_idx, global_step |
None
|
artifacts
|
list[Artifact]
|
List of artifacts to log (default: None) |
None
|
metrics
|
list[Metric]
|
List of metrics to log (default: None) |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Empty dict (sink node has no outputs) |
Source code in cuvis_ai/node/monitor.py
log
¶
Log a scalar value to TensorBoard.
This method provides a simple interface for external trainers to log metrics directly, complementing the port-based logging. Used by GradientTrainer to log train/val losses to the same TensorBoard directory as graph metrics and artifacts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name/tag for the scalar (e.g., "train/loss", "val/accuracy") |
required |
value
|
float
|
Scalar value to log |
required |
step
|
int
|
Global step number |
required |
Examples:
>>> tensorboard_node = TensorBoardMonitorNode(output_dir="./runs")
>>> # From external trainer
>>> tensorboard_node.log("train/loss", 0.5, step=100)
Source code in cuvis_ai/node/monitor.py

ToImagecuvis_ai.node.videosinkWrite incoming RGB frames to individual image files, one file per frame.
ToImage
¶
ToImage(
output_dir,
filename_pattern="frame_{frame_id:06d}.png",
frame_rotation=None,
overlay_title=None,
**kwargs,
)
Bases: _FrameRenderMixin, Node
Write incoming RGB frames to individual image files, one file per frame.
Mirrors :class:ToVideoNode but emits a standalone image per frame instead
of an encoded video stream. Each file is written immediately and is complete
on disk the moment forward returns, so there is no lazy encoder process
and no explicit close() / finalization step (and none of the fragmented
movflags playability caveats a streaming video has).
The output name comes from filename_pattern with the frame index
substituted (the {frame_id} field); the image format is inferred from the
pattern's file extension (for example .png or .jpg). When the batch
carries a frame_id port, that value drives both the filename and the text
overlay; otherwise a running per-node counter is used. A pattern without a
{frame_id} field writes every frame to the same file (last wins).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
str
|
Directory the image files are written to. Created if missing. |
required |
filename_pattern
|
str
|
|
'frame_{frame_id:06d}.png'
|
frame_rotation
|
int | None
|
Optional frame rotation in degrees; same semantics and accepted values as
:class: |
None
|
overlay_title
|
str | None
|
Optional static title rendered at the top center with its own darkened
background block. Default is |
None
|
Source code in cuvis_ai/node/video.py
forward
¶
Write each incoming RGB frame to its own image file.
Returns:
| Type | Description |
|---|---|
dict
|
Empty dict (sink node). |
Source code in cuvis_ai/node/video.py

ToVideoNodecuvis_ai.node.videosinkWrite incoming RGB frames directly to a video file via ffmpeg.
ToVideoNode
¶
ToVideoNode(
output_video_path,
frame_rate=10.0,
frame_rotation=None,
video_codec="libx264",
bitrate="12M",
overlay_title=None,
write_mode="full",
**kwargs,
)
Bases: _FrameRenderMixin, Node
Write incoming RGB frames directly to a video file via ffmpeg.
This node lazily starts a single ffmpeg subprocess on the first frame and
pipes raw rgb24 bytes to its stdin; ffmpeg handles encoding, bitrate
control, and muxing. close() sends EOF and waits for ffmpeg to flush the
trailer — callers must invoke it explicitly (e.g. in a finally block of
the enclosing pipeline driver) to surface encoder errors.
The ffmpeg binary is resolved via imageio_ffmpeg by default (bundled with
the wheel — no system install needed). Override with the
CUVIS_AI_FFMPEG_BIN environment variable to point at a custom build
(e.g. one with h264_nvenc / vaapi / amf hardware encoders).
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
|
video_codec
|
str
|
ffmpeg |
'libx264'
|
bitrate
|
str
|
ffmpeg |
'12M'
|
overlay_title
|
str | None
|
Optional static title rendered at the top center with its own slim
darkened background block. Default is |
None
|
write_mode
|
str
|
How the mp4 is finalized. |
'full'
|
Source code in cuvis_ai/node/video.py
forward
¶
Append incoming RGB frames to the configured video file.
Returns:
| Type | Description |
|---|---|
dict
|
Empty dict (sink node). |
Source code in cuvis_ai/node/video.py
close
¶
Flush EOF to ffmpeg, wait for mux, and surface any encoder errors.
Idempotent — repeated calls are no-ops. Must be called explicitly by the
pipeline driver; do not rely on __del__ for normal teardown.
Source code in cuvis_ai/node/video.py
cleanup
¶
Finalize the video file when the hosting pipeline is torn down.
A gRPC/session pipeline has no explicit driver close() call, so the
session-teardown cleanup() (invoked by CuvisPipeline.cleanup on
session close, pipeline replacement, or run stop) is where the ffmpeg
trailer gets flushed. close() is idempotent, so calling it here in
addition to an explicit driver close() is safe.
CuvisPipeline.cleanup wraps each node's cleanup() in a bare
try/except that only logger.warnings, so a finalize failure here
(ffmpeg unable to write the moov trailer, leaving an unplayable file)
would otherwise be indistinguishable from a benign teardown warning while
the run still reports success. Surface it explicitly at ERROR level and
record it on _finalize_error so callers/tests can detect the truncated
output, then re-raise so nothing is silently hidden.
Source code in cuvis_ai/node/video.py

_BaseCocoTrackWritercuvis_ai.node.json_filesinkShared tensor parsing helpers for tracking writers.
_BaseCocoTrackWriter
¶
Bases: _BaseJsonWriterNode
Shared tensor parsing helpers for tracking writers.
Source code in cuvis_ai/node/json_file.py

_BaseJsonWriterNodecuvis_ai.node.json_filesinkShared JSON write lifecycle for sink nodes.
_BaseJsonWriterNode
¶
Bases: Node
Shared JSON write lifecycle for sink nodes.
Source code in cuvis_ai/node/json_file.py

AnomalyDataNodecuvis_ai.node.datasourceCU3S data node with binary anomaly label mapping.
AnomalyDataNode
¶
Bases: CU3SDataNode
CU3S data node with binary anomaly label mapping.
Inherits shared CU3S normalization (cube + wavelengths) and additionally maps
multi-class masks to binary anomaly masks: classes in normal_class_ids become 0,
everything else (or anomaly_class_ids when given) becomes 1.
Source code in cuvis_ai/node/data.py
forward
¶
Apply CU3S normalization and optional binary anomaly mask mapping.
Source code in cuvis_ai/node/data.py

BBoxPromptcuvis_ai.node.promptssourceEmit scheduled runtime bbox prompts plus overlay-friendly debug tensors.
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

CU3SDataNodecuvis_ai.node.datasourceGeneral-purpose data node for CU3S hyperspectral sequences.
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

Cu3sDataModulecuvis_ai_dataloader.data.datamodule_cu3ssourceSingle cu3s recording with optional COCO annotations.
Single cu3s recording with optional COCO annotations.
Data module cu3s — pip extras: cu3s, coco.

DetectionJsonReadercuvis_ai.node.json_filesourceRead COCO detection JSON and emit tensors per frame.
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

LentilsAnomalyDataNodecuvis_ai.node.datasourceDeprecated alias of :class:`AnomalyDataNode` (nothing lentils-specific inside).
LentilsAnomalyDataNode
¶
Bases: AnomalyDataNode
Deprecated alias of :class:AnomalyDataNode (nothing lentils-specific inside).
Kept so saved pipelines referencing the old class name keep loading.
Source code in cuvis_ai/node/data.py

MaskPromptcuvis_ai.node.promptssourceEmit a scheduled label-map prompt mask for the requested frame.
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

MultiCu3sDataModulecuvis_ai_dataloader.data.datamodule_cu3s_multisourceMultiple cu3s recordings over a universe.csv (source, index; optional split).
Multiple cu3s recordings over a universe.csv (source, index; optional split).
Data module cu3s_multi — pip extras: cu3s, coco.

MultiNpzDataModulecuvis_ai_dataloader.data.datamodule_npz_multisourcePer-frame .npz over a universe.csv (source, index, materialized_path), split by a splits.json.
Per-frame .npz over a universe.csv (source, index, materialized_path), split by a splits.json.
Data module npz_multi — pip extras: none.

NpyReadercuvis_ai.node.numpy_filesourceLoad a `.npy` file once and return the same tensor every forward call.
NpyReader
¶
Bases: Node
Load a .npy file once and return the same tensor every forward call.
Source code in cuvis_ai/node/numpy_file.py
forward
¶

PointPromptcuvis_ai.node.promptssourceEmit a scheduled list of point prompts for the requested frame.
PointPrompt
¶
Bases: Node
Emit a scheduled list of point prompts for the requested frame.
Unlike :class:MaskPrompt / :class:BBoxPrompt (which read prompts from a COCO
detection JSON), point prompts are supplied directly as (x, y, type) because
object selection is interactive, not stored in a detection file. Each point is a
pixel coordinate with a type of positive (object), negative
(background), or neutral (ignored). All points fire on prompt_frame_id
and address a single object; every other frame emits an empty list.
Configure the point prompts and the frame they fire on.
Args:
points: Iterable of (x, y[, type]) tuples or {x, y, type, element_id}
dicts in pixel coordinates. type defaults to positive.
prompt_frame_id: Source frame index on which to emit the points.
Source code in cuvis_ai/node/prompts.py
forward
¶
Emit the configured point prompts on prompt_frame_id, else an empty list.
Source code in cuvis_ai/node/prompts.py

TextPromptcuvis_ai.node.promptssourceEmit a runtime text prompt for the requested frame.
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

TiffDataNodecuvis_ai_inspecscrap.node.datasource

TiffPairedDataModulecuvis_ai_dataloader.data.datamodule_tiff_pairedsourceTIFF cubes with paired PNG label images.
TIFF cubes with paired PNG label images.
Data module tiff_paired — pip extras: tiff.

TrackingResultsReadercuvis_ai.node.json_filesourceRead tracking results JSON (bbox or mask format) and emit per-frame tensors.
TrackingResultsReader
¶
Bases: Node
Read tracking results JSON (bbox or mask format) and emit per-frame tensors.
Supports two JSON formats:
-
COCO image dialect (
coco_bbox) —images+annotationswithbboxand/or RLE-dictsegmentationfields plus additivetrack_id. Emitsbboxes,category_ids,confidences,track_ids; when any annotation carries asegmentation, also emits themasklabel map (pixel value =track_id, annotation id when track_id is missing/negative; overlaps painted in ascending annotation-id order) andobject_ids. -
Video COCO (
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

VideoFrameNodecuvis_ai.node.videosourcePassthrough source node that receives RGB frames from the batch.
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

AugmentationComposecuvis_ai_augment.node.composetransformApplies a sequence of stochastic augmentation transforms to a cube and paired mask during training only.
Applies a sequence of stochastic augmentation transforms to a cube and paired mask during training only.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
cube |
float32 |
[-1, -1, -1, -1] |
Hyperspectral cube [B, H, W, C] in float32 |
mask optional |
int32 |
[-1, -1, -1] |
Per-pixel mask [B, H, W] (int32 or bool) |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
cube |
float32 |
[-1, -1, -1, -1] |
Augmented cube [B, H, W, C] |
mask optional |
int32 |
[-1, -1, -1] |
Augmented mask [B, H, W] |

BBoxRoiCropNodecuvis_ai.node.preprocessorstransformDifferentiable bbox cropping via torchvision roi_align.
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

BBoxSpectralExtractorcuvis_ai.node.spectral_extractortransformExtract per-bbox spectral signatures with trimmed median/mean and std.
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.
Notes
Only the first batch element (cube[0], bboxes[0]) is processed.
Outputs are always shaped [1, N, …]. Feed one frame at a time
(B == 1).
Source code in cuvis_ai/node/spectral_extractor.py
forward
¶
Extract per-bbox spectral signatures. See class docstring for batch semantics.
Source code in cuvis_ai/node/spectral_extractor.py

BandpassByWavelengthcuvis_ai.node.preprocessorstransformSelect channels by wavelength interval from BHWC tensors.
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

BinaryAnomalyLabelMappercuvis_ai.node.labelstransformConvert multi-class segmentation masks to binary anomaly targets.
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 |
Source code in cuvis_ai/node/labels.py

BinaryDecidercuvis_ai.node.deciders.binary_decidertransformSimple decider node using a static threshold to classify data.
BinaryDecider
¶
Bases: BinaryDecider
Simple decider node using a static threshold to classify data.
Accepts logits as input, applies sigmoid transformation to convert to probabilities [0, 1], then applies threshold to produce binary decisions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threshold
|
float
|
The threshold to use for classification after sigmoid. Values >= threshold are classified as anomalies (True). Default: 0.5 |
0.5
|
Examples:
>>> from cuvis_ai.node.deciders.binary_decider import BinaryDecider
>>> import torch
>>>
>>> # Create decider with default threshold
>>> decider = BinaryDecider(threshold=0.5)
>>>
>>> # Apply to RX anomaly logits
>>> logits = torch.randn(4, 256, 256, 1) # [B, H, W, C]
>>> output = decider.forward(logits=logits)
>>> decisions = output["decisions"] # [4, 256, 256, 1] boolean mask
>>>
>>> # Use in pipeline
>>> pipeline.connect(
... (logit_head.logits, decider.logits),
... (decider.decisions, visualizer.mask),
... )
See Also
QuantileBinaryDecider : Adaptive per-batch thresholding ScoreToLogit : Convert scores to logits before decisioning
Source code in cuvis_ai/node/deciders/binary_decider.py
forward
¶
Apply sigmoid and threshold-based decisioning on channels-last data.
Args: logits: Tensor shaped (B, H, W, C) containing logits.
Returns: Dictionary with "decisions" key containing (B, H, W, 1) decision mask.
Source code in cuvis_ai/node/deciders/binary_decider.py

BlobDetectorcuvis_ai.node.blob_detectortransformLocalize bright blobs (e.g. pills, granules, tray compartments) in a cube.
BlobDetector
¶
BlobDetector(
brightness="band_mean",
threshold_method="otsu",
threshold=0.5,
index_wavelengths=None,
opening_kernel=3,
closing_kernel=3,
min_area=5,
max_area=None,
keep_largest=None,
connectivity=8,
**kwargs,
)
Bases: Node
Localize bright blobs (e.g. pills, granules, tray compartments) in a cube.
The cube's first frame is reduced to a 2-D brightness image, thresholded
into a foreground mask, morphologically cleaned, and labeled into connected
components. Components are filtered by area and, optionally, capped to the
keep_largest biggest so a fixed-layout scene yields a stable blob count.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
brightness
|
str
|
How to reduce the cube |
'band_mean'
|
threshold_method
|
str
|
|
'otsu'
|
threshold
|
float
|
Quantile in |
0.5
|
index_wavelengths
|
tuple[float, float] or None
|
Two wavelengths (nm) for |
None
|
opening_kernel
|
int
|
Square structuring-element side for morphological opening (speckle
removal); |
3
|
closing_kernel
|
int
|
Square side for morphological closing (hole fill); |
3
|
min_area
|
int
|
Drop connected components with fewer than this many pixels. Default |
5
|
max_area
|
int or None
|
Drop components larger than this many pixels ( |
None
|
keep_largest
|
int or None
|
After area filtering, keep only the |
None
|
connectivity
|
int
|
|
8
|
Validate and store the detection hyperparameters.
Source code in cuvis_ai/node/blob_detector.py
forward
¶
Detect blobs in the first frame of cube.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube |
required |
wavelengths
|
ndarray or Tensor or None
|
Wavelengths |
None
|
**_
|
Any
|
Additional unused keyword arguments (e.g. the pipeline |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/blob_detector.py

BlobMajorityVotecuvis_ai_inspecscrap.node.deciderstransform

CIETristimulusRGBSelectorcuvis_ai.node.channel_selectortransformCIE 1931 tristimulus-based RGB rendering.
CIETristimulusRGBSelector
¶
Bases: ChannelSelectorBase
CIE 1931 tristimulus-based 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 a faithful (true) RGB rendering 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

CIRSelectorcuvis_ai.node.channel_selectortransformColor Infrared (CIR) false color composition.
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

CIRedEdgeSelectorcuvis_ai.node.channel_selectortransformChlorophyll Index Red Edge renderer.
CIRedEdgeSelector
¶
CIRedEdgeSelector(
red_edge_nm=720.0,
nir_nm=800.0,
colormap_min=-1.0,
colormap_max=1.0,
eps=1e-06,
**kwargs,
)
Bases: _VegetationIndexBase
Chlorophyll Index Red Edge renderer.
Computes NIR / RedEdge - 1 over bands resolved by nearest sensor
wavelength. The raw index map is returned via index_image and
rgb_image carries an HSV colour-mapped render.
Source code in cuvis_ai/node/channel_selector.py

CameraEmulationFalseRGBSelectorcuvis_ai.node.channel_selectortransformCamera-emulation false RGB using smooth Gaussian sensitivity curves.
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

ChannelNormalizeNodecuvis_ai.node.preprocessorstransformPer-channel mean/std normalization for NCHW tensors.
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

ChannelSelectorBasecuvis_ai.node.channel_selectortransformBase class for hyperspectral band selection strategies.
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). Subclasses that emit
a different channel count (e.g. :class:FixedWavelengthSelector
with n != 3) must override OUTPUT_SPECS to widen the channel
dimension; the base class keeps the tight 3-channel contract so
pipeline validation catches accidental mis-wiring of the standard
RGB selectors (FastRGBSelector, RangeAverageFalseRGBSelector,
CIRSelector, CIETristimulusRGBSelector, NDVI variants, …).
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

ClassMapRobustifiercuvis_ai.node.mask_opstransformPer-class morphological cleanup of an integer label map.
ClassMapRobustifier
¶
ClassMapRobustifier(
opening_kernel=0,
closing_kernel=3,
min_area=10,
keep_largest=True,
background_value=-1,
**kwargs,
)
Bases: Node
Per-class morphological cleanup of an integer label map.
Runs :class:MaskRobustifier independently on the binary mask of each class
present in class_map (despeckle + close + min-area / largest-component
filter), then repaints the survivors into one label map. Classes are painted
in ascending surviving-area order, so a larger class wins any pixel an
overlapping smaller class also kept. Pixels removed as speckle become
background_value (holes); :class:NearestLabelFill is the companion node
that fills them. The input map is echoed verbatim on the source port so the
fill node has both the foreground extent and the fallback labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
opening_kernel
|
int
|
Morphological opening kernel for the internal |
0
|
closing_kernel
|
int
|
Morphological closing kernel. |
3
|
min_area
|
int
|
Drop per-class connected components smaller than this. |
10
|
keep_largest
|
bool
|
Keep only the largest surviving component of each class. Default |
True
|
background_value
|
int
|
Label value for unassigned pixels in the output. Default |
-1
|
Source code in cuvis_ai/node/mask_ops.py
forward
¶
Clean each present class with morphology, then repaint area-sorted into one map.
Source code in cuvis_ai/node/mask_ops.py

ContinuumRemovalcuvis_ai.node.pretreatments.continuum_removaltransformPer-pixel continuum (upper convex hull) removal across the spectral axis.
ContinuumRemoval
¶
Bases: Node
Per-pixel continuum (upper convex hull) removal across the spectral axis.
For every spectrum the upper convex hull over (wavelength, reflectance)
is computed, linearly interpolated to all bands, and the spectrum is
divided by it. Continuum-free regions map to ~1.0 while absorption
bands dip below 1.0, making feature depths comparable across spectra.
The hull is built with a batched Andrew monotone-chain scan that runs
entirely in torch (vectorized over pixels), so the node stays
device-agnostic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eps
|
float
|
Lower clamp on the hull before division, guarding against division by zero (default: 1e-8). |
1e-08
|
Source code in cuvis_ai/node/pretreatments/continuum_removal.py
forward
¶
Divide each spectrum by its upper convex hull.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Input cube in BHWC format. |
required |
wavelengths
|
array - like
|
Band wavelengths, length |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/pretreatments/continuum_removal.py

Cropcuvis_ai_augment.node.croptransformDeterministic fixed-rectangle spatial crop of a cube and optional paired mask, applied identically at every execution stage.
Deterministic fixed-rectangle spatial crop of a cube and optional paired mask, applied identically at every execution stage.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
data |
float32 |
[-1, -1, -1, -1] |
Cube [B, H, W, C] in float32 |
mask optional |
int32 |
[-1, -1, -1] |
Optional per-pixel mask [B, H, W] (cropped identically) |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
cropped |
float32 |
[-1, -1, -1, -1] |
Cropped cube [B, H', W', C] |
mask_cropped optional |
int32 |
[-1, -1, -1] |
Cropped mask [B, H', W'] (only when a mask is connected) |

DecisionToMaskcuvis_ai.node.conversiontransformCombine binary decisions and identity labels into a single int32 mask.
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

DeepEIoUTrackcuvis_ai_deepeiou.nodetransformDeepEIoU multi-object tracker node.
DeepEIoU multi-object tracker node.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
bboxes |
float32 |
[1, -1, 4] |
Detection bounding boxes [1, N, 4] xyxy pixel coordinates. |
category_ids |
int64 |
[1, -1] |
Detection category IDs [1, N]. |
confidences |
float32 |
[1, -1] |
Detection confidence scores [1, N]. |
embeddings optional |
float32 |
[1, -1, -1] |
Per-detection ReID embeddings [1, N, D]. Optional; if absent, tracker uses EIoU-only mode. |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
bboxes |
float32 |
[1, -1, 4] |
Input bboxes pass-through [1, N, 4] xyxy pixel coordinates. |
track_ids |
int64 |
[1, -1] |
Track IDs aligned with input detections [1, N]. -1 for detections not assigned to any track. |
confidences |
float32 |
[1, -1] |
Input confidences pass-through [1, N]. |
category_ids |
int64 |
[1, -1] |
Input category_ids pass-through [1, N]. |

DeepSVDDCenterTrackercuvis_ai.node.anomaly.deep_svddtransformTrack and expose Deep SVDD center statistics with optional logging.
DeepSVDDCenterTracker
¶
Bases: Node
Track and expose Deep SVDD center statistics with optional logging.
Source code in cuvis_ai/node/anomaly/deep_svdd.py
requires_initial_fit
property
¶
Whether this node requires statistical initialization from training data.
Returns:
| Type | Description |
|---|---|
bool
|
Always True for center tracking initialization. |
statistical_initialization
¶
Initialize the Deep SVDD center from training embeddings.
Computes the mean embedding across all training samples to initialize the hypersphere center.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Training data stream with embeddings [B, H, W, D]. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no embeddings are received from the input stream. |
ValueError
|
If embedding dimensions don't match initialized rep_dim. |
Source code in cuvis_ai/node/anomaly/deep_svdd.py
forward
¶
Track and output the Deep SVDD center with exponential moving average.
Updates the center using EMA during training (and optionally during eval), then outputs the current center and center norm metric.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embeddings
|
Tensor
|
Deep SVDD embeddings [B, H, W, D]. |
required |
context
|
Context
|
Execution context determining whether to update center. |
None
|
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with:
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If statistical_initialization() has not been called. |
ValueError
|
If embedding dimensions don't match initialized rep_dim. |
Source code in cuvis_ai/node/anomaly/deep_svdd.py

DisplayNormalizercuvis_ai.node.normalizationtransformApply sRGB gamma companding (IEC 61966-2-1) to a ``[0, 1]`` BHWC tensor.
DisplayNormalizer
¶
Bases: _ScoreNormalizerBase
Apply sRGB gamma companding (IEC 61966-2-1) to a [0, 1] BHWC tensor.
The stateless display-encoding companion to :class:PercentileNormalizer:
chain it after the normalizer on the false-RGB display path
(selector -> PercentileNormalizer -> DisplayNormalizer) to lift midtones
so images look natural on standard displays. ML / n-channel paths skip it.
Ports
INPUT_SPECS
data : float32, shape (-1, -1, -1, -1), BHWC tensor, values in [0, 1].
OUTPUT_SPECS
normalized : float32, shape (-1, -1, -1, -1), sRGB gamma-encoded, [0, 1].
Source code in cuvis_ai/node/normalization.py

EVI2Selectorcuvis_ai.node.channel_selectortransformTwo-band Enhanced Vegetation Index renderer.
EVI2Selector
¶
EVI2Selector(
red_nm=660.0,
nir_nm=800.0,
colormap_min=-1.0,
colormap_max=1.0,
eps=1e-06,
**kwargs,
)
Bases: _VegetationIndexBase
Two-band Enhanced Vegetation Index renderer.
Computes 2.5 * (NIR - Red) / (NIR + 2.4 * Red + 1) over bands resolved by
nearest sensor wavelength. The raw index map is returned via index_image
and rgb_image carries an HSV colour-mapped render.
The additive +1 constant is only meaningful for reflectance in [0, 1];
feed reflectance-calibrated cubes, not raw radiance/DN.
Source code in cuvis_ai/node/channel_selector.py

EVISelectorcuvis_ai.node.channel_selectortransformEnhanced Vegetation Index renderer.
EVISelector
¶
EVISelector(
blue_nm=460.0,
red_nm=660.0,
nir_nm=800.0,
colormap_min=-1.0,
colormap_max=1.0,
eps=1e-06,
**kwargs,
)
Bases: _VegetationIndexBase
Enhanced Vegetation Index renderer.
Computes 2.5 * (NIR - Red) / (NIR + 6 * Red - 7.5 * Blue + 1) over bands
resolved by nearest sensor wavelength. The raw index map is returned via
index_image and rgb_image carries an HSV colour-mapped render.
The additive +1 constant is only meaningful for reflectance in [0, 1];
feed reflectance-calibrated cubes, not raw radiance/DN.
Source code in cuvis_ai/node/channel_selector.py

FastRGBSelectorcuvis_ai.node.channel_selectortransformcuvis-next parity FastRGB renderer.
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

FixedWavelengthSelectorcuvis_ai.node.channel_selectortransformFixed wavelength band selection — picks the nearest band for each target wavelength.
FixedWavelengthSelector
¶
FixedWavelengthSelector(
target_wavelengths=(650.0, 550.0, 450.0),
normalize_output=True,
**kwargs,
)
Bases: ChannelSelectorBase
Fixed wavelength band selection — picks the nearest band for each target wavelength.
For the standard 3-channel case (default) this produces a "true color-ish" RGB image.
For n > 3 target wavelengths the node stacks n bands into a
[B, H, W, n] output — useful for multi-channel hyperspectral models (e.g.
a 6-channel VIS+SWIR input to a Dinomaly detector).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_wavelengths
|
tuple[float, ...]
|
Target wavelengths in nanometers, in the order they should be stacked. Must contain at least one wavelength. Default: (650.0, 550.0, 450.0) — standard false-RGB. |
(650.0, 550.0, 450.0)
|
normalize_output
|
bool
|
If |
True
|
Ports
OUTPUT_SPECS
rgb_image : float32, shape (-1, -1, -1, -1)
Stacked selected bands [B, H, W, len(target_wavelengths)].
Port name kept as rgb_image for graph compatibility with
downstream consumers. For the 3-channel default the output is the
normalised RGB image; for n != 3 it is the raw stacked bands.
band_info : dict
See forward for keys.
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

GNDVISelectorcuvis_ai.node.channel_selectortransformGreen Normalized Difference Vegetation Index renderer.
GNDVISelector
¶
GNDVISelector(
nir_nm=800.0,
green_nm=550.0,
colormap_min=-1.0,
colormap_max=1.0,
eps=1e-06,
**kwargs,
)
Bases: _ColormappedNormalizedDifferenceSelector
Green Normalized Difference Vegetation Index renderer.
Computes (CUBE(nir_nm) - CUBE(green_nm)) / (CUBE(nir_nm) + CUBE(green_nm)).
Bands are resolved by nearest available sensor wavelength. The raw index map
is returned via index_image and rgb_image carries an HSV colour-mapped
render.
Source code in cuvis_ai/node/channel_selector.py

HighContrastSelectorcuvis_ai.node.channel_selectortransformData-driven band selection using spatial variance + Laplacian energy.
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

IdentityNormalizercuvis_ai.node.normalizationtransformNo-op normalizer; preserves incoming scores.
IdentityNormalizer
¶
Bases: _ScoreNormalizerBase
No-op normalizer; preserves incoming scores.
Source code in cuvis_ai/node/normalization.py

ImageConcatenatorcuvis_ai.node.compositingtransformConcatenate several RGB frames into one side-by-side or stacked strip.
ImageConcatenator
¶
Bases: Node
Concatenate several RGB frames into one side-by-side or stacked strip.
A fan-in node: connect any number of rgb_image sources to the single
images port and they are concatenated in connection order (the
order the edges were added with pipeline.connect). Frames may differ on
the cross axis (height for a horizontal strip, width for a vertical one);
each is padded to the common size with bg_color and aligned per
align. An optional gap inserts a bg_color separator between
frames. The whole batch is concatenated together, so every source must
share the same batch size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axis
|
str
|
|
'horizontal'
|
gap
|
int
|
Width (horizontal) or height (vertical) in pixels of a |
0
|
bg_color
|
tuple[float, float, float]
|
RGB in [0, 1] used for padding and gaps. Default white |
(1.0, 1.0, 1.0)
|
align
|
str
|
Cross-axis placement of a smaller frame: |
'center'
|
Source code in cuvis_ai/node/compositing.py

InsetComposercuvis_ai.node.compositingtransformPaste a fixed-size inset frame into a corner of a larger base frame.
InsetComposer
¶
InsetComposer(
corner="top-right",
margin_px=16,
border_px=2,
border_color=(1.0, 1.0, 1.0),
**kwargs,
)
Bases: Node
Paste a fixed-size inset frame into a corner of a larger base frame.
Picture-in-picture compositor. The inset is expected to already be at its
final pixel size (e.g. produced by :class:ROIZoomNode); this node only
places it onto the base, optionally with a coloured border. When
valid == 0 for a frame the base passes through untouched, so the
inset never lies about a stale ROI.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corner
|
str
|
One of |
'top-right'
|
margin_px
|
int
|
Distance in pixels between the inset and the closest base edges.
Default |
16
|
border_px
|
int
|
Border thickness in pixels. |
2
|
border_color
|
tuple[float, float, float]
|
Border RGB in [0, 1]. Default white |
(1.0, 1.0, 1.0)
|
Source code in cuvis_ai/node/compositing.py

IntensityThresholdSegmentercuvis_ai.node.segmentation.intensitytransformSegment foreground by thresholding a per-pixel reduced intensity.
IntensityThresholdSegmenter
¶
Bases: Node
Segment foreground by thresholding a per-pixel reduced intensity.
The cube is collapsed over its channel axis to a single per-pixel intensity
using the chosen reduction, then pixels whose intensity lies inside the
closed interval [low, high] are marked as foreground (1); all other
pixels are background (0).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low
|
float
|
Inclusive lower bound of the foreground intensity interval. Default: 0.0. |
0.0
|
high
|
float
|
Inclusive upper bound of the foreground intensity interval. Default: 1.0. |
1.0
|
reduction
|
str
|
How to collapse the channel axis to a scalar intensity. One of
|
'mean'
|
band_index
|
int
|
Channel index used when |
0
|
Examples:
>>> seg = IntensityThresholdSegmenter(low=0.2, high=0.8, reduction="mean")
>>> cube = torch.rand(2, 8, 8, 16)
>>> seg.forward(cube=cube)["mask"].shape
torch.Size([2, 8, 8])
Source code in cuvis_ai/node/segmentation/intensity.py
forward
¶
Reduce the cube over channels and threshold it into a foreground mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Input hyperspectral cube |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/segmentation/intensity.py

InverseFrequencyClassWeightscuvis_ai_inspecscrap.node.lossestransform

LabelOffsetcuvis_ai.node.mask_opstransformAdd a constant offset to every label in an integer label map.
LabelOffset
¶
Bases: Node
Add a constant offset to every label in an integer label map.
Mainly used to lift a 0-based dense label map (e.g. a KMeansClusterer /
GaussianMixtureClusterer class_mask, where cluster ids run 0..k-1)
to 1-based ids before :class:MajorityVoteByBlob, which treats 0 as
background in both its vote and its output. Without the shift a cluster-0
region would be dropped as background and collide with the unassigned label.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
offset
|
int
|
Value added to every label. Default |
1
|
Source code in cuvis_ai/node/mask_ops.py
forward
¶
Return the label map with offset added to every element.

LabelOverlaycuvis_ai.node.compositingtransformAlpha-blend a colourised label map onto an RGB image on its foreground pixels.
LabelOverlay
¶
Bases: Node
Alpha-blend a colourised label map onto an RGB image on its foreground pixels.
A pixel is "foreground" when its label_rgb differs from background_color;
background pixels keep the original RGB. Returns a single blended frame, so several
overlays can be montaged column-by-column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha
|
float
|
Blend factor for the label colour over the base image (default 0.55). |
0.55
|
background_color
|
tuple[float, float, float]
|
Label-map background colour in [0, 1]; pixels equal to it are left unblended. |
(0.0, 0.0, 0.0)
|
Source code in cuvis_ai/node/compositing.py
forward
¶
Blend label_rgb onto rgb_image where the label is non-background.
Source code in cuvis_ai/node/compositing.py

LegendStripcuvis_ai.node.compositingtransformAppend a horizontal class-colour legend strip below the input frame.
LegendStrip
¶
LegendStrip(
entries,
n_columns=6,
tile_height_px=22,
swatch_width_px=28,
text_padding_px=6,
background_color=(0.08, 0.08, 0.08),
text_color=(240, 240, 240),
dim_text_color=(110, 110, 110),
font_size=12,
**kwargs,
)
Bases: Node
Append a horizontal class-colour legend strip below the input frame.
Each (label, rgb) entry renders as a swatch plus its text label, wrapped over
n_columns. When the optional label_rgb mask is connected, the legend appends
a connected-component instance count (N) per class for the current frame and dims
rows whose count is zero. The legend is built from an explicit entries list of
(label, rgb) rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entries
|
list[tuple[str, tuple[int, int, int]]]
|
Ordered |
required |
n_columns
|
int
|
Number of legend columns before wrapping to a new row (default 6). |
6
|
tile_height_px
|
int
|
Legend layout dimensions in pixels. |
22
|
swatch_width_px
|
int
|
Legend layout dimensions in pixels. |
22
|
text_padding_px
|
int
|
Legend layout dimensions in pixels. |
22
|
font_size
|
int
|
Legend layout dimensions in pixels. |
22
|
background_color
|
tuple[float, float, float]
|
Strip background colour in [0, 1]. |
(0.08, 0.08, 0.08)
|
text_color
|
tuple[int, int, int]
|
Text colour for present / zero-count rows, in 0-255. |
(240, 240, 240)
|
dim_text_color
|
tuple[int, int, int]
|
Text colour for present / zero-count rows, in 0-255. |
(240, 240, 240)
|
Source code in cuvis_ai/node/compositing.py
forward
¶
Append the legend strip below frame; optionally count instances per class.
Source code in cuvis_ai/node/compositing.py

LegendStripNodecuvis_ai_inspecscrap.node.legendtransform

Logarithmcuvis_ai.node.pretreatments.logarithmtransformElement-wise logarithm of the cube.
Logarithm
¶
Bases: Node
Element-wise logarithm of the cube.
Computes log10(x) (default) or ln(x) after clamping the input to a
small positive floor so non-positive values do not produce -inf or
nan. With negate=True the sign is flipped, yielding true absorbance
-log10(R) from reflectance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
str
|
|
'log10'
|
negate
|
bool
|
Negate the result so reflectance maps to absorbance (default: False). |
False
|
eps
|
float
|
Lower clamp applied before the logarithm (default: 1e-8). |
1e-08
|
Source code in cuvis_ai/node/pretreatments/logarithm.py
forward
¶
Apply the configured logarithm to the cube.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Input cube in BHWC format. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/pretreatments/logarithm.py

MCARISelectorcuvis_ai.node.channel_selectortransformModified Chlorophyll Absorption in Reflectance Index renderer.
MCARISelector
¶
MCARISelector(
green_nm=550.0,
red_nm=670.0,
red_edge_nm=700.0,
colormap_min=-1.0,
colormap_max=1.0,
eps=1e-06,
**kwargs,
)
Bases: _VegetationIndexBase
Modified Chlorophyll Absorption in Reflectance Index renderer.
Computes ((RE - Red) - 0.2 * (RE - Green)) * (RE / Red) over bands
resolved by nearest sensor wavelength, where RE is the red-edge band. The
raw index map is returned via index_image and rgb_image carries an HSV
colour-mapped render.
Source code in cuvis_ai/node/channel_selector.py

MSAVISelectorcuvis_ai.node.channel_selectortransformModified Soil Adjusted Vegetation Index renderer.
MSAVISelector
¶
MSAVISelector(
red_nm=660.0,
nir_nm=800.0,
colormap_min=-1.0,
colormap_max=1.0,
eps=1e-06,
**kwargs,
)
Bases: _VegetationIndexBase
Modified Soil Adjusted Vegetation Index renderer.
Computes 0.5 * (2*NIR + 1 - sqrt((2*NIR + 1)^2 - 8*(NIR - Red))) over
bands resolved by nearest sensor wavelength. The raw index map is returned via
index_image and rgb_image carries an HSV colour-mapped render.
The additive +1 constants are only meaningful for reflectance in [0, 1];
feed reflectance-calibrated cubes, not raw radiance/DN.
Source code in cuvis_ai/node/channel_selector.py

MajorityVoteByBlobcuvis_ai.node.mask_opstransformAssign each blob the majority per-pixel label found inside it.
MajorityVoteByBlob
¶
Bases: Node
Assign each blob the majority per-pixel label found inside it.
Per-pixel classifiers (e.g. a Spectral Angle Mapper) produce noisy labels
when reference spectra are close together. Voting within each detected blob
denoises that into a single robust label per object: for every blob id in
blob_mask (1..N), the most frequent nonzero identity_mask value over
that blob's pixels becomes the blob's label; blobs with no labelled pixels
stay 0, as does the background.
forward
¶
Paint each blob with the majority label of its pixels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identity_mask
|
Tensor
|
Per-pixel labels |
required |
blob_mask
|
Tensor
|
Blob label map |
required |
**_
|
Any
|
Additional unused keyword arguments (e.g. the pipeline |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/mask_ops.py

MaskRobustifiercuvis_ai.node.mask_opstransformClean a binary/labelled mask with morphology + largest-component filter.
MaskRobustifier
¶
Bases: Node
Clean a binary/labelled mask with morphology + largest-component filter.
Applies morphological opening (remove speckle), then closing (fill small
holes), optionally drops connected components below min_area pixels,
and optionally keeps only the single largest component.
Output is an int32 mask with the same spatial shape as the input; non-zero values are preserved where the original mask was non-zero and survives the cleanup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
opening_kernel
|
int
|
Side length of the square structuring element used for |
0
|
closing_kernel
|
int
|
Side length for |
3
|
min_area
|
int
|
Drop connected components with fewer than this many pixels. |
10
|
keep_largest
|
bool
|
If True, keep only the single largest surviving component. Default
|
True
|
Source code in cuvis_ai/node/mask_ops.py

MaskToBBoxKalmancuvis_ai.node.mask_opstransformMask -> bounding box with constant-velocity Kalman smoothing.
MaskToBBoxKalman
¶
MaskToBBoxKalman(
padding_fraction=0.2,
min_size_px=96,
min_hits=3,
max_predict_frames=20,
process_noise=0.01,
measurement_noise=1.0,
**kwargs,
)
Bases: Node
Mask -> bounding box with constant-velocity Kalman smoothing.
Each frame the bbox tight to the non-zero extent of the mask (with padding) is used as a measurement to update an 8-state Kalman filter (cx, cy, w, h, vx, vy, vw, vh). When the mask is empty the filter is stepped in prediction-only mode, so the downstream ROI stays pinned to a plausible location for a few frames rather than vanishing.
A warm-up of min_hits consecutive measurement frames is required
before the track is confirmed; hits during the warm-up never leak to
downstream consumers (valid=0), and a single missed frame during
warm-up resets the hit counter. This suppresses isolated false-positive
detections that would otherwise briefly pop the inset into view.
Output valid encodes track state per frame:
1- measurement used this frame on a confirmed track.2- predicted only (mask empty on a confirmed track, within budget).0- unconfirmed warm-up, no track, or post-drop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
padding_fraction
|
float
|
Fractional padding applied to the measurement bbox before it is fed
to the filter. |
0.2
|
min_size_px
|
int
|
Lower bound on the output bbox edge length (post-Kalman). Small
measurements are expanded around the centre. Default |
96
|
min_hits
|
int
|
Number of consecutive measurement frames required to confirm a new
track. Missed frames during warm-up reset the hit counter back to
zero, so transient false positives never graduate. Default |
3
|
max_predict_frames
|
int
|
After this many consecutive empty frames (on a confirmed track) the
track is dropped and subsequent empty frames emit |
20
|
process_noise
|
float
|
Scalar multiplier for the Kalman process-noise covariance. |
0.01
|
measurement_noise
|
float
|
Scalar multiplier for the Kalman measurement-noise covariance. |
1.0
|
Source code in cuvis_ai/node/mask_ops.py

MaskedMeanSpectrumcuvis_ai.node.spectral_extractortransformPer-frame mean spectrum of a hyperspectral cube over a binary mask.
MaskedMeanSpectrum
¶
Bases: Node
Per-frame mean spectrum of a hyperspectral cube over a binary mask.
For each frame, averages cube values at pixels where mask > 0 and
emits the resulting [C] spectrum. When the mask is empty for a given
frame the output is a zero vector and valid is 0.

MeanCentercuvis_ai.node.pretreatments.scalingtransformSubtract a globally-fitted per-channel mean from the cube.
MeanCenter
¶
Bases: _StatisticalFitNode
Subtract a globally-fitted per-channel mean from the cube.
During statistical_initialization every training pixel is streamed
through a Welford accumulator to compute the exact per-channel mean over
the full dataset; forward then subtracts that mean from each spectrum.
Notes
The fitted mean_c is registered as a persistent buffer so a
checkpointed node reloads ready for inference.
Source code in cuvis_ai/node/pretreatments/scaling.py
statistical_initialization
¶
Fit the per-channel mean from the training stream via Welford.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterable of port-keyed batch dicts matching |
required |
Source code in cuvis_ai/node/pretreatments/scaling.py
forward
¶
Subtract the fitted per-channel mean from the cube.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Input cube in BHWC format. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/pretreatments/scaling.py

MinMaxNormalizercuvis_ai.node.normalizationtransformMin-max normalization per sample and channel (keeps gradients).
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
|
max_initialization_frames
|
int or None
|
Cap on the number of frames (batch elements) consumed by statistical_initialization(): the final batch is sliced to the cap and the input stream is not iterated further. None uses the entire training stream (default: None) |
None
|
**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/usecases/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.
Consumes at most max_initialization_frames frames when the cap is set: the
final batch is sliced to the cap and the stream is not iterated further.
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

MultiRangeSlicercuvis_ai.node.deciders.multi_range_decidertransformBucket a per-pixel score map into ordered class indices by edges.
MultiRangeSlicer
¶
Bases: Node
Bucket a per-pixel score map into ordered class indices by edges.
Each pixel score is assigned the index of the half-open range it falls into,
delegating to :func:torch.bucketize. With edges = [e0, e1, ..., e_{k-1}]
the output index is 0 for scores below the first edge and k for
scores at/above the last edge.
Convention
torch.bucketize(x, edges, right=False) is equivalent to
numpy.digitize(x, edges, right=True) (and right=True corresponds to
numpy.digitize(..., right=False)). The right flag selects whether a
value exactly equal to an edge falls into the lower or upper bucket: with
right=False (the default here) an edge value goes to the upper bucket,
matching numpy.digitize(..., right=True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
edges
|
list[float]
|
Monotonically increasing bucket boundaries. Default: |
None
|
right
|
bool
|
Passed through to :func: |
False
|
Examples:
>>> slicer = MultiRangeSlicer(edges=[0.25, 0.5, 0.75])
>>> scores = torch.tensor([[[[0.1], [0.3], [0.6], [0.9]]]])
>>> slicer.forward(scores=scores)["class_mask"]
tensor([[[0, 1, 2, 3]]], dtype=torch.int32)
Source code in cuvis_ai/node/deciders/multi_range_decider.py
forward
¶
Slice the score map into ordered bucket indices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
Tensor
|
Per-pixel score map |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/deciders/multi_range_decider.py

NBRSelectorcuvis_ai.node.channel_selectortransformNormalized Burn Ratio renderer.
NBRSelector
¶
NBRSelector(
nir_nm=850.0,
swir_nm=2200.0,
colormap_min=-1.0,
colormap_max=1.0,
eps=1e-06,
**kwargs,
)
Bases: _ColormappedNormalizedDifferenceSelector
Normalized Burn Ratio renderer.
Computes (CUBE(nir_nm) - CUBE(swir_nm)) / (CUBE(nir_nm) + CUBE(swir_nm)).
Bands are resolved by nearest available sensor wavelength. The raw index map
is returned via index_image and rgb_image carries an HSV colour-mapped
render.
Source code in cuvis_ai/node/channel_selector.py

NDRESelectorcuvis_ai.node.channel_selectortransformNormalized Difference Red Edge index renderer.
NDRESelector
¶
NDRESelector(
nir_nm=800.0,
red_edge_nm=720.0,
colormap_min=-1.0,
colormap_max=1.0,
eps=1e-06,
**kwargs,
)
Bases: _ColormappedNormalizedDifferenceSelector
Normalized Difference Red Edge index renderer.
Computes
(CUBE(nir_nm) - CUBE(red_edge_nm)) / (CUBE(nir_nm) + CUBE(red_edge_nm)).
Bands are resolved by nearest available sensor wavelength. The raw index map
is returned via index_image and rgb_image carries an HSV colour-mapped
render.
Source code in cuvis_ai/node/channel_selector.py

NDVISelectorcuvis_ai.node.channel_selectortransformNormalized Difference Vegetation Index renderer.
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

NDWISelectorcuvis_ai.node.channel_selectortransformNormalized Difference Water Index renderer.
NDWISelector
¶
NDWISelector(
green_nm=560.0,
nir_nm=860.0,
colormap_min=-1.0,
colormap_max=1.0,
eps=1e-06,
**kwargs,
)
Bases: _ColormappedNormalizedDifferenceSelector
Normalized Difference Water Index renderer.
Computes (CUBE(green_nm) - CUBE(nir_nm)) / (CUBE(green_nm) + CUBE(nir_nm)).
Bands are resolved by nearest available sensor wavelength. The raw index map
is returned via index_image and rgb_image carries an HSV colour-mapped
render.
Source code in cuvis_ai/node/channel_selector.py

NearestLabelFillcuvis_ai.node.mask_opstransformFill morphology-removed gaps in a label map with the nearest surviving label.
NearestLabelFill
¶
Bases: Node
Fill morphology-removed gaps in a label map with the nearest surviving label.
After per-class morphology (:class:ClassMapRobustifier) some pixels that were
labelled in the original map are dropped to background_value. This node
repaints every such gap with the label of its nearest surviving pixel, found by
iterative single-pixel dilation (8-connected / Chebyshev nearest; ties resolved
toward the larger class id). Gaps no label can reach -- e.g. a class wiped out
entirely by an area filter -- fall back to the original label on the source
port. The foreground to fill is source != background_value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
background_value
|
int
|
Label value treated as "unassigned" in both inputs and the output.
Default |
-1
|
Source code in cuvis_ai/node/mask_ops.py
forward
¶
Grow surviving labels into the gaps; fall back to source where unreachable.
Source code in cuvis_ai/node/mask_ops.py

OcclusionNodeBasecuvis_ai.node.occlusiontransformBase class for synthetic occlusion from tracking masks.
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

PCAcuvis_ai.node.dimensionality_reductiontransformProject each frame independently onto its principal components.
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

PRISelectorcuvis_ai.node.channel_selectortransformPhotochemical Reflectance Index renderer.
PRISelector
¶
PRISelector(
band1_nm=531.0,
band2_nm=570.0,
colormap_min=-1.0,
colormap_max=1.0,
eps=1e-06,
**kwargs,
)
Bases: _VegetationIndexBase
Photochemical Reflectance Index renderer.
Computes (R531 - R570) / (R531 + R570) over bands resolved by nearest
sensor wavelength. The raw index map is returned via index_image and
rgb_image carries an HSV colour-mapped render.
Source code in cuvis_ai/node/channel_selector.py

PatchSamplercuvis_ai.node.patch_inferencetransformExtract labeled center-pixel patches from a cube and an integer target map.
PatchSampler
¶
PatchSampler(
patch_size=7,
samples_per_frame=256,
class_balanced=True,
ignore_index=-100,
mode="train",
max_per_frame=None,
**kwargs,
)
Bases: Node
Extract labeled center-pixel patches from a cube and an integer target map.
For each frame, gather the pixels whose target is not ignore_index and, around each, cut a
patch_size x patch_size window (reflect-padded at borders), emitting patches
[N, P, P, C] and integer labels [N]. patch_size=1 yields single-pixel spectra;
larger odd sizes yield spatial-spectral patches.
mode="train" draws samples_per_frame center pixels per frame (class-balanced by default,
with replacement); mode="eval" takes every labeled pixel, optionally strided down to
max_per_frame for dense scoring. Sampling uses torch's global RNG, so seeding torch makes a
run reproducible while still drawing fresh patches each call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patch_size
|
int
|
Side of the square window; must be a positive odd integer. Default |
7
|
samples_per_frame
|
int
|
Center pixels drawn per frame in |
256
|
class_balanced
|
bool
|
In |
True
|
ignore_index
|
int
|
Target value marking pixels to skip (never sampled). Default |
-100
|
mode
|
str
|
|
'train'
|
max_per_frame
|
int or None
|
In |
None
|
Validate and store the sampling hyperparameters.
Source code in cuvis_ai/node/patch_inference.py
forward
¶
Sample patches and labels across the batch's frames.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube |
required |
targets
|
Tensor
|
Per-pixel integer class targets |
required |
**_
|
Any
|
Additional unused keyword arguments (e.g. the pipeline |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/patch_inference.py

PatchSamplercuvis_ai_inspecscrap.node.patch_samplertransform

PerChannelStandardizercuvis_ai_inspecscrap.node.normalizationtransform

PerPixelUnitNormcuvis_ai.node.normalizationtransformPer-pixel mean-centering and L2 normalization across channels.
PerPixelUnitNorm
¶
Bases: _ScoreNormalizerBase
Per-pixel mean-centering and L2 normalization across channels.
Source code in cuvis_ai/node/normalization.py

PercentileNormalizercuvis_ai.node.normalizationtransformPer-channel normalization to ``[0, 1]`` for BHWC data of any channel count.
PercentileNormalizer
¶
PercentileNormalizer(
n_channels,
norm_mode=RUNNING,
freeze_running_bounds_after_frames=20,
running_warmup_frames=10,
quantile_low=0.005,
quantile_high=0.995,
eps=1e-08,
**kwargs,
)
Bases: _ScoreNormalizerBase
Per-channel normalization to [0, 1] for BHWC data of any channel count.
Extracted from ChannelSelectorBase so band selection and display
normalization are separate, composable steps. Operates on any channel count
C (fixed at construction via n_channels). Does not apply sRGB
gamma; chain :class:DisplayNormalizer after it for the false-RGB display
path. ML / n-channel callers use this node alone.
Modes (norm_mode):
per_frame: per-batch, per-channel absolute min/max; no inter-frame state.statistical: global percentile bounds precomputed viaStatisticalTrainer.running(default): the firstrunning_warmup_framesframes use per-frame percentile normalization while accumulating global percentile bounds (min-of-lows, max-of-highs); afterwards those bounds are used, frozen afterfreeze_running_bounds_after_framescalls. Bounds update on every call including inference, which live false-RGB video relies on; the freeze guards late drift.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_channels
|
int
|
Channel count |
required |
norm_mode
|
str | NormMode
|
Normalization mode. Default |
RUNNING
|
freeze_running_bounds_after_frames
|
int | None
|
Stop updating |
20
|
running_warmup_frames
|
int
|
Frames to normalize per-frame while accumulating bounds. Default |
10
|
quantile_low
|
float
|
Percentile bounds (fractions) for |
0.005
|
quantile_high
|
float
|
Percentile bounds (fractions) for |
0.005
|
eps
|
float
|
Floor for the |
1e-08
|
Ports
INPUT_SPECS
data : float32, shape (-1, -1, -1, -1), BHWC tensor with C == n_channels.
OUTPUT_SPECS
normalized : float32, shape (-1, -1, -1, -1), same shape, values in [0, 1].
Source code in cuvis_ai/node/normalization.py
statistical_initialization
¶
Accumulate global per-channel percentile bounds across the dataset.
Preserves the established min-of-batch-lows / max-of-batch-highs accumulation (batch-order sensitive); a true streaming percentile is a deliberate follow-up, not changed here.
Source code in cuvis_ai/node/normalization.py

PoissonCubeOcclusionNodecuvis_ai.node.occlusiontransformDeprecated alias of PoissonOcclusionNode with cube-only ports.
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
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 | |
forward
¶
Apply cube-only occlusion using the parent implementation.
Source code in cuvis_ai/node/occlusion.py

PoissonOcclusionNodecuvis_ai.node.occlusiontransformPure-PyTorch occlusion node for either RGB frames or hyperspectral cubes.
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
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 | |
forward
¶
Occlude either the provided RGB batch or cube batch for the current frame.
Source code in cuvis_ai/node/occlusion.py

QuantileBinaryDecidercuvis_ai.node.deciders.binary_decidertransformQuantile-based thresholding node operating on BHWC logits or scores.
QuantileBinaryDecider
¶
Bases: BinaryDecider
Quantile-based thresholding node operating on BHWC logits or scores.
This decider computes a tensor-valued threshold per batch item using the requested quantile over one or more non-batch dimensions, then produces a binary mask where values greater than or equal to that threshold are marked as anomalies. Useful for adaptive thresholding when score distributions vary across batches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
quantile
|
float
|
Quantile in the closed interval [0, 1] used for the threshold computation (default: 0.995). Higher values (e.g., 0.99, 0.995) are typical for anomaly detection to capture rare events. |
0.995
|
reduce_dims
|
Sequence[int] | None
|
Axes (relative to the input tensor) over which to compute the quantile.
When |
None
|
Examples:
>>> from cuvis_ai.node.deciders.binary_decider import QuantileBinaryDecider
>>> import torch
>>>
>>> # Create quantile-based decider (99.5th percentile)
>>> decider = QuantileBinaryDecider(quantile=0.995)
>>>
>>> # Apply to anomaly scores
>>> scores = torch.randn(4, 256, 256, 1) # [B, H, W, C]
>>> output = decider.forward(logits=scores)
>>> decisions = output["decisions"] # [4, 256, 256, 1] boolean mask
>>>
>>> # Per-channel thresholding (reduce H, W only)
>>> decider_perchannel = QuantileBinaryDecider(
... quantile=0.99,
... reduce_dims=[1, 2], # Compute threshold per channel
... )
See Also
BinaryDecider : Fixed threshold decisioning
Source code in cuvis_ai/node/deciders/binary_decider.py
forward
¶
Apply quantile-based thresholding to produce binary decisions.
Computes per-batch thresholds using the specified quantile over reduce_dims, then classifies values >= threshold as anomalies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Input logits or anomaly scores, shape (B, H, W, C) |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary containing:
|
Source code in cuvis_ai/node/deciders/binary_decider.py

ROIZoomNodecuvis_ai.node.compositingtransformCrop a region defined by a bbox and resize it to a fixed output frame.
ROIZoomNode
¶
Bases: Node
Crop a region defined by a bbox and resize it to a fixed output frame.
Emits one RGB frame per input frame at (zoom_height, zoom_width).
When valid is provided and equals 0 for a frame, the output is a
solid bg_color frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zoom_height
|
int
|
Output frame dimensions in pixels. Defaults 320 x 320. |
320
|
zoom_width
|
int
|
Output frame dimensions in pixels. Defaults 320 x 320. |
320
|
bg_color
|
tuple[float, float, float]
|
Background RGB (in [0, 1]) used when |
(0.0, 0.0, 0.0)
|
Source code in cuvis_ai/node/compositing.py

RangeAverageFalseRGBSelectorcuvis_ai.node.channel_selectortransformRange-based false RGB selection by averaging bands per channel.
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

RgbLabelToClassIndexcuvis_ai_inspecscrap.node.labelstransform

SAVISelectorcuvis_ai.node.channel_selectortransformSoil Adjusted Vegetation Index renderer.
SAVISelector
¶
SAVISelector(
red_nm=660.0,
nir_nm=800.0,
soil_factor=0.5,
colormap_min=-1.0,
colormap_max=1.0,
eps=1e-06,
**kwargs,
)
Bases: _VegetationIndexBase
Soil Adjusted Vegetation Index renderer.
Computes (1 + L) * (NIR - Red) / (NIR + Red + L) over bands resolved by
nearest sensor wavelength, where L is the soil-brightness correction. The
raw index map is returned via index_image and rgb_image carries an HSV
colour-mapped render.
The additive L constant is only meaningful for reflectance in [0, 1];
feed reflectance-calibrated cubes, not raw radiance/DN.
Source code in cuvis_ai/node/channel_selector.py

SNVCorrectioncuvis_ai.node.pretreatments.snvtransformStandard Normal Variate correction along the spectral axis.
SNVCorrection
¶
Bases: Node
Standard Normal Variate correction along the spectral axis.
For every spectrum the per-band mean is subtracted and the result divided by the per-band standard deviation, removing multiplicative scatter and additive baseline effects on a pixel-by-pixel basis. Stateless: no fitting required.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eps
|
float
|
Lower clamp on the per-spectrum standard deviation, guarding against division by zero on flat spectra (default: 1e-8). |
1e-08
|
Source code in cuvis_ai/node/pretreatments/snv.py
forward
¶
Apply per-spectrum mean centring and unit-variance scaling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Input cube in BHWC format. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/pretreatments/snv.py

SaturatedPixelDetectorcuvis_ai.node.preprocessorstransformFlag pixels whose channels reach the sensor saturation value.
SaturatedPixelDetector
¶
Bases: Node
Flag pixels whose channels reach the sensor saturation value.
For every pixel the node computes the fraction of bands that sit at or above
saturation_value and exposes it as a per-pixel scores map. A boolean
decisions mask marks pixels whose saturated-band fraction exceeds
mask_threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
saturation_value
|
float
|
Reflectance/intensity level at which a band counts as saturated.
Bands with |
1.0
|
mask_threshold
|
float
|
Threshold on the saturated-band fraction. Pixels with
|
0.0
|
Examples:
>>> detector = SaturatedPixelDetector(saturation_value=1.0, mask_threshold=0.0)
>>> cube = torch.rand(2, 8, 8, 16)
>>> out = detector.forward(cube=cube)
>>> out["scores"].shape, out["decisions"].shape
(torch.Size([2, 8, 8, 1]), torch.Size([2, 8, 8, 1]))
Source code in cuvis_ai/node/preprocessors.py
forward
¶
Compute the per-pixel saturated-band fraction and saturation mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Input hyperspectral cube |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/preprocessors.py

SavitzkyGolaycuvis_ai.node.pretreatments.savitzky_golaytransformSavitzky-Golay smoothing / derivative filter over the spectral axis.
SavitzkyGolay
¶
Bases: Node
Savitzky-Golay smoothing / derivative filter over the spectral axis.
A polynomial of degree polyorder is least-squares fitted within a
sliding window of window_length bands; the fitted value (or its
deriv-th derivative) replaces the centre band. Coefficients are built
once via :func:scipy.signal.savgol_coeffs and applied with a single
conv1d along the channel axis.
Notes
The SciPy coefficients are convolution-oriented, while torch conv1d
is a cross-correlation; the kernel is therefore stored already flipped so
the result matches scipy.signal.savgol_filter(..., mode="nearest") on
the interior. This filter does not reproduce SciPy's mode="interp"
boundary handling.
Sample spacing (deriv > 0 only)
A Savitzky-Golay kernel is a fixed convolution, so it assumes uniform band
spacing. When the optional wavelengths port is connected, the effective
spacing is taken from it (the median of the band steps) and the derivative
is rescaled accordingly, so the delta parameter is only used as a
fallback when wavelengths is absent. If the bands are not uniformly
spaced, a single kernel cannot be exact and a warning is emitted; use
:class:~cuvis_ai.node.pretreatments.spectral_derivative.SpectralDerivative
for a coordinate-aware derivative.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window_length
|
int
|
Length of the filter window in bands; must be odd (default: 11). |
11
|
polyorder
|
int
|
Order of the fitted polynomial; must be less than |
2
|
deriv
|
int
|
Order of the derivative to compute; |
0
|
delta
|
float
|
Fallback sample spacing in nm, used for |
1.0
|
mode
|
str
|
Boundary handling: |
'nearest'
|
Source code in cuvis_ai/node/pretreatments/savitzky_golay.py
forward
¶
Apply the Savitzky-Golay filter along the spectral axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Input cube in BHWC format. |
required |
wavelengths
|
array - like
|
Band wavelengths in nm. For |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/pretreatments/savitzky_golay.py

ScoreToLogitcuvis_ai.node.conversiontransformTrainable head that converts RX scores to anomaly logits.
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

ShapeMorphologycuvis_ai.node.morphologytransformPer-object shape descriptors from a binary or labeled mask.
ShapeMorphology
¶
Bases: Node
Per-object shape descriptors from a binary or labeled mask.
For each batch element the mask is reduced to integer instance labels
(connected components when binarize is True, otherwise the input is
taken to already carry labels) and a fixed set of geometric descriptors is
computed per object. Descriptors follow the
skimage.measure.regionprops conventions:
area- pixel count of the region.centroid_y/centroid_x- mean pixel coordinates.major_axis/minor_axis-4 * sqrt(lambda)of the two covariance eigenvalues (descending).eccentricity-sqrt(1 - lambda_2 / lambda_1).orientation-0.5 * atan2(2 * cov_xy, cov_yy - cov_xx).bbox_area- area of the axis-aligned bounding box.
Rows are padded to max_objects; valid marks the first N rows
True (real objects) and the remainder False (padding).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
properties
|
list of str
|
Descriptor names to emit, in order along the |
None
|
max_objects
|
int
|
Number of object rows in the output; objects beyond this are dropped
and fewer objects are zero-padded. Default |
256
|
connectivity
|
int
|
Pixel connectivity ( |
8
|
binarize
|
bool
|
If True, treat any nonzero pixel as foreground and run connected-
component labeling. If False, treat the input as an already-labeled
mask and use its nonzero values as instance ids. Default |
True
|
Source code in cuvis_ai/node/morphology.py
forward
¶
Label objects and emit per-object descriptors, padded to max_objects.
Source code in cuvis_ai/node/morphology.py

SigmoidNormalizercuvis_ai.node.normalizationtransformMedian-centered sigmoid squashing per sample and channel.
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

SigmoidTransformcuvis_ai.node.normalizationtransformApplies sigmoid transformation to convert logits to probabilities [0,1].
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

SignaturesToReferencescuvis_ai.node.spectral_extractortransformTreat each object's signature as its own Spectral Angle Mapper reference.
SignaturesToReferences
¶
Bases: Node
Treat each object's signature as its own Spectral Angle Mapper reference.
Reshapes per-object signatures [1, N, C] (as produced by
:class:SpectralSignatureExtractor) into reference spectra [N, 1, 1, C]
for :class:~cuvis_ai.node.spectral_angle_mapper.SpectralAngleMapper -- one
reference per object, in object-id order, so reference k corresponds to
object k. Use it when every detected object is known a priori to be a
distinct material: each object's signature becomes a reference, the mapper
scores every pixel against all references, and each object should recover
its own pixels. The reference count follows the number of objects (no fixed
reference count, no clustering).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
normalize
|
str or None
|
Optional reference normalization: |
None
|
Validate the optional normalization mode and store it.
Source code in cuvis_ai/node/spectral_extractor.py
forward
¶
Reshape per-object signatures into one reference spectrum per object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signatures
|
Tensor
|
Per-object signatures |
required |
**_
|
Any
|
Additional unused keyword arguments (e.g. the pipeline |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/spectral_extractor.py

SolidOcclusionNodecuvis_ai.node.occlusiontransformDeprecated alias of PoissonOcclusionNode.
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
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 | |

SpatialRotateNodecuvis_ai.node.preprocessorstransformRotate spatial dimensions of cubes, masks, and RGB images.
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

SpectralDerivativecuvis_ai.node.pretreatments.spectral_derivativetransformFirst- or second-order spectral derivative along the band axis.
SpectralDerivative
¶
Bases: Node
First- or second-order spectral derivative along the band axis.
Derivatives suppress additive/multiplicative baseline effects and sharpen
absorption features. The derivative is taken with respect to wavelength
(nanometers), honouring non-uniform band spacing via the wavelengths
port.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order
|
int
|
Derivative order; |
1
|
Source code in cuvis_ai/node/pretreatments/spectral_derivative.py
forward
¶
Differentiate each spectrum with respect to wavelength.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Input cube in BHWC format. |
required |
wavelengths
|
array - like
|
Band wavelengths, length |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/pretreatments/spectral_derivative.py

SpectralSignatureExtractorcuvis_ai.node.spectral_extractortransformExtract per-object spectral signatures from SAM-style label masks.
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.
Notes
Only the first batch element of cube is processed; mask is required
to be [1, H, W] by INPUT_SPECS. Outputs are always shaped
[1, N, C]. Feed one frame at a time.
Source code in cuvis_ai/node/spectral_extractor.py
forward
¶
Extract per-object signatures. See class docstring for batch semantics.
Source code in cuvis_ai/node/spectral_extractor.py

TitleOverlaycuvis_ai.node.compositingtransformBurn a text caption into the top-left of each RGB frame, over a translucent box.
TitleOverlay
¶
TitleOverlay(
text="",
font_size=20,
pad_px=8,
text_color=(255, 255, 255),
box_color=(0, 0, 0),
box_alpha=0.5,
**kwargs,
)
Bases: Node
Burn a text caption into the top-left of each RGB frame, over a translucent box.
The caption comes from one of three places, in priority order: the per-frame
caption input port (a list[str], one entry per frame, so a DataModule can
title each montage column), the text argument to :meth:forward, or the
constructor text default. Drawn with PIL over a semi-transparent box so it stays
legible on any background.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Default caption drawn into every frame when no per-frame |
''
|
font_size
|
int
|
Caption font size in points (default 20). |
20
|
pad_px
|
int
|
Inset of the caption box from the top-left corner (default 8). |
8
|
text_color
|
tuple[int, int, int]
|
Text and box RGB colours in 0-255. |
(255, 255, 255)
|
box_color
|
tuple[int, int, int]
|
Text and box RGB colours in 0-255. |
(255, 255, 255)
|
box_alpha
|
float
|
Opacity of the box behind the text (default 0.5). |
0.5
|
Source code in cuvis_ai/node/compositing.py
forward
¶
Caption each frame from the per-frame caption port, text, or the default.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
Tensor
|
RGB frames |
required |
caption
|
list[str] or None
|
Per-frame captions, one per batch element; takes priority over |
None
|
text
|
str or None
|
Single caption applied to every frame, overriding the constructor default. |
None
|
**_
|
Any
|
Additional unused keyword arguments (e.g. the pipeline |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/compositing.py

TopKIndicescuvis_ai.node.channel_selectortransformUtility node that surfaces the top-k channel indices from selector weights.
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

TwoStageBinaryDecidercuvis_ai.node.deciders.two_stage_decidertransformTwo-stage binary decider: image-level gate + pixel quantile mask.
TwoStageBinaryDecider
¶
TwoStageBinaryDecider(
image_threshold=0.5,
top_k_fraction=0.001,
quantile=0.995,
reduce_dims=None,
**kwargs,
)
Bases: BinaryDecider
Two-stage binary decider: image-level gate + pixel quantile mask.
Source code in cuvis_ai/node/deciders/two_stage_decider.py
forward
¶
Apply two-stage binary decision: image-level gate + pixel quantile.
Stage 1: Compute image-level anomaly score from top-k pixel scores. If below threshold, return blank mask (no anomalies).
Stage 2: For images passing the gate, apply pixel-level quantile thresholding to create binary anomaly mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Anomaly scores [B, H, W, C] or [B, H, W, 1]. |
required |
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "decisions" key containing binary masks [B, H, W, 1]. |
Notes
The image-level score is computed as the mean of the top-k% highest pixel scores. For multi-channel inputs, the max across channels is used for each pixel.
Source code in cuvis_ai/node/deciders/two_stage_decider.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 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 | |

UnitVarianceScalingcuvis_ai.node.pretreatments.scalingtransformDivide the cube by a globally-fitted per-channel standard deviation.
UnitVarianceScaling
¶
Bases: _StatisticalFitNode
Divide the cube by a globally-fitted per-channel standard deviation.
During statistical_initialization every training pixel is streamed
through a Welford accumulator to compute the exact per-channel standard
deviation (sample, ddof=1) over the full dataset; forward then
divides each spectrum by that standard deviation.
Notes
The fitted std_c is registered as a persistent buffer so a
checkpointed node reloads ready for inference.
Source code in cuvis_ai/node/pretreatments/scaling.py
statistical_initialization
¶
Fit the per-channel standard deviation from the stream via Welford.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterable of port-keyed batch dicts matching |
required |
Source code in cuvis_ai/node/pretreatments/scaling.py
forward
¶
Divide the cube by the fitted per-channel standard deviation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Input cube in BHWC format. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
|
Source code in cuvis_ai/node/pretreatments/scaling.py

WaferSegmentationcuvis_ai_wafer_thickness.node.wafer_segmentationtransformSegment a wafer from a flat background by spectral contrast.
Segment a wafer from a flat background by spectral contrast.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
cube |
float32 |
[-1, -1, -1, -1] |
Hyperspectral reflectance cube [B, H, W, C]. |
wavelengths |
int32 |
[-1] |
Wavelengths [C] in nm. |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
mask |
int32 |
[-1, -1, -1] |
Wafer mask [B, H, W]; non-zero = wafer. |

WaferThicknesscuvis_ai_wafer_thickness.node.wafer_thicknesstransformPer-pixel film thickness [nm] from interference-order peak positions.
Per-pixel film thickness [nm] from interference-order peak positions.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
cube |
float32 |
[-1, -1, -1, -1] |
Hyperspectral reflectance cube [B, H, W, C]. |
wavelengths |
int32 |
[-1] |
Wavelengths [C] in nm. |
mask optional |
int32 |
[-1, -1, -1] |
Wafer mask [B, H, W]; non-zero = analyse. Optional: omitted = all pixels. |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
thickness |
float32 |
[-1, -1, -1] |
Per-pixel film thickness [B, H, W] in nm; NaN outside mask. |
uncertainty |
float32 |
[-1, -1, -1] |
Std of per-order thickness estimates [B, H, W] in nm (lower is better; 0 for a single order); NaN outside mask. |

YOLOPostprocesscuvis_ai_ultralytics.nodetransformUltralytics NMS + box scaling postprocess for YOLO raw tensors.
Ultralytics NMS + box scaling postprocess for YOLO raw tensors.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
raw_preds |
float32 |
[-1, -1, -1] |
Raw YOLO tensor |
model_input_hw |
int64 |
[-1, 2] |
Model H,W |
orig_hw |
int64 |
[-1, 2] |
Original H,W |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
bboxes |
float32 |
[-1, -1, 4] |
Final boxes [B, N, 4] |
category_ids |
int64 |
[-1, -1] |
Class ids [B, N] |
confidences |
float32 |
[-1, -1] |
Scores [B, N] |

YOLOPreprocesscuvis_ai_ultralytics.nodetransformConvert RGB images to stride-aligned channel-first BGR tensors for YOLO.
Convert RGB images to stride-aligned channel-first BGR tensors for YOLO.
Inputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
rgb_image |
float32 |
[-1, -1, -1, 3] |
RGB image [B, H, W, 3] in [0, 1] |
Outputs
| Port | Dtype | Shape | Description |
|---|---|---|---|
preprocessed |
float32 |
[-1, 3, -1, -1] |
Channel-first BGR [B, 3, H', W'] stride-aligned, in [0, 1] |
model_input_hw |
int64 |
[-1, 2] |
Padded model input [H', W'] per sample |
orig_hw |
int64 |
[-1, 2] |
Original image [H, W] per sample before preprocessing |

ZScoreNormalizercuvis_ai.node.normalizationtransformZ-score (standardization) normalization along specified dimensions.
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

ZScoreNormalizerGlobalcuvis_ai.node.anomaly.deep_svddtransformPort-based Deep SVDD z-score normalizer for BHWC cubes.
ZScoreNormalizerGlobal
¶
Bases: Node
Port-based Deep SVDD z-score normalizer for BHWC cubes.
Source code in cuvis_ai/node/anomaly/deep_svdd.py
requires_initial_fit
property
¶
Whether this node requires statistical initialization from training data.
Returns:
| Type | Description |
|---|---|
bool
|
Always True for Z-score normalization. |
statistical_initialization
¶
Estimate per-band z-score statistics from the provided stream.
Source code in cuvis_ai/node/anomaly/deep_svdd.py
forward
¶
Apply per-channel Z-score normalization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input feature tensor [B, H, W, C]. |
required |
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "normalized" key containing Z-score normalized data [B, H, W, C]. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If statistical_initialization() has not been called. |
ValueError
|
If input channel count doesn't match initialized num_channels. |
Source code in cuvis_ai/node/anomaly/deep_svdd.py

_ColormappedNormalizedDifferenceSelectorcuvis_ai.node.channel_selectortransformTwo-band normalized-difference selector with an HSV-colormap RGB render.
_ColormappedNormalizedDifferenceSelector
¶
_ColormappedNormalizedDifferenceSelector(
primary_nm,
secondary_nm,
colormap_min=-1.0,
colormap_max=1.0,
eps=1e-06,
**kwargs,
)
Bases: _NormalizedDifferenceIndexBase, ABC
Two-band normalized-difference selector with an HSV-colormap RGB render.
Abstract base: concrete subclasses set the primary/secondary default
wavelengths and implement the semantic index_name / primary_label /
secondary_label properties. The scalar index image is mapped to
rgb_image with the same Blood_OXY-style HSV colormap path that
:class:NDVISelector uses, controlled by colormap_min / colormap_max.
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Compute the normalized-difference index plus a colour-mapped RGB output.
Source code in cuvis_ai/node/channel_selector.py

_NormalizedDifferenceIndexBasecuvis_ai.node.channel_selectortransformAbstract base for two-band normalized-difference indices.
_NormalizedDifferenceIndexBase
¶
_NormalizedDifferenceIndexBase(
primary_nm,
secondary_nm,
eps=1e-06,
band_tolerance_nm=50.0,
**kwargs,
)
Bases: ChannelSelectorBase, ABC
Abstract base for two-band normalized-difference indices.
Subclasses define the semantic labels and strategy name, while this base handles nearest-band resolution, stable normalized-difference computation, and delegates RGB rendering to subclasses.
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Compute raw index image plus RGB render.
Source code in cuvis_ai/node/channel_selector.py

_ScoreNormalizerBasecuvis_ai.node.normalizationtransformBase class for BHWC normalization nodes.
_ScoreNormalizerBase
¶
Bases: Node
Base class for BHWC normalization nodes.
Notes
All normalization nodes in this module expect inputs in BHWC format
([batch, height, width, channels]). Callers are responsible for adding
a batch dimension when working with HWC tensors (use x.unsqueeze(0)).
Most subclasses are differentiable, but some keep fitted statistical state
(e.g. :class:MinMaxNormalizer with running stats, :class:PercentileNormalizer)
and update it under no_grad during forward.
Source code in cuvis_ai/node/normalization.py
forward
¶
Normalize input data (BHWC only).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor in BHWC format [B, H, W, C] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "normalized" key containing normalized tensor |
Source code in cuvis_ai/node/normalization.py

_VegetationIndexBasecuvis_ai.node.channel_selectortransformAbstract base for multi-band vegetation indices with custom formulas.
_VegetationIndexBase
¶
_VegetationIndexBase(
band_nm,
colormap_min=-1.0,
colormap_max=1.0,
eps=1e-06,
band_tolerance_nm=50.0,
**kwargs,
)
Bases: ChannelSelectorBase, ABC
Abstract base for multi-band vegetation indices with custom formulas.
Resolves a set of named bands (each a defaulted, tunable wavelength hparam)
to their nearest sensor wavelengths, computes a scalar index_image from a
subclass-provided formula, and renders rgb_image with the same Blood_OXY
HSV colormap path used by :class:NDVISelector. Denominators in subclass
formulas should be clamped with self.eps to avoid divide-by-zero.
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Compute the vegetation index plus a colour-mapped RGB output.
Source code in cuvis_ai/node/channel_selector.py

DensePatchDataModulecuvis_ai_inspecscrap.data.dense_patch_datamoduleunspecified
Data module metal_scrap_dense_patch — pip extras: tiff.

MetalScrapDataModulecuvis_ai_inspecscrap.data.metal_scrap_datamoduleunspecified
Data module metal_scrap — pip extras: tiff.

MetalScrapPatchDataModulecuvis_ai_inspecscrap.data.metal_scrap_patch_datamoduleunspecified
Data module metal_scrap_patch — pip extras: tiff.

MontageColumnDataModulecuvis_ai_inspecscrap.data.montage_column_datamoduleunspecified
Data module metal_scrap_montage_columns — pip extras: none.

AnomalyMaskcuvis_ai.node.anomaly_visualizationvisualizerVisualize anomaly detection with GT and predicted masks.
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
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 410 411 412 413 414 415 416 417 418 | |

BBoxesOverlayNodecuvis_ai.node.anomaly_visualizationvisualizerTorch-only bounding-box overlay renderer for YOLO-style detections.
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

ChannelSelectorFalseRGBVizcuvis_ai.node.anomaly_visualizationvisualizerVisualize false RGB output from channel selectors with optional mask overlay.
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

ChannelWeightsVizcuvis_ai.node.anomaly_visualizationvisualizerVisualize channel mixer weights as a heatmap.
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
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 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 | |

ClassMapToRGBcuvis_ai.node.colormapvisualizerColourise an integer class-index map ``[B, H, W]`` into an RGB image ``[B, H, W, 3]``.
ClassMapToRGB
¶
Bases: Node
Colourise an integer class-index map [B, H, W] into an RGB image [B, H, W, 3].
Each class id indexes a palette colour; pixels equal to background_value (and, when a
mask is connected, pixels where mask == 0) render black. The explicit palette
lets it colourise arbitrary integer id-maps (compartment ids, cluster ids, class indices).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
palette
|
list[tuple[int, int, int]] | None
|
Per-id RGB colours in 0-255, indexed by class id. When |
None
|
background_value
|
int
|
Class id rendered black (default |
-1
|
Source code in cuvis_ai/node/colormap.py
forward
¶
Look the palette up per pixel; background and masked-out pixels stay black.
Source code in cuvis_ai/node/colormap.py

CubeRGBVisualizercuvis_ai.node.pipeline_visualizationvisualizerCreates false-color RGB images from hyperspectral cube using channel weights.
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

ImageArtifactVizBasecuvis_ai.node.anomaly_visualizationvisualizerBase class for visualization nodes that produce image artifacts.
ImageArtifactVizBase
¶
Bases: Node
Base class for visualization nodes that produce image artifacts.
Source code in cuvis_ai/node/anomaly_visualization.py

MaskOverlayNodecuvis_ai.node.anomaly_visualizationvisualizerAlpha-blend a coloured mask overlay onto RGB frames.
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

PCAVisualizationcuvis_ai.node.pipeline_visualizationvisualizerVisualize PCA-projected data with scatter and image plots.
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
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 | |

PipelineComparisonVisualizercuvis_ai.node.pipeline_visualizationvisualizerTensorBoard visualization node for comparing pipeline stages.
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 |
anomaly_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
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 539 540 541 542 543 544 545 546 547 548 549 550 551 | |

RGBAnomalyMaskcuvis_ai.node.anomaly_visualizationvisualizerVisualize anomaly detection with GT and predicted masks on RGB images.
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
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 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 | |

ScalarHSVColormapNodecuvis_ai.node.colormapvisualizerMap a scalar BHWC image to RGB using an HSV colormap.
ScalarHSVColormapNode
¶
Bases: Node
Map a scalar BHWC image to RGB using an HSV colormap.
Source code in cuvis_ai/node/colormap.py
forward
¶
Colorize a scalar image in BHWC format.
Source code in cuvis_ai/node/colormap.py

ScoreHeatmapVisualizercuvis_ai.node.anomaly_visualizationvisualizerLog LAD/RX score heatmaps as TensorBoard artifacts.
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

SpectraPlotcuvis_ai.node.spectrum_plotvisualizerRender a multi-series line plot of per-class mean spectra into an RGB frame.
SpectraPlot
¶
SpectraPlot(
palette=None,
title="",
xlabel="wavelength in [nm]",
ylabel="value",
plot_width=720,
plot_height=540,
dpi=150,
linewidth=1.0,
bg_color="white",
fg_color="black",
**kwargs,
)
Bases: Node
Render a multi-series line plot of per-class mean spectra into an RGB frame.
A multi-series sibling of :class:SpectrumPlotNode: instead of a tracked-vs-reference pair, it
draws one line per row of signatures (e.g. the per-object mean spectra from
:class:~cuvis_ai.node.spectral_extractor.SpectralSignatureExtractor), coloured by palette.
The plot is rendered to a fixed-size RGB frame so it drops into the graph like any other image
output (stitch several with ImageConcatenator).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
palette
|
list[tuple[int, int, int]] | None
|
Per-row line colours in 0-255, indexed by row id and wrapped modulo its length. Share the
same palette as a |
None
|
title
|
str
|
Axis title and labels. |
''
|
xlabel
|
str
|
Axis title and labels. |
''
|
ylabel
|
str
|
Axis title and labels. |
''
|
plot_width
|
int
|
Pixel dimensions of the rendered frame (default 720 x 540). |
720
|
plot_height
|
int
|
Pixel dimensions of the rendered frame (default 720 x 540). |
720
|
dpi
|
int
|
Figure dpi (default 150). |
150
|
linewidth
|
float
|
Line width for each spectrum (default 1.0). |
1.0
|
bg_color
|
str
|
Background / foreground (axis, text) colours. |
'white'
|
fg_color
|
str
|
Background / foreground (axis, text) colours. |
'white'
|
Source code in cuvis_ai/node/spectrum_plot.py
forward
¶
Render one multi-series plot frame per batch element.
Source code in cuvis_ai/node/spectrum_plot.py

SpectrumPlotNodecuvis_ai.node.spectrum_plotvisualizerRender a per-frame line plot of tracked vs reference spectrum.
SpectrumPlotNode
¶
SpectrumPlotNode(
wavelengths,
reference_wavelengths,
plot_width=960,
plot_height=720,
dpi=150,
xlabel="wavelength in [nm]",
ylabel="spectral radiance in [W/m²/sr/µm]",
tracked_label="",
reference_label="",
tracked_color="red",
reference_color="lime",
bg_color="black",
fg_color="white",
y_fixed_range=(0.0, 12.0),
y_num_ticks=12,
tracked_hold_frames=15,
**kwargs,
)
Bases: Node
Render a per-frame line plot of tracked vs reference spectrum.
The tracked line is plotted against wavelengths (typically the full
cube grid), while the reference line is plotted against
reference_wavelengths (typically the narrower bandpass subset where
the SAM reference is defined). Both are drawn on a single axes with a
fixed x-range so the axis does not re-scale from frame to frame.
Output shape is fixed to (plot_height, plot_width) so downstream
ToVideoNode gets consistent frame dimensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wavelengths
|
ndarray
|
Full wavelength grid in nm, shape |
required |
reference_wavelengths
|
ndarray
|
Wavelength grid for the reference line in nm, shape |
required |
plot_width
|
int
|
Pixel dimensions of the rendered frame. Default 960 x 720. |
960
|
plot_height
|
int
|
Pixel dimensions of the rendered frame. Default 960 x 720. |
960
|
dpi
|
int
|
Figure dpi. Default 150. |
150
|
xlabel
|
str
|
Axis labels. |
'wavelength in [nm]'
|
ylabel
|
str
|
Axis labels. |
'wavelength in [nm]'
|
tracked_label
|
str
|
Legend labels. |
''
|
reference_label
|
str
|
Legend labels. |
''
|
tracked_color
|
str
|
Matplotlib colour specs for the two lines. |
'red'
|
reference_color
|
str
|
Matplotlib colour specs for the two lines. |
'red'
|
bg_color
|
str
|
Background / foreground colours. |
'black'
|
fg_color
|
str
|
Background / foreground colours. |
'black'
|
y_fixed_range
|
tuple[float, float] | None
|
If set, fixes the y-axis range. Otherwise auto-scales per-frame on the union of tracked+reference values, with a small headroom. |
(0.0, 12.0)
|
y_num_ticks
|
int
|
When |
12
|
tracked_hold_frames
|
int
|
When |
15
|
Source code in cuvis_ai/node/spectrum_plot.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 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 | |

TrackingOverlayNodecuvis_ai.node.anomaly_visualizationvisualizerAlpha-blend per-object coloured masks onto RGB frames.
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
|
text_scale
|
int
|
Integer scale of the object-ID label font (default 2). Use 1 for smaller ids on small frames with many objects. |
2
|
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
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 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 | |

TrackingPointerOverlayNodecuvis_ai.node.anomaly_visualizationvisualizerDraw downward triangle pointers for all tracked objects.
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
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 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 | |
No items match your search and filters.