Status: Needs Review
This page has not been reviewed for accuracy and completeness. Content may be outdated or contain errors.
Utilities API¶
Current helper modules used by the tracking, visualization, restore, and gRPC workflows.
Workflow Helpers¶
grpc_workflow
¶
Shared helpers for gRPC example clients using the Phase 5 workflow.
config_search_paths
¶
Return absolute search paths covering all config groups.
Source code in cuvis_ai/utils/grpc_workflow.py
build_stub
¶
Create a gRPC stub for the CuvisAI service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_address
|
str
|
Server address (default: localhost:50051) |
'localhost:50051'
|
max_msg_size
|
int
|
Maximum message size in bytes (default: 300MB) |
300 * 1024 * 1024
|
Source code in cuvis_ai/utils/grpc_workflow.py
create_session_with_search_paths
¶
Create a session and register search paths.
Source code in cuvis_ai/utils/grpc_workflow.py
resolve_trainrun_config
¶
Resolve a trainrun config via the ConfigService.
Source code in cuvis_ai/utils/grpc_workflow.py
apply_trainrun_config
¶
Apply resolved trainrun config to a session.
Source code in cuvis_ai/utils/grpc_workflow.py
format_progress
¶
Pretty-print training progress messages.
Source code in cuvis_ai/utils/grpc_workflow.py
load_manifest_bytes
¶
Load a plugin YAML manifest, resolve relative plugin paths, and return JSON bytes.
Source code in cuvis_ai/utils/grpc_workflow.py
normalize_pipeline_bytes
¶
Unwrap Hydra group wrappers until a PipelineConfig payload with nodes is reached.
Source code in cuvis_ai/utils/grpc_workflow.py
cli_helpers
¶
CLI and experiment bookkeeping helpers shared across tracking examples.
resolve_run_output_dir
¶
Resolve the per-run output directory from --output-dir and --out-basename.
Source code in cuvis_ai/utils/cli_helpers.py
resolve_end_frame
¶
Reconcile --end-frame and --max-frames into an effective end-frame index.
Source code in cuvis_ai/utils/cli_helpers.py
write_experiment_info
¶
Write an experiment_info.txt alongside outputs for traceability.
Source code in cuvis_ai/utils/cli_helpers.py
append_tracking_metrics
¶
Append diagnostic track-count metrics from a COCO tracking JSON.
Source code in cuvis_ai/utils/cli_helpers.py
Visualization And Drawing Helpers¶
vis_helpers
¶
Visualization helper utilities for converting figures and tensors to arrays.
fig_to_array
¶
Convert matplotlib figure to numpy array in RGB format.
This utility handles the conversion of a matplotlib figure to a numpy array by saving it to a BytesIO buffer, loading it with PIL, and converting to a numpy array. The figure is automatically closed after conversion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fig
|
Figure
|
The matplotlib figure to convert |
required |
dpi
|
int
|
Resolution for the saved image (default: 150) |
150
|
Returns:
| Type | Description |
|---|---|
ndarray
|
RGB image as numpy array with shape (H, W, 3) and dtype uint8 |
Examples:
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [1, 4, 9])
>>> img_array = fig_to_array(fig, dpi=150)
>>> img_array.shape
(height, width, 3)
Source code in cuvis_ai/utils/vis_helpers.py
tensor_to_uint8
¶
Convert float tensor [0, 1] to uint8 [0, 255].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
Input tensor with values in [0, 1] |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Tensor converted to uint8 in range [0, 255], stays on original device |
Source code in cuvis_ai/utils/vis_helpers.py
tensor_to_numpy
¶
Convert torch tensor to numpy array on CPU.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
Input tensor (can be on any device) |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Numpy array representation |
Source code in cuvis_ai/utils/vis_helpers.py
create_mask_overlay
¶
Alpha-blend a colored tint on foreground pixels.
Pure PyTorch, no gradients. Works for both single images [H, W, 3]
and batched [B, H, W, 3] thanks to broadcasting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rgb
|
Tensor
|
RGB image(s) in |
required |
mask
|
Tensor
|
Segmentation mask where |
required |
alpha
|
float
|
Blend factor for the overlay colour (default: 0.4). |
0.4
|
color
|
tuple[float, float, float]
|
RGB overlay colour in |
(1.0, 0.0, 0.0)
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Blended image, same shape and device as rgb, clamped to |
Source code in cuvis_ai/utils/vis_helpers.py
object_color
¶
Return a deterministic RGB colour for object_id (0-255 per channel).
render_multi_object_overlay
¶
render_multi_object_overlay(
frame,
masks,
*,
alpha=0.4,
draw_contours=True,
draw_ids=True,
contour_thickness=2,
font_scale=0.7,
font_thickness=2,
)
Render coloured mask overlays with contours and ID labels onto a frame.
This is the shared rendering path used by both the SAM3 tracking script's
built-in overlay output and the standalone render_tracking_overlay.py.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
ndarray
|
RGB image, shape |
required |
masks
|
list[tuple[int, ndarray]]
|
List of |
required |
alpha
|
float
|
Overlay opacity (default 0.4). |
0.4
|
draw_contours
|
bool
|
Draw contour outlines on mask edges (default True). |
True
|
draw_ids
|
bool
|
Render object ID labels above each mask (default True). |
True
|
contour_thickness
|
int
|
Pixel width of contour lines (default 2). |
2
|
font_scale
|
float
|
Legacy text scale knob (default 0.7). Mapped to bitmap font scale. |
0.7
|
font_thickness
|
int
|
Legacy text thickness knob (default 2). Mapped to bitmap font scale. |
2
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Copy of frame with overlays, same shape and dtype. |
Source code in cuvis_ai/utils/vis_helpers.py
torch_draw
¶
Pure-torch drawing helpers for uint8 HWC images.
mask_edge
¶
Compute edge pixels from a binary mask.
Source code in cuvis_ai/utils/torch_draw.py
draw_box
¶
Draw rectangle edges in-place on a uint8 HWC image.
Source code in cuvis_ai/utils/torch_draw.py
draw_text
¶
Draw bitmap text in-place on a uint8 HWC image.
Source code in cuvis_ai/utils/torch_draw.py
draw_downward_triangle
¶
draw_downward_triangle(
img,
tip_x,
tip_y,
width,
height,
color,
*,
outline_color=None,
outline_thickness=1,
)
Draw a filled downward-pointing isosceles triangle in-place.
Source code in cuvis_ai/utils/torch_draw.py
id_to_color
¶
Map integer IDs to deterministic uint8 RGB colors (hybrid policy).
Source code in cuvis_ai/utils/torch_draw.py
overlay_instances
¶
overlay_instances(
image,
masks,
*,
alpha=0.4,
draw_edges=True,
draw_ids=True,
edge_thickness=2,
text_scale=2,
)
Blend instance masks, draw optional edges, and draw optional object IDs.
Source code in cuvis_ai/utils/torch_draw.py
draw_sparkline
¶
Render a filled area sparkline chart on a uint8 HWC image (in-place).
Draws a mini filled area chart of values within the rectangle
(x1, y1, x1+width, y1+height). The values are min-max normalized
internally; the chart is filled from the curve down to the bottom edge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
Tensor
|
|
required |
x1
|
int
|
Top-left corner of the sparkline region. |
required |
y1
|
int
|
Top-left corner of the sparkline region. |
required |
width
|
int
|
Dimensions of the sparkline region in pixels. |
required |
height
|
int
|
Dimensions of the sparkline region in pixels. |
required |
values
|
Tensor
|
|
required |
color
|
Tensor or tuple
|
RGB color for the filled area. |
required |
bg_alpha
|
float
|
Background darkening factor (0=black, 1=no darkening). |
0.5
|
Source code in cuvis_ai/utils/torch_draw.py
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 | |
Color And False-RGB Helpers¶
color_spaces
¶
Color space conversion utilities (PyTorch, differentiable).
srgb_to_linear
¶
Apply inverse sRGB EOTF (companding to linear).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
sRGB values in [0, 1] with arbitrary batch shape. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Linear-light values, same shape as input. |
Source code in cuvis_ai/utils/color_spaces.py
linear_rgb_to_oklab
¶
Convert linear RGB to OKLab.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rgb
|
Tensor
|
Linear RGB tensor with shape |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
OKLab tensor |
Source code in cuvis_ai/utils/color_spaces.py
rgb_to_oklab
¶
Convert RGB to OKLab, optionally handling sRGB input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rgb
|
Tensor
|
RGB tensor |
required |
assume_srgb
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
Tensor
|
OKLab tensor |
Source code in cuvis_ai/utils/color_spaces.py
false_rgb_sampling
¶
Helpers for sampled-fixed false-RGB normalization initialization.
uniform_sample_positions
¶
Return deterministic uniformly spaced indices in [0, total_frames).
Source code in cuvis_ai/utils/false_rgb_sampling.py
build_statistical_sample_stream
¶
Yield sampled inputs in the format expected by statistical_initialization.
Source code in cuvis_ai/utils/false_rgb_sampling.py
initialize_false_rgb_sampled_fixed
¶
Initialize a false-RGB selector statistically from a deterministic sample.
Source code in cuvis_ai/utils/false_rgb_sampling.py
Numerical Utilities¶
poisson_inpaint
¶
GPU/CPU Poisson inpainting for channel-last images.
poisson_inpaint
¶
Inpaint masked pixels by solving the Laplace equation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Tensor
|
Tensor |
required |
mask
|
Tensor
|
Tensor |
required |
max_iter
|
int
|
Maximum CG iterations. |
1000
|
tol
|
float
|
CG residual tolerance. |
1e-06
|
Source code in cuvis_ai/utils/poisson_inpaint.py
73 74 75 76 77 78 79 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 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 | |
welford
¶
Numerically stable streaming statistics using Welford's online algorithm.
Provides a reusable WelfordAccumulator that incrementally computes mean,
variance, covariance, and correlation from batches of data. The accumulator
is an nn.Module so that .to(device) propagates to its internal
buffers automatically when the parent node is moved.
Reference: Welford, B. P. (1962). "Note on a method for calculating corrected sums of squares and products." Technometrics, 4(3), 419-420.
Chan, T. F., Golub, G. H., & LeVeque, R. J. (1979). "Updating formulae
and a pairwise algorithm for computing sample variances."
WelfordAccumulator
¶
Bases: Module
Numerically stable streaming mean / variance / covariance.
All internal accumulation happens in float64 for numerical stability. Property getters return float32 tensors.
The buffers are registered with persistent=False so they are
excluded from state_dict() — only the parent node's own
buffers (mu, cov, …) are serialised. This is correct because
the accumulator is transient training state that is consumed by
finalize() inside statistical_initialization().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_features
|
int
|
Number of features (channels) per sample. |
required |
track_covariance
|
bool
|
If |
False
|
Source code in cuvis_ai/utils/welford.py
cov
property
¶
Sample covariance matrix, shape (C, C), float32.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
corr
property
¶
Absolute correlation matrix, shape (C, C), float32.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
reset
¶
update
¶
Incorporate a batch of samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Tensor
|
Sample matrix of shape |
required |
Source code in cuvis_ai/utils/welford.py
deep_svdd_factory
¶
Deep SVDD Channel Configuration Utilities.
This module provides utilities for inferring channel counts after bandpass filtering for Deep SVDD networks. This is useful for automatically configuring network architectures based on the data pipeline's preprocessing steps.
See Also
cuvis_ai.node.preprocessors : Bandpass filtering nodes cuvis_ai.anomaly.deep_svdd : Deep SVDD anomaly detection
ChannelConfig
dataclass
¶
Configuration for network channel counts.
Stores the number of input and output channels for network layers, typically determined after bandpass filtering.
Attributes:
| Name | Type | Description |
|---|---|---|
num_channels |
int
|
Total number of channels in the network. |
in_channels |
int
|
Number of input channels to the network. |
infer_channels_after_bandpass
¶
Infer post-bandpass channel count from a sample batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
datamodule
|
object
|
Datamodule with a train_dataloader() method returning batches with "wavelengths". |
required |
bandpass_cfg
|
object
|
Config with min_wavelength_nm and max_wavelength_nm fields. |
required |
Returns:
| Type | Description |
|---|---|
ChannelConfig
|
num_channels and in_channels set to the filtered channel count. |