File size: 1,764 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""Shared utility functions used across the floor-visualizer backend."""

from __future__ import annotations

import time
from contextlib import contextmanager

import numpy as np


@contextmanager
def timed_stage(label: str):
    """Context manager that measures elapsed time and prints a timing line.

    Yields a dict with an ``elapsed_ms`` key that is populated on exit.

    Usage::

        with timed_stage("Floor segmentation") as t:
            result = run_segmentation(img)
        print(t["elapsed_ms"])
    """
    info: dict = {"elapsed_ms": 0.0}
    t0 = time.perf_counter()
    try:
        yield info
    finally:
        info["elapsed_ms"] = (time.perf_counter() - t0) * 1000
        print(f"[TIMING] {label} took {info['elapsed_ms'] / 1000:.3f} seconds", flush=True)


def to_numpy(value):
    """Convert a torch.Tensor or array-like to a numpy array."""
    if value is None:
        return None
    try:
        import torch
        if isinstance(value, torch.Tensor):
            return value.detach().float().cpu().numpy()
    except ImportError:
        pass
    return np.asarray(value)


def seg_class_mask(seg_map: np.ndarray, class_id_list: list[int]) -> np.ndarray:
    """Return a uint8 binary mask for pixels whose seg_map value is in *class_id_list*."""
    return np.isin(seg_map, class_id_list).astype(np.uint8)


def mask_to_indices(mask: np.ndarray) -> np.ndarray:
    """Return the flat uint32 indices of non-zero pixels in *mask*."""
    return np.flatnonzero(mask.ravel()).astype(np.uint32)


def encode_b64(arr: np.ndarray | None) -> str | None:
    """Base64-encode a numpy array's raw bytes, or return None."""
    if arr is None:
        return None
    import base64
    return base64.b64encode(arr.tobytes()).decode()