"""Perception data types and interfaces."""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
import numpy as np
@dataclass
class Proposal:
"""A candidate region from an open-vocabulary detector/segmenter."""
label: str # the text prompt that produced it
score: float
box: tuple[float, float, float, float] # x1, y1, x2, y2 in pixels
mask: np.ndarray | None = None # HxW bool
[docs]
@dataclass
class GroundedObject:
"""A region tied to a label, with evidence scores and (if known) 3-D position."""
label: str
score: float # final selection score (Eq. 9 numerator)
box: tuple[float, float, float, float] | None = None
mask: np.ndarray | None = None
position: np.ndarray | None = None # map frame (x, y, z), metres
radius_m: float | None = None # approximate footprint radius
range_m: float | None = None # from the robot base
bearing_rad: float | None = None # from the robot heading, counter-clockwise
source: str = "camera" # camera | memory | sim
age_s: float = 0.0
evidence: dict = field(default_factory=dict)
@dataclass
class Observation:
image: np.ndarray | None # BGR frame the objects were found in (None in sim)
objects: list[GroundedObject]
class Detector(ABC):
"""Open-vocabulary detector: image + text prompts -> proposals."""
@abstractmethod
def detect(self, image_bgr: np.ndarray, prompts: list[str]) -> list[Proposal]: ...
[docs]
class Grounder(ABC):
"""Visual grounding of language references, with a short-term scene memory."""
[docs]
@abstractmethod
def observe(self, queries: list[str] | None = None) -> Observation:
"""Detect ``queries`` (or the configured vocabulary) in the current view."""
[docs]
@abstractmethod
def locate(self, query: str) -> GroundedObject | None:
"""Best match for ``query`` in view, else from recent memory, else None."""
[docs]
@abstractmethod
def remembered(self, query: str | None = None) -> list[GroundedObject]:
"""Objects in scene memory (optionally only those matching ``query``)."""
[docs]
def frame(self) -> np.ndarray | None:
"""Latest camera frame (BGR), if there is a camera."""
return None
@staticmethod
def annotate(image_bgr: np.ndarray, objects: list[GroundedObject]) -> np.ndarray:
import cv2
out = image_bgr.copy()
for obj in objects:
if obj.mask is not None:
overlay = out.copy()
overlay[obj.mask] = (255, 160, 0)
out = cv2.addWeighted(overlay, 0.35, out, 0.65, 0)
for obj in objects:
if obj.box is None:
continue
x1, y1, x2, y2 = (int(v) for v in obj.box)
cv2.rectangle(out, (x1, y1), (x2, y2), (0, 200, 0), 2)
text = f"{obj.label} {obj.score:.2f}"
if obj.range_m is not None:
text += f" {obj.range_m:.1f}m"
cv2.putText(
out, text, (x1, max(y1 - 6, 12)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 200, 0), 2
)
return out
_ARTICLES = frozenset({"the", "a", "an"})
def tokens(phrase: str) -> set[str]:
"""Normalised content words of an English noun phrase (articles dropped, plurals singular)."""
out = set()
for tok in phrase.casefold().replace("-", " ").replace("_", " ").split():
if tok in _ARTICLES:
continue
if tok.endswith("ies") and len(tok) > 4:
tok = tok[:-3] + "y"
elif tok.endswith("s") and not tok.endswith("ss") and len(tok) > 3:
tok = tok[:-1]
out.add(tok)
return out
def label_match(query: str, label: str) -> float:
"""Token-overlap (Jaccard) similarity in [0, 1] between two English noun phrases."""
q, t = tokens(query), tokens(label)
if not q or not t:
return 0.0
return len(q & t) / len(q | t)