"""Image-space measures and frame transforms used by visual grounding.
Pure NumPy, no deep-learning dependencies, so everything here is unit-tested.
"""
from __future__ import annotations
import math
import numpy as np
from ..config import DegradationConfig, DepthConfig, Extrinsics, Intrinsics
from ..types import Pose2D
# Optical frame (x right, y down, z forward) -> camera body frame (x forward, y left, z up).
R_BODY_OPTICAL = np.array([[0.0, 0.0, 1.0], [-1.0, 0.0, 0.0], [0.0, -1.0, 0.0]])
# ------------------------------------------------------------- transforms
def rpy_matrix(roll: float, pitch: float, yaw: float) -> np.ndarray:
cr, sr, cp, sp, cy, sy = (
math.cos(roll),
math.sin(roll),
math.cos(pitch),
math.sin(pitch),
math.cos(yaw),
math.sin(yaw),
)
return np.array(
[
[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
[sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
[-sp, cp * sr, cp * cr],
]
)
[docs]
def base_from_optical(ext: Extrinsics) -> np.ndarray:
"""4x4 transform mapping points in the camera optical frame to the base frame."""
T = np.eye(4)
T[:3, :3] = (
rpy_matrix(
math.radians(ext.roll_deg), math.radians(ext.pitch_deg), math.radians(ext.yaw_deg)
)
[docs]
@ R_BODY_OPTICAL
)
T[:3, 3] = (ext.x, ext.y, ext.z)
return T
def backproject(u: float, v: float, depth_m: float, K: Intrinsics) -> np.ndarray:
"""Pinhole back-projection of pixel (u, v) at metric depth into the optical frame."""
return np.array([(u - K.cx) * depth_m / K.fx, (v - K.cy) * depth_m / K.fy, depth_m])
def transform(T: np.ndarray, p: np.ndarray) -> np.ndarray:
return T[:3, :3] @ p + T[:3, 3]
def base_to_map(p_base: np.ndarray, pose: Pose2D) -> np.ndarray:
c, s = math.cos(pose.yaw), math.sin(pose.yaw)
return np.array(
[pose.x + c * p_base[0] - s * p_base[1], pose.y + s * p_base[0] + c * p_base[1], p_base[2]]
)
def intrinsics_from_fov(width: int, height: int, hfov_deg: float) -> Intrinsics:
fx = (width / 2.0) / math.tan(math.radians(hfov_deg) / 2.0)
return Intrinsics(fx=fx, fy=fx, cx=width / 2.0, cy=height / 2.0)
# ----------------------------------------------------------- mask quality
def _hull_area(points: np.ndarray) -> float:
"""Area of the convex hull of 2-D points (Andrew's monotone chain + shoelace)."""
pts = np.unique(points, axis=0)
if len(pts) < 3:
return 0.0
pts = pts[np.lexsort((pts[:, 1], pts[:, 0]))]
def half(seq: np.ndarray) -> list:
chain: list = []
for p in seq:
while len(chain) >= 2:
(x1, y1), (x2, y2) = chain[-2], chain[-1]
if (x2 - x1) * (p[1] - y1) - (y2 - y1) * (p[0] - x1) > 0:
break
chain.pop()
chain.append(tuple(p))
return chain
hull = np.array(half(pts)[:-1] + half(pts[::-1])[:-1])
x, y = hull[:, 0], hull[:, 1]
return 0.5 * abs(float(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))))
[docs]
def mask_quality(mask: np.ndarray) -> float:
"""Q(M) = area(M) / area(convex hull of M), in [0, 1].
Fragmented or ragged masks score low; compact, solid masks score close to 1.
"""
mask = mask.astype(bool)
area = int(mask.sum())
if area == 0:
return 0.0
# Boundary pixels suffice for the hull; use pixel corners so a filled
# rectangle scores exactly 1.
inner = mask.copy()
inner[1:-1, 1:-1] = (
mask[1:-1, 1:-1] & mask[:-2, 1:-1] & mask[2:, 1:-1] & mask[1:-1, :-2] & mask[1:-1, 2:]
)
inner[0, :] = inner[-1, :] = inner[:, 0] = inner[:, -1] = False
ys, xs = np.nonzero(mask & ~inner)
corners = np.concatenate(
[np.stack([xs + dx, ys + dy], axis=1) for dx in (-0.5, 0.5) for dy in (-0.5, 0.5)]
)
hull = _hull_area(corners)
return float(min(1.0, area / hull)) if hull > 0 else 0.0
# ------------------------------------------------------------ degradation
[docs]
def degradation_vector(
image_bgr: np.ndarray,
box: tuple[float, float, float, float],
mask: np.ndarray | None,
cfg: DegradationConfig,
) -> np.ndarray:
"""Omega_i = (darkness, blur, truncation), each in [0, 1].
* darkness: how far the region's mean luma is below ``reference_luma``;
* blur: how far its Laplacian variance is below ``reference_sharpness``;
* truncation: fraction of the region's border lying on the image border, a
proxy for objects cut off by the field of view or occluded.
"""
h, w = image_bgr.shape[:2]
x1, y1, x2, y2 = (round(v) for v in box)
x1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2)
if x2 - x1 < 2 or y2 - y1 < 2:
return np.ones(3)
crop = image_bgr[y1:y2, x1:x2].astype(np.float64) / 255.0
luma = crop @ np.array([0.114, 0.587, 0.299]) # BGR weights
region = mask[y1:y2, x1:x2] if mask is not None else None
values = luma[region] if region is not None and region.any() else luma.ravel()
darkness = max(0.0, 1.0 - float(values.mean()) / cfg.reference_luma)
lap = (
-4 * luma[1:-1, 1:-1] + luma[:-2, 1:-1] + luma[2:, 1:-1] + luma[1:-1, :-2] + luma[1:-1, 2:]
) * 255.0
sharpness = float(lap.var()) if lap.size else 0.0
blur = max(0.0, 1.0 - sharpness / cfg.reference_sharpness)
edges = [x1 <= 0, y1 <= 0, x2 >= w, y2 >= h]
side = [y2 - y1, x2 - x1, y2 - y1, x2 - x1]
truncation = sum(s for e, s in zip(edges, side, strict=True) if e) / (
2.0 * ((x2 - x1) + (y2 - y1))
)
return np.clip(np.array([darkness, blur, truncation]), 0.0, 1.0)
[docs]
def degradation_weight(omega: np.ndarray, beta: float) -> float:
"""Theta_i = exp(-beta * ||Omega_i||)."""
return float(math.exp(-beta * float(np.linalg.norm(omega))))
# -------------------------------------------------------------------- depth
def region_centroid(
box: tuple[float, float, float, float], mask: np.ndarray | None
) -> tuple[float, float]:
if mask is not None and mask.any():
ys, xs = np.nonzero(mask)
return float(xs.mean()), float(ys.mean())
x1, y1, x2, y2 = box
return (x1 + x2) / 2.0, (y1 + y2) / 2.0
[docs]
def region_depth(
depth_m: np.ndarray,
box: tuple[float, float, float, float],
mask: np.ndarray | None,
cfg: DepthConfig,
) -> float | None:
"""Median valid depth in a neighbourhood of the region centroid, restricted to the mask when
there is one; falls back to the whole region."""
h, w = depth_m.shape[:2]
u, v = region_centroid(box, mask)
r = cfg.window_px
ys = slice(max(0, int(v) - r), min(h, int(v) + r + 1))
xs = slice(max(0, int(u) - r), min(w, int(u) + r + 1))
def median(values: np.ndarray) -> float | None:
ok = values[np.isfinite(values) & (values >= cfg.min_m) & (values <= cfg.max_m)]
return float(np.median(ok)) if ok.size else None
window = depth_m[ys, xs]
if mask is not None:
z = median(window[mask[ys, xs]])
if z is None:
z = median(depth_m[mask])
else:
z = median(window)
if z is None:
x1, y1, x2, y2 = (round(c) for c in box)
z = median(depth_m[max(0, y1) : y2, max(0, x1) : x2])
return z