fp2 / src /fiberpose /utils.py
vikba's picture
Upload folder using huggingface_hub
beb4f15 verified
Raw History Blame Contribute Delete
6.71 kB
"""Shared numeric and image helper utilities used across Fiberpose modules."""
import colorsys
import numpy as np
from numba import njit
def label_to_rgb(label: int) -> tuple[int, int, int]:
"""Deterministically map a positive label ID to a vivid RGB color."""
if label <= 0:
return (0, 0, 0)
hue = (label * 0.6180339887498949) % 1.0 # golden ratio multiplier for good spacing
sat = 0.55 + 0.35 * (((label * 0.2171) % 1.0))
val = 0.85
r, g, b = colorsys.hsv_to_rgb(hue, sat, val)
return int(round(r * 255)), int(round(g * 255)), int(round(b * 255))
def labels_to_color(labels: np.ndarray | None) -> np.ndarray | None:
"""Render a label-id map into an RGB visualization image."""
if labels is None:
return None
labels_i64 = np.asarray(labels, dtype=np.int64)
if labels_i64.ndim != 2:
return None
if labels_i64.size == 0:
return np.zeros(labels_i64.shape + (3,), dtype=np.uint8)
# One color per distinct id (label_to_rgb maps ids <= 0 to black), then a single gather.
ids, inverse = np.unique(labels_i64, return_inverse=True)
palette = np.array([label_to_rgb(int(v)) for v in ids], dtype=np.uint8).reshape(-1, 3)
return palette[inverse.reshape(labels_i64.shape)]
# ------------- image helpers -------------
def to_uint8_for_view(img: np.ndarray | None) -> np.ndarray | None:
if img is None:
return None
arr = img.astype(np.float32, copy=False)
if np.isnan(arr).any() or np.isinf(arr).any():
arr = np.nan_to_num(arr, nan=0.0, posinf=0.0, neginf=0.0)
amin, amax = float(arr.min()), float(arr.max())
if amax <= amin:
return np.zeros(arr.shape, dtype=np.uint8)
arr = (arr - amin) / (amax - amin)
return (arr * 255.0).clip(0, 255).astype(np.uint8)
def ensure_rgb_u8(img: np.ndarray | None) -> np.ndarray | None:
if img is None:
return None
if img.ndim == 2:
u8 = to_uint8_for_view(img)
return np.stack([u8, u8, u8], axis=-1)
if img.ndim == 3:
if img.shape[2] == 1:
ch = to_uint8_for_view(img[..., 0])
return np.stack([ch, ch, ch], axis=-1)
if img.dtype != np.uint8:
return to_uint8_for_view(img)[..., :3]
return img[..., :3]
return ensure_rgb_u8(to_uint8_for_view(img))
# ------------- core math helpers -------------
@njit(cache=True)
def _normalize(v, eps=1e-12):
n = np.sqrt(np.sum(v * v))
return v / (n + eps)
@njit(cache=True)
def _bilinear(arr, y, x):
"""Bilinear sample arr at (y, x) with clamped borders. arr is HxW."""
h, w = arr.shape
y0 = int(np.floor(y))
x0 = int(np.floor(x))
y1 = y0 + 1
x1 = x0 + 1
y0c = 0 if y0 < 0 else (h - 1 if y0 >= h else y0)
y1c = 0 if y1 < 0 else (h - 1 if y1 >= h else y1)
x0c = 0 if x0 < 0 else (w - 1 if x0 >= w else x0)
x1c = 0 if x1 < 0 else (w - 1 if x1 >= w else x1)
wy = y - y0
wx = x - x0
a = arr[y0c, x0c]
b = arr[y0c, x1c]
c = arr[y1c, x0c]
d = arr[y1c, x1c]
return (1-wy) * ((1-wx)*a + wx*b) + wy * ((1-wx)*c + wx*d)
@njit(cache=True)
def _sample_vec2(gx, gy, y, x):
"""Sample gradient vector [dy, dx] at (y,x)."""
return np.array([_bilinear(gy, y, x), _bilinear(gx, y, x)])
@njit(cache=True)
def _tangent2d(centerline, k):
"""Unit tangent at index k using central/one-sided differences. centerline is Nx2 in (y,x)."""
N = len(centerline)
if k == 0:
t = centerline[1] - centerline[0]
elif k == N-1:
t = centerline[-1] - centerline[-2]
else:
t = centerline[k+1] - centerline[k-1]
return _normalize(t)
@njit(cache=True)
def _rot90_ccw(v):
"""Rotate (y,x) by +90° in image coordinates."""
return np.array([-v[1], v[0]])
# ------------- normals from DT -------------
@njit(cache=True)
def normals_from_dt_2d(centerline, dt, gx, gy, alpha=0.5, iters=3, tau_g=1e-3, eps=1e-8):
"""
centerline: (N,2) float array of (y,x) points (same pixel coords as dt)
dt: HxW float distance transform
gx, gy: HxW gradients of dt (e.g., gx, gy = np.gradient(dt))
alpha: probe step as fraction of local radius (h = alpha * r)
iters: fixed-point iterations per point
tau_g: threshold on |(g+ - g-)| below which we fall back to n0/previous
returns: (N,2) unit normals (y,x) with continuity enforced
"""
N = len(centerline)
normals = np.zeros((N, 2), dtype=np.float64)
n_iter = max(1, iters)
for k in range(N):
y, x = centerline[k]
r = _bilinear(dt, y, x)
h = alpha * max(r, 1e-6) # always probe a tiny bit, even if r~0
# initial guess n0 from tangent (rotate by 90°)
t = _tangent2d(centerline, k)
n = _rot90_ccw(t)
# prefer previous orientation if available (continuity)
if k > 0 and np.dot(n, normals[k-1]) < 0:
n = -n
# fixed-point refinement
for _ in range(n_iter):
yp, xp = y + h * n[0], x + h * n[1]
ym, xm = y - h * n[0], x - h * n[1]
gp = _sample_vec2(gx, gy, yp, xp) # ∇DT at +h along n
gm = _sample_vec2(gx, gy, ym, xm) # ∇DT at -h along n
d = 0.5 * (gp - gm) # averaged direction (normal candidate)
mag = np.linalg.norm(d)
if mag < tau_g:
break
n_new = d / (mag + eps)
# keep orientation continuous along the curve
if k > 0 and np.dot(n_new, normals[k-1]) < 0:
n_new = -n_new
n = n_new
normals[k] = _normalize(n)
return normals
# ------------- geometry helpers -------------
def resample_polyline_xy(points_xy: np.ndarray, step: float) -> np.ndarray:
"""Resample an open polyline (N,2) in XY to ~equal arc-length spacing of 'step'."""
pts = np.asarray(points_xy, dtype=np.float64).reshape(-1, 2)
if len(pts) < 2:
return pts.copy()
seg = pts[1:] - pts[:-1]
seg_len = np.linalg.norm(seg, axis=1)
cum = np.concatenate([[0.0], np.cumsum(seg_len)])
L = cum[-1]
if L <= 1e-6:
return pts[:1].copy()
s_targets = np.arange(0.0, L + 1e-9, float(step))
if s_targets[-1] < L:
s_targets = np.append(s_targets, L)
out = []
k = 0
for s in s_targets:
while k + 1 < len(cum) and cum[k+1] < s:
k += 1
if k + 1 >= len(cum):
out.append(pts[-1])
else:
ds = cum[k+1] - cum[k]
if ds <= 1e-12:
out.append(pts[k].copy())
else:
a = (s - cum[k]) / ds
out.append(pts[k] * (1 - a) + pts[k+1] * a)
return np.asarray(out, dtype=np.float64)