Lumi robot software on the Jetson Thor

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 15:19:07 +09:00
co-authored by Claude Opus 5.5
commit 96b01fa12e
177 changed files with 39901 additions and 0 deletions
View File
+319
View File
@@ -0,0 +1,319 @@
"""Torso camera -> arm base calibration with the ArUco marker on the gripper (eye-to-hand).
The marker (DICT_4X4_50, id 0, 50 mm black square) is stuck on the gripper body, so it moves rigidly with the
flange. For each sample we store where the arm controller says the flange is (base frame) and where the camera
sees the marker (camera frame). Two unknown fixed transforms link them: camera in the arm base frame and marker
on the flange; solve() finds both (Park & Martin's AX = XB).
python vision/calib.py collect # move the arm by hand (Cobo π); every still pose with the marker in view
# is saved and Lumi says "Saved, N". Ctrl+C or MAX_SAMPLES to stop.
python vision/calib.py solve # compute camera_extrinsics.json, print the error of every sample
python vision/calib.py check # live: marker position from the camera vs from the arm, in mm
python vision/calib.py clear # forget the samples
add --camera head to any of these for the head camera (own samples and result file)
Keep the lift and the waist where they are during a session: the camera turns with the waist and moves with
the lift, the arm base too, but samples from different body poses must not be mixed until that is verified.
"""
import json
import math
import sys
import time
from pathlib import Path
import cv2
import numpy as np
from robot import arm, head
from vision import camview
ROOT = Path(__file__).resolve().parents[1] # the project folder
SAMPLES_DIR = ROOT / "data" / "calib_samples"
RESULT = ROOT / "data" / "camera_extrinsics.json"
CAMERA = "torso" # --camera head switches the three names above and this one
MARKER_ID = 0
MARKER_MM = 50.0 # black square side, checked with a ruler on the print
STILL_S = 1.5 # s the joints must not move before a sample is taken
STILL_DEG = 0.05 # max joint change while "still"
MIN_MOVE_MM, MIN_TURN_DEG = 30.0, 8.0 # a new sample must differ this much from every saved one
MAX_SAMPLES = 30
OUTLIER_FACTOR, OUTLIER_MIN_MM = 3.0, 8.0 # samples off by more than this x the median (and 8 mm) are left out
POLL_S = 0.2
DICT = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50)
DETECTOR = cv2.aruco.ArucoDetector(DICT, cv2.aruco.DetectorParameters())
H = MARKER_MM / 2
MARKER_POINTS = np.array([[-H, H, 0], [H, H, 0], [H, -H, 0], [-H, -H, 0]], np.float64) # ArUco corner order
# ---------- poses ----------
EULER = ("Rz Ry Rx", "Rx Ry Rz") # candidate orders of the controller's (rx, ry, rz); solve() keeps the better one
def rpy_matrix(rx, ry, rz, order=EULER[0]):
"""Rotation of the controller's (rx, ry, rz) in degrees. "Rz Ry Rx" = fixed X, then Y, then Z (roll-pitch-yaw)."""
a, b, c = np.radians([rx, ry, rz])
R = {"Rx": np.array([[1, 0, 0], [0, math.cos(a), -math.sin(a)], [0, math.sin(a), math.cos(a)]]),
"Ry": np.array([[math.cos(b), 0, math.sin(b)], [0, 1, 0], [-math.sin(b), 0, math.cos(b)]]),
"Rz": np.array([[math.cos(c), -math.sin(c), 0], [math.sin(c), math.cos(c), 0], [0, 0, 1]])}
first, second, third = (R[k] for k in order.split())
return first @ second @ third
def matrix(R, t):
T = np.eye(4)
T[:3, :3], T[:3, 3] = R, np.ravel(t)
return T
def flange_pose(position, order=EULER[0]):
"""4x4 flange pose in the arm base frame (mm) from get_data's actual_position (tool 0 = flange)."""
x, y, z, rx, ry, rz = position
return matrix(rpy_matrix(rx, ry, rz, order), [x, y, z])
def angle_between(R1, R2):
return math.degrees(math.acos(np.clip((np.trace(R1.T @ R2) - 1) / 2, -1, 1)))
# ---------- camera ----------
def camera_model():
intr = camview.intrinsics(CAMERA)
if intr is None:
sys.exit(f"no intrinsics for the {CAMERA} camera: is the camera service running (camview.py --serve)?")
K = np.array([[intr["fx"], 0, intr["cx"]], [0, intr["fy"], intr["cy"]], [0, 0, 1]])
return K, np.array(intr["dist"], np.float64), (intr["width"], intr["height"])
def latest_image():
camview.want(CAMERA) # keep the service at full speed
data = camview.raw_path(CAMERA).read_bytes()
return cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_COLOR)
def find_marker(img, K, dist):
"""(4x4 marker pose in the camera frame (mm), corners) or (None, None)."""
corners, ids, _ = DETECTOR.detectMarkers(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))
if ids is None or MARKER_ID not in ids.ravel():
return None, None
c = corners[list(ids.ravel()).index(MARKER_ID)][0].astype(np.float64)
ok, rvec, tvec = cv2.solvePnP(MARKER_POINTS, c, K, dist, flags=cv2.SOLVEPNP_IPPE_SQUARE)
if not ok:
return None, None
return matrix(cv2.Rodrigues(rvec)[0], tvec), c
# ---------- collect ----------
def say(text):
print(text, flush=True)
try:
from audio import mouth
mouth.say(text)
except Exception as e:
print(f" (cannot speak: {e})", flush=True)
def load_samples():
return [json.loads(p.read_text()) for p in sorted(SAMPLES_DIR.glob("sample_*.json"))]
def collect():
K, dist, size = camera_model()
SAMPLES_DIR.mkdir(exist_ok=True)
samples = load_samples()
print(f"camera {CAMERA} {size[0]}x{size[1]}, {len(samples)} samples so far; move the arm, hold it still")
joints, still_since, warned = None, time.time(), False
try:
while len(samples) < MAX_SAMPLES:
time.sleep(POLL_S)
try:
d = arm.cmd("get_data")
q = np.array(d["joint_actual_position"])
except (KeyError, OSError, ValueError) as e: # now and then a reply without the arm state
print(f" (arm state unavailable: {e})", flush=True)
continue
if joints is None or np.max(np.abs(q - joints)) > STILL_DEG:
joints, still_since, warned = q, time.time(), False
continue
if time.time() - still_since < STILL_S:
continue
T_base_flange = flange_pose(d["actual_position"])
near = [s for s in samples if
np.linalg.norm(np.array(s["flange"])[:3, 3] - T_base_flange[:3, 3]) < MIN_MOVE_MM and
angle_between(np.array(s["flange"])[:3, :3], T_base_flange[:3, :3]) < MIN_TURN_DEG]
if near:
continue # same pose as a saved sample: wait for a new one
img = latest_image()
T_cam_marker, corners = find_marker(img, K, dist)
if T_cam_marker is None:
if not warned:
say("I can't see the marker.")
warned = True
continue
n = len(samples) + 1
sample = {"position": d["actual_position"], "flange": T_base_flange.tolist(), "marker": T_cam_marker.tolist(), "corners": corners.tolist(),
"joints": q.tolist(), "body": head.status(), "time": time.time()}
(SAMPLES_DIR / f"sample_{n:02d}.json").write_text(json.dumps(sample))
cv2.imwrite(str(SAMPLES_DIR / f"sample_{n:02d}.jpg"), img)
samples.append(sample)
print(f" #{n}: flange {T_base_flange[:3, 3].round(0)} mm, marker {T_cam_marker[2, 3]:.0f} mm "
f"from the camera", flush=True)
say(f"Saved, {n}.")
except KeyboardInterrupt:
pass
print(f"{len(samples)} samples in {SAMPLES_DIR}")
# ---------- solve ----------
def rotation_log(R):
"""Axis * angle (rad) of a rotation matrix."""
return cv2.Rodrigues(R)[0].ravel()
def mean_rotation(Rs):
U, _, Vt = np.linalg.svd(sum(Rs))
D = np.diag([1, 1, np.sign(np.linalg.det(U @ Vt))])
return U @ D @ Vt
def solve_ax_xb(As, Bs):
"""X with A X = X B for pairs of relative motions (Park & Martin 1994): rotation from the rotation axes,
then translation by least squares."""
alphas = np.array([rotation_log(A[:3, :3]) for A in As])
betas = np.array([rotation_log(B[:3, :3]) for B in Bs])
M = betas.T @ alphas # sum of beta alpha^T
w, V = np.linalg.eigh(M.T @ M)
R = V @ np.diag(1 / np.sqrt(w)) @ V.T @ M.T # (M^T M)^-1/2 M^T
C = np.vstack([A[:3, :3] - np.eye(3) for A in As])
d = np.concatenate([R @ B[:3, 3] - A[:3, 3] for A, B in zip(As, Bs)])
t = np.linalg.lstsq(C, d, rcond=None)[0]
return matrix(R, t)
def refine(flange, marker, T_base_cam, T_flange_marker, iterations=50):
"""Levenberg-Marquardt on the marker centre: camera pose (6) and marker offset on the flange (3) that make
the camera's and the arm's marker positions agree best. AX = XB weighs rotations, this weighs millimetres."""
def unpack(p):
return matrix(cv2.Rodrigues(p[:3])[0], p[3:6]), p[6:9]
def residuals(p):
X, offset = unpack(p)
return np.concatenate([(X @ M)[:3, 3] - (F[:3, :3] @ offset + F[:3, 3]) for F, M in zip(flange, marker)])
p = np.concatenate([rotation_log(T_base_cam[:3, :3]), T_base_cam[:3, 3], T_flange_marker[:3, 3]])
lam = 1e-3
r = residuals(p)
for _ in range(iterations):
J = np.empty((r.size, p.size))
for k in range(p.size): # numeric Jacobian: radians and millimetres
dp = np.zeros(p.size)
dp[k] = 1e-6 if k < 3 else 1e-3
J[:, k] = (residuals(p + dp) - r) / dp[k]
step = np.linalg.solve(J.T @ J + lam * np.diag(np.diag(J.T @ J)), -J.T @ r)
r_new = residuals(p + step)
if r_new @ r_new < r @ r:
p, r, lam = p + step, r_new, lam / 3
if np.linalg.norm(step) < 1e-6:
break
else:
lam *= 5
X, offset = unpack(p)
return X, matrix(T_flange_marker[:3, :3], offset)
def solve(samples, order=EULER[0]):
"""Camera pose in the arm base frame and marker pose on the flange, with the error of each sample.
Each sample i gives F_i Y = X M_i (F flange in base, Y marker on flange, X camera in base, M marker in
camera). For two samples: (F_j^-1 F_i) Y = Y (M_j^-1 M_i), an AX = XB problem for Y; X follows."""
flange = [flange_pose(s["position"], order) for s in samples]
marker = [np.array(s["marker"]) for s in samples]
As, Bs = [], []
for i in range(len(samples)):
for j in range(i + 1, len(samples)):
A = np.linalg.inv(flange[j]) @ flange[i]
if np.degrees(np.linalg.norm(rotation_log(A[:3, :3]))) > 5: # small turns carry no axis information
As.append(A)
Bs.append(np.linalg.inv(marker[j]) @ marker[i])
if len(As) < 3:
sys.exit("the samples hardly differ in orientation: tilt the marker differently between samples")
T_flange_marker = solve_ax_xb(As, Bs)
Xs = [F @ T_flange_marker @ np.linalg.inv(M) for F, M in zip(flange, marker)]
T_base_cam = matrix(mean_rotation([X[:3, :3] for X in Xs]), np.mean([X[:3, 3] for X in Xs], axis=0))
T_base_cam, T_flange_marker = refine(flange, marker, T_base_cam, T_flange_marker)
errors = []
for F, M in zip(flange, marker):
seen = (T_base_cam @ M)[:3, 3] # marker centre in the base frame, from the camera
expected = (F @ T_flange_marker)[:3, 3] # ... from the arm
errors.append(float(np.linalg.norm(seen - expected)))
return T_base_cam, T_flange_marker, errors
def run_solve():
samples = load_samples()
if len(samples) < 6:
sys.exit(f"only {len(samples)} samples: collect at least 6 (better 12-15) with different tilts")
results = {order: solve(samples, order) for order in EULER}
order = min(results, key=lambda o: np.median(results[o][2]))
for o, r in results.items():
print(f" angles as {o}: median error {np.median(r[2]):.1f} mm")
T_base_cam, T_flange_marker, errors = results[order]
limit = max(OUTLIER_FACTOR * float(np.median(errors)), OUTLIER_MIN_MM)
bad = [i for i, e in enumerate(errors) if e > limit]
if bad and len(samples) - len(bad) >= 6: # an arm still moving, a blurred or steep marker
print(f" left out (error > {limit:.1f} mm): samples {[i + 1 for i in bad]}")
samples = [s for i, s in enumerate(samples) if i not in bad]
T_base_cam, T_flange_marker, errors = solve(samples, order)
for i, e in enumerate(errors, 1):
print(f" sample {i:2d}: {e:5.1f} mm")
print(f"error: median {np.median(errors):.1f} mm, max {max(errors):.1f} mm")
print(f"camera in the arm base frame: {T_base_cam[:3, 3].round(1)} mm")
print(f"marker on the flange: {T_flange_marker[:3, 3].round(1)} mm")
RESULT.write_text(json.dumps({
"camera": CAMERA, "euler": order, "T_base_cam": T_base_cam.tolist(), "T_flange_marker": T_flange_marker.tolist(),
"samples": len(samples), "median_error_mm": round(float(np.median(errors)), 1),
"max_error_mm": round(max(errors), 1), "body": samples[0].get("body"), # [lift, waist, head yaw, pitch]
"time": time.strftime("%Y-%m-%d %H:%M")}, indent=1))
print(f"saved {RESULT.name}")
def check():
K, dist, _ = camera_model()
res = json.loads(RESULT.read_text())
T_base_cam, T_flange_marker = np.array(res["T_base_cam"]), np.array(res["T_flange_marker"])
order = res["euler"]
print("marker seen by the camera vs where the arm puts it (Ctrl+C to stop)")
try:
while True:
T_cam_marker, _ = find_marker(latest_image(), K, dist)
expected = (flange_pose(arm.cmd("get_data")["actual_position"], order) @ T_flange_marker)[:3, 3]
if T_cam_marker is None:
print(" marker not in view", flush=True)
else:
seen = (T_base_cam @ T_cam_marker)[:3, 3]
print(f" camera {seen.round(0)} arm {expected.round(0)} difference "
f"{np.linalg.norm(seen - expected):.1f} mm", flush=True)
time.sleep(0.5)
except KeyboardInterrupt:
pass
if __name__ == "__main__":
if "--camera" in sys.argv:
CAMERA = sys.argv[sys.argv.index("--camera") + 1]
if CAMERA != "torso": # the torso keeps the original file names
SAMPLES_DIR = ROOT / "data" / f"calib_samples_{CAMERA}"
RESULT = ROOT / "data" / f"camera_extrinsics_{CAMERA}.json"
what = sys.argv[1] if len(sys.argv) > 1 else ""
if what == "collect":
collect()
elif what == "solve":
run_solve()
elif what == "check":
check()
elif what == "clear":
for p in SAMPLES_DIR.glob("sample_*"):
p.unlink()
print("samples removed")
else:
print(__doc__)
+57
View File
@@ -0,0 +1,57 @@
"""Camera stability test on the Thor: stream colour + depth from one camera and count full frames.
python vision/camera_fps.py head # head camera, 30 s, the modes person.py / lumi.py use
python vision/camera_fps.py torso 60 # torso camera, 60 s
python vision/camera_fps.py head --default # the camera's own default modes (the old, broken USB 2 case)
The camera is chosen by name (head / torso), serial number or index, like person.py.
A healthy camera gives the asked fps (15 in person.py's modes) with almost no missed frames.
Ctrl+C stops early and prints the result so far.
"""
import sys
import time
from pyorbbecsdk import Config, OBSensorType
from vision import person
from vision import camview
if camview.service_pid():
sys.exit("The camera service (camview.py) has the cameras. Stop it first: python vision/camview.py --stop (and --start afterwards) "
"(api/server.py / lumi.py start it again when needed).")
args = [a for a in sys.argv[1:] if not a.startswith("--")]
camera = args[0] if args else "head"
seconds = float(args[1]) if len(args) > 1 else 30
default = "--default" in sys.argv
pipeline, serial, name = person.open_camera(camera)
config = Config()
for sensor, mode in ((OBSensorType.COLOR_SENSOR, person.COLOR_MODE), (OBSensorType.DEPTH_SENSOR, person.DEPTH_MODE)):
profiles = pipeline.get_stream_profile_list(sensor)
p = profiles.get_default_video_stream_profile() if default else person._profile(pipeline, sensor, mode)
config.enable_stream(p)
print(f" {sensor}: {p.get_width()}x{p.get_height()} {str(p.get_format()).split('.')[-1]} @ {p.get_fps()} fps")
print(f"{name} camera SN {serial}, {seconds:.0f} s" + (" (default modes)" if default else ""))
pipeline.start(config)
full = missed = 0
start = last = time.time()
try:
while time.time() - start < seconds:
frames = pipeline.wait_for_frames(1000)
if frames is None or frames.get_color_frame() is None or frames.get_depth_frame() is None:
missed += 1
else:
full += 1
if time.time() - last >= 5: # progress every 5 s
last = time.time()
print(f" {last - start:4.0f} s: {full / (last - start):5.1f} fps, missed {missed}")
except KeyboardInterrupt: # Ctrl+C: stop early and still print the result
pass
finally:
pipeline.stop()
elapsed = time.time() - start
print(f"{name} camera: {full / elapsed:.1f} fps, {missed} missed in {elapsed:.0f} s")
+66
View File
@@ -0,0 +1,66 @@
"""Camera test on the Thor: list the Orbbec cameras, grab colour + depth from one, save a picture.
python vision/camera_test.py # camera 0
python vision/camera_test.py 1 # camera 1
Prints each camera's serial number and the distance (mm) at the image centre,
and saves color_<id>.jpg next to this file. Cover a camera with your hand to see which is head / torso.
"""
import pathlib
import sys
import cv2
import numpy as np
from pyorbbecsdk import Config, Context, OBLogLevel, OBSensorType, Pipeline
from vision import camview
if camview.service_pid():
sys.exit("The camera service (camview.py) has the cameras. Stop it first: python vision/camview.py --stop (and --start afterwards) "
"(api/server.py / lumi.py start it again when needed).")
cam_id = int(sys.argv[1]) if len(sys.argv) > 1 else 0
ctx = Context() # keep the context alive while devices are used
ctx.set_logger_level(OBLogLevel.NONE) # hide SDK noise such as "Timestamp anomaly"
devices = ctx.query_devices()
print(f"{devices.get_count()} camera(s):")
for i in range(devices.get_count()):
print(f" [{i}] {devices.get_device_name_by_index(i)} SN {devices.get_device_serial_number_by_index(i)}")
pipeline = Pipeline(devices.get_device_by_index(cam_id))
config = Config()
for sensor in (OBSensorType.COLOR_SENSOR, OBSensorType.DEPTH_SENSOR):
config.enable_stream(pipeline.get_stream_profile_list(sensor).get_default_video_stream_profile())
pipeline.start(config)
color = depth_mm = None
for n in range(90): # skip ~30 frames so auto exposure settles
frames = pipeline.wait_for_frames(100)
if frames is None:
continue
c, d = frames.get_color_frame(), frames.get_depth_frame()
if c is not None:
data = np.asanyarray(c.get_data())
if str(c.get_format()).endswith("MJPG"):
color = cv2.imdecode(data, cv2.IMREAD_COLOR)
else: # RGB
color = cv2.cvtColor(data.reshape(c.get_height(), c.get_width(), 3), cv2.COLOR_RGB2BGR)
if d is not None and len(d.get_data()) == d.get_width() * d.get_height() * 2: # skip broken frames
raw = np.frombuffer(d.get_data(), dtype=np.uint16).reshape(d.get_height(), d.get_width())
depth_mm = raw.astype(np.float32) * d.get_depth_scale()
if n >= 30 and color is not None and depth_mm is not None:
break
pipeline.stop()
if color is None or depth_mm is None:
sys.exit("No frames. Is another program (e.g. lumi-vision-api) using the camera?")
h, w = depth_mm.shape
centre = depth_mm[h // 2 - 20:h // 2 + 20, w // 2 - 20:w // 2 + 20]
valid = centre[centre > 0]
print(f"colour {color.shape[1]}x{color.shape[0]}, depth {w}x{h}")
print(f"distance at centre: {np.median(valid):.0f} mm" if valid.size else "distance at centre: no depth")
out = pathlib.Path(__file__).resolve().parents[1] / "logs" / f"color_{cam_id}.jpg"
cv2.imwrite(str(out), color)
print(f"saved {out}")
+417
View File
@@ -0,0 +1,417 @@
"""Camera service: the ONLY program that opens the Orbbec cameras; everyone else reads its results.
Two programs opening Orbbec cameras at the same time make the SDK reset the devices: the head camera then
disconnects every ~2.5 s (seen 2026-10-12). So one service owns both cameras:
python vision/camview.py --serve # started by api/server.py at boot (and by lumi.py if it is not running)
python vision/camview.py --stop # free the cameras, e.g. for camera_fps.py / camera_test.py; it stays off
# (nothing restarts it) until `python vision/camview.py --serve` or --start
For each camera it runs person detection (person.py) and writes to /dev/shm:
- lumi_cam_<name>.jpg / .json picture with boxes (PUBLISH_HZ) + people, for the dashboard (api/server.py /view)
- lumi_det_<name>.json every detection frame: people with boxes, frame size, head yaw (RemoteDetector);
for the torso also objects (cups, bottles...) measured by objects.py
- lumi_raw_<name>.jpg the camera's own full-size JPEG of every frame (live video, calib.py)
- lumi_intr_<name>.json colour intrinsics of the running mode (calib.py, objects)
Programs that need people (lumi.py, api/server.py) use RemoteDetector, which has the same read() as
person.PersonDetector. They tell the service whom to draw red (focus) through lumi_focus_<name>.json.
Nobody reading for IDLE_S (no viewer, no lumi.py): detection drops to 1 frame a second.
"""
import io
import json
import os
import signal
import subprocess
import sys
import threading
import time
from pathlib import Path
import cv2
import numpy as np
ROOT = Path(__file__).resolve().parents[1] # the project folder
VENV_PY = ROOT / ".venv" / "bin" / "python"
SHM = Path("/dev/shm")
PID_FILE = SHM / "lumi_camd.pid"
STATUS_FILE = SHM / "lumi_camd.json"
OFF_FILE = SHM / "lumi_camd.off" # written by --stop: do not restart the service automatically
SETTINGS = SHM / "lumi_view_settings.json"
CAMERAS = ("head", "torso")
PUBLISH_HZ = 5.0
VIEW_WIDTH = 640 # px, pictures are scaled down to this width
FRESH_S = 1.5 # s; a newer picture counts as live
IDLE_S = 30.0 # s without any reader -> slow detection (1 per second)
DEFAULTS = {"box_color": "#22c55e", "thickness": 2, "boxes": True, "labels": True}
FOCUS_COLOR = (68, 68, 239) # BGR red: the person Lumi talks to
DEPTH_MIN_MBPS = 5000 # head depth only at USB 3 speed: at USB 2, depth + the speaker playing (same hub) = disconnects
FOCUS_FRESH_S = 3.0 # s; an older focus file (lumi.py gone) is ignored
DEPTH_EVERY_S = 0.5 # s between torso depth frames written for the skills (is the table there?)
MATCH_DEG = 8.0 # a torso-camera person within this angle gives the head person's distance
_last = {}
_settings = {"time": 0.0, "value": dict(DEFAULTS)}
def frame_path(name):
return SHM / f"lumi_cam_{name}.jpg"
def info_path(name):
return SHM / f"lumi_cam_{name}.json"
def raw_path(name):
"""The camera's own JPEG of the newest frame (no boxes): the dashboard's live video."""
return SHM / f"lumi_raw_{name}.jpg"
def intrinsics_path(name):
"""Colour camera matrix and distortion of the running mode, written when the camera opens."""
return SHM / f"lumi_intr_{name}.json"
def intrinsics(name):
"""{width, height, fx, fy, cx, cy, dist} of a camera opened by the service, or None."""
try:
return json.loads(intrinsics_path(name).read_text())
except (FileNotFoundError, ValueError):
return None
def usb_mbps(serial):
"""Link speed (Mb/s) of the USB device with this serial number, 0 if not found (Linux sysfs)."""
for d in Path("/sys/bus/usb/devices").glob("*"):
try:
if (d / "serial").read_text().strip() == serial:
return int((d / "speed").read_text())
except (OSError, ValueError):
continue
return 0
def det_path(name):
return SHM / f"lumi_det_{name}.json"
def depth_path(name):
"""Depth (mm, uint16, aligned to the full-size colour frame) of a recent frame, .npy; torso only."""
return SHM / f"lumi_depth_{name}.npy"
def depth(name, max_age=FRESH_S):
"""The newest depth frame written by the service, or None when there is none this fresh."""
try:
if time.time() - depth_path(name).stat().st_mtime > max_age:
return None
return np.load(depth_path(name))
except (FileNotFoundError, ValueError, OSError):
return None
def focus_path(name):
return SHM / f"lumi_focus_{name}.json"
def want_path(name):
return SHM / f"lumi_cam_{name}.want"
def _write(path, data):
tmp = path.with_suffix(path.suffix + f".{os.getpid()}.tmp")
tmp.write_bytes(data)
os.replace(tmp, path) # atomic: a reader never sees half a file
def want(name):
"""A reader (dashboard, lumi.py) is interested in this camera: keep full speed."""
try:
want_path(name).touch()
except OSError:
pass
# ---------- drawing settings (dashboard) ----------
def settings():
now = time.time()
if now - _settings["time"] > 1.0:
_settings["time"] = now
try:
_settings["value"] = {**DEFAULTS, **json.loads(SETTINGS.read_text())}
except (FileNotFoundError, ValueError):
_settings["value"] = dict(DEFAULTS)
return _settings["value"]
def save_settings(new):
_settings["time"] = 0.0
value = {**settings(), **{k: v for k, v in new.items() if k in DEFAULTS and v is not None}}
_write(SETTINGS, json.dumps(value).encode())
_settings["time"] = 0.0
return value
def _bgr(hex_color):
h = hex_color.lstrip("#")
try:
r, g, b = (int(h[i:i + 2], 16) for i in (0, 2, 4))
except ValueError:
r, g, b = 34, 197, 94
return b, g, r
def publish(name, color, people=(), source="camview.py"):
"""Picture with person boxes for the dashboard (called by PersonDetector.read for every frame)."""
now = time.time()
if now - _last.get(name, 0) < 1 / PUBLISH_HZ:
return
_last[name] = now
s = settings()
scale = VIEW_WIDTH / color.shape[1]
img = cv2.resize(color, (VIEW_WIDTH, int(color.shape[0] * scale)))
box_color, thick = _bgr(s["box_color"]), max(1, min(6, int(s["thickness"])))
for p in people:
x1, y1, x2, y2 = (int(v * scale) for v in p["box"])
col = FOCUS_COLOR if p.get("focus") or p.get("near") else box_color
if s["boxes"]:
cv2.rectangle(img, (x1, y1), (x2, y2), col, thick + (1 if col == FOCUS_COLOR else 0))
if s["labels"]:
text = ("TALKING " if p.get("focus") else "") + f"{p['distance_m']} m {p['angle_deg']:+.0f} deg"
(tw, th), _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
ty = max(th + 6, y1)
cv2.rectangle(img, (x1, ty - th - 6), (x1 + tw + 6, ty), col, -1)
cv2.putText(img, text, (x1 + 3, ty - 4), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (20, 20, 20), 1, cv2.LINE_AA)
ok, jpg = cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 75])
if not ok:
return
_write(frame_path(name), jpg.tobytes())
_write(info_path(name), json.dumps({"time": now, "source": source, "people": [
{**{k: p[k] for k in ("distance_m", "angle_deg", "score")}, "focus": bool(p.get("focus")),
"near": bool(p.get("near"))}
for p in people]}).encode())
def picture_age(name):
try:
return time.time() - frame_path(name).stat().st_mtime
except FileNotFoundError:
return None
def status():
try:
return json.loads(STATUS_FILE.read_text())
except (FileNotFoundError, ValueError):
return {}
# ---------- the service ----------
def service_pid():
try:
pid = int(PID_FILE.read_text())
os.kill(pid, 0)
if "camview.py" in Path(f"/proc/{pid}/cmdline").read_bytes().decode(errors="replace"):
return pid
except (FileNotFoundError, ValueError, ProcessLookupError, PermissionError):
pass
return None
_start_lock = threading.Lock()
def ensure_running():
"""Start the camera service if it is not running (safe to call often)."""
with _start_lock:
if service_pid() or OFF_FILE.exists():
return
subprocess.Popen([str(VENV_PY), str(ROOT / "vision" / "camview.py"), "--serve"], cwd=ROOT, stdin=subprocess.DEVNULL,
stdout=open(ROOT / "logs" / "camview.log", "a"), stderr=subprocess.STDOUT, start_new_session=True)
for _ in range(30): # wait until it has written its pid
time.sleep(0.1)
if service_pid():
return
def stop_service():
OFF_FILE.touch()
pid = service_pid()
if pid:
try:
os.kill(pid, signal.SIGTERM)
time.sleep(1.5)
if service_pid():
os.kill(pid, signal.SIGKILL)
except ProcessLookupError:
pass
return pid
def _serve():
OFF_FILE.unlink(missing_ok=True)
if service_pid():
sys.exit("camera service already running")
PID_FILE.write_text(str(os.getpid()))
signal.signal(signal.SIGTERM, lambda *_: os._exit(0)) # exit at once: pipeline.stop() can hang
cv2.setNumThreads(8) # two YOLOs share these (the Thor has 14 cores)
from vision.person import PersonDetector, CAMERAS as SERIALS
from vision import head_cam, objects
state = {name: "starting" for name in CAMERAS}
def write_status():
_write(STATUS_FILE, json.dumps({"pid": os.getpid(), "cameras": state, "time": time.time()}).encode())
latest = {} # name -> (time, people): the torso's depth helps the head
def write_raw(name, jpeg):
_write(raw_path(name), jpeg)
def torso_distance(angle):
"""Distance of the torso camera's person at about this angle (both angles are waist-frame)."""
t, people = latest.get("torso", (0, []))
if time.time() - t > 0.5:
return None
near = [p for p in people if p["distance_m"] and abs(p["angle_deg"] - angle) < MATCH_DEG]
return min(near, key=lambda p: abs(p["angle_deg"] - angle))["distance_m"] if near else None
def run(name):
det = None
last_focus_read, focus_mtime, last_depth = 0.0, None, 0.0
while True:
if det is None:
try:
depth = name != "head" or usb_mbps(SERIALS[name]) >= DEPTH_MIN_MBPS
det = PersonDetector(name, head_sign=1.0, depth=depth)
det.on_raw = write_raw # every camera frame, for the live video
if not depth: # head at USB 2: colour only, distance from the torso
print(f"{name} camera at USB 2 speed: colour only", flush=True)
det.distance_hint = torso_distance
try:
_write(intrinsics_path(name), json.dumps(det.intrinsics()).encode())
except Exception as e:
print(f"{name}: no intrinsics: {e}", flush=True)
state[name] = "ok"
except Exception as e:
state[name] = f"cannot open: {e}"
write_status()
time.sleep(5)
continue
write_status()
now = time.time()
if now - last_focus_read > 0.2: # whom lumi.py talks to (drawn red)
last_focus_read = now
try:
st = focus_path(name).stat()
if now - st.st_mtime > FOCUS_FRESH_S: # lumi.py stopped (or crashed): nobody to draw red
det.focus_angle = None
elif st.st_mtime != focus_mtime:
focus_mtime = st.st_mtime
det.focus_angle = json.loads(focus_path(name).read_text()).get("angle")
except (FileNotFoundError, ValueError):
det.focus_angle = None
try:
color, people = det.read()
except Exception as e:
state[name] = f"error: {e}"
write_status()
time.sleep(1)
continue
if color is not None:
latest[name] = (time.time(), people)
found = []
if det.objects:
try:
if name == "torso":
found = objects.measure_all(color, det.depth, det.objects)
elif det.head_pose is not None: # the head camera's pose follows the head
T = head_cam.base_from_head(*det.head_pose[2:])
if T is not None:
found = objects.measure_all(color, det.depth, det.objects, intrinsics(name), T)
except Exception as e:
print(f"objects: {e}", flush=True)
_write(det_path(name), json.dumps({
"time": time.time(), "serial": det.serial, "height": color.shape[0], "width": color.shape[1],
"head_yaw": det.head_yaw, "head_pose": det.head_pose, "bad_jpeg": det.bad_jpeg, "reopens": det.reopens, "reboots": det.reboots,
"people": people, "objects": found}).encode())
if det.depth is not None and time.time() - last_depth >= DEPTH_EVERY_S:
buf = io.BytesIO()
np.save(buf, det.depth.astype(np.uint16))
_write(depth_path(name), buf.getvalue())
last_depth = time.time()
try:
idle = time.time() - want_path(name).stat().st_mtime > IDLE_S
except FileNotFoundError:
idle = True
if idle:
time.sleep(1.0)
for name in CAMERAS:
threading.Thread(target=run, args=(name,), daemon=True).start()
time.sleep(2.0) # open the cameras one after the other
while True:
time.sleep(5)
write_status()
class RemoteDetector:
"""Reads the camera service's detections; same use as person.PersonDetector (read(), name, head_yaw...)."""
def __init__(self, camera="head", head_sign=1.0):
if camera not in CAMERAS:
raise ValueError(f"camera must be one of {CAMERAS} (the camera service owns them)")
self.name, self.head_sign = camera, head_sign
self.serial, self.head_yaw, self.bad_jpeg, self.reopens = "?", 0.0, 0, 0
self._last_time, self._last_want = 0.0, 0.0
self._focus, self._focus_written = None, 0.0
ensure_running()
@property
def focus_angle(self):
return self._focus
@focus_angle.setter
def focus_angle(self, angle):
angle = None if angle is None else round(float(angle), 1)
if angle != self._focus or time.time() - self._focus_written > 1.0: # heartbeat: see FOCUS_FRESH_S
self._focus, self._focus_written = angle, time.time()
for name in CAMERAS: # waist-frame angle: the same person in both cameras
_write(focus_path(name), json.dumps({"angle": angle}).encode())
def read(self, timeout=0.3):
"""(frame stand-in with .shape, people) for a new detection frame, or (None, []) if none came."""
now = time.time()
if now - self._last_want > 1.0:
self._last_want = now
want(self.name)
if not service_pid():
ensure_running()
end = now + timeout
while time.time() < end:
try:
if det_path(self.name).stat().st_mtime > self._last_time:
d = json.loads(det_path(self.name).read_text())
if d["time"] > self._last_time:
self._last_time = d["time"]
self.serial, self.head_yaw = d["serial"], d["head_yaw"]
self.bad_jpeg, self.reopens = d["bad_jpeg"], d["reopens"]
return np.empty((d["height"], 0), np.uint8), d["people"]
except (FileNotFoundError, ValueError, KeyError):
pass
time.sleep(0.01)
return None, []
def close(self):
self.focus_angle = None
if __name__ == "__main__":
if "--serve" in sys.argv:
_serve()
elif "--stop" in sys.argv:
print(("stopped" if stop_service() else "not running") + "; it stays off until: python vision/camview.py --start")
elif "--start" in sys.argv:
OFF_FILE.unlink(missing_ok=True)
ensure_running()
print({"pid": service_pid()})
else:
print({"pid": service_pid(), **status()})
+217
View File
@@ -0,0 +1,217 @@
"""Head camera -> arm base transform at any head yaw / pitch.
calib.py --camera head gives the camera pose at one head pose (yaw 0, pitch -5, saved as "body" in
camera_extrinsics_head.json). The head turns about a vertical yaw axis and a horizontal pitch axis; both are measured
here in the arm base frame: the arm holds the gripper marker still, the head moves through small steps, and the
marker poses the camera sees give each axis. The lift and the waist carry the arm and the head together, so they
do not change the transform.
python vision/head_cam.py measure yaw # arm still with the marker in view; the head turns -30..0 deg
python vision/head_cam.py measure pitch # marker in the upper part of the view; the head tilts -5..+4 deg
python vision/head_cam.py fit # axes from both measurements -> camera_extrinsics_head.json
python vision/head_cam.py check # live: marker from the head camera vs from the arm, at the head pose now
Measured 2026-10-19: yaw -30..0 deg and pitch -5..+4 deg, the model within 11 mm / 1.4 deg of every pose seen.
Larger turns (yaw > 0, pitch > 4) are extrapolated.
"""
import json
import sys
import time
from pathlib import Path
import cv2
import numpy as np
from robot import arm, head
ROOT = Path(__file__).resolve().parents[1] # the project folder
RESULT = ROOT / "data" / "camera_extrinsics_head.json"
MEASURED = {"yaw": ROOT / "data" / "head_axes_yaw.json", "pitch": ROOT / "data" / "head_axes_pitch.json"}
STEPS = {"yaw": [(y, -5) for y in (0, -10, -20, -30, -10, 0)], # (yaw, pitch) deg; the marker must stay in view
"pitch": [(0, p) for p in (-5, -2, 1, 4, -5)] + [(-20, p) for p in (-5, -1, 3, -5)] + [(0, -5)]}
SETTLE_S = 1.5 # s after a head move before the frames are read
FRAMES = 6 # marker poses averaged per head pose
MIN_TURN_DEG = 2.0 # head poses closer than this to the reference give no axis direction
_cache = {"mtime": None, "data": None}
def _load():
try:
m = RESULT.stat().st_mtime
except FileNotFoundError:
return None
if m != _cache["mtime"]:
_cache["mtime"], _cache["data"] = m, json.loads(RESULT.read_text())
return _cache["data"]
def _rot(axis, deg):
return cv2.Rodrigues(np.asarray(axis, float) / np.linalg.norm(axis) * np.radians(deg))[0]
def base_from_head(yaw, pitch):
"""4x4 head camera -> arm base transform at head (yaw, pitch) deg, or None before calib.py and fit have run."""
d = _load()
if d is None or "pitch_axis" not in d:
return None
X = np.array(d["T_base_cam"])
ref_yaw, ref_pitch = d["body"][2], d["body"][3]
yp, yu = np.array(d["yaw_axis"]["point"]), np.array(d["yaw_axis"]["dir"])
pp, pu = np.array(d["pitch_axis"]["point"]), np.array(d["pitch_axis"]["dir"]) # as at the reference yaw
Rp, Ry = _rot(pu, pitch - ref_pitch), _rot(yu, yaw - ref_yaw)
out = np.eye(4)
out[:3, :3] = Ry @ Rp @ X[:3, :3]
out[:3, 3] = yp + Ry @ (pp + Rp @ (X[:3, 3] - pp) - yp)
return out
def head_centre():
"""The head's turning centre (mm, arm base frame): midway between the closest points of the yaw and the pitch
axis (27 mm apart in the 2026-10-19 fit). Fixed at any head pose and lift; None before fit has run."""
d = _load()
if d is None or "pitch_axis" not in d:
return None
p, u = np.array(d["yaw_axis"]["point"]), np.array(d["yaw_axis"]["dir"])
q, v = np.array(d["pitch_axis"]["point"]), np.array(d["pitch_axis"]["dir"])
w, b = p - q, u @ v
den = (u @ u) * (v @ v) - b * b
s, t = (b * (v @ w) - (v @ v) * (u @ w)) / den, ((u @ u) * (v @ w) - b * (u @ w)) / den
return (p + s * u + q + t * v) / 2
def base_from_head_now():
"""base_from_head at the head pose the body reports now (None when unknown)."""
_, _, yaw, pitch = head.status()
return base_from_head(yaw, pitch)
# ---------- measuring ----------
def _flange():
for _ in range(10): # get_data now and then answers without the arm state
try:
return arm.cmd("get_data")["actual_position"]
except (KeyError, OSError, ValueError):
time.sleep(0.2)
raise RuntimeError("no arm state")
def _orthonormal(R):
U, _, Vt = np.linalg.svd(R)
return U @ Vt
def measure(which):
"""Move the head through STEPS[which] (slowly, lift and waist stay) and save the marker pose at each."""
from vision import calib
calib.CAMERA = "head"
K, dist, _ = calib.camera_model()
lift, waist, yaw0, pitch0 = head.status()
start, rows = _flange(), []
for yaw, pitch in STEPS[which]:
head.moveto([lift, waist, yaw, pitch], vel=20, acc=20)
time.sleep(SETTLE_S)
seen = []
for _ in range(FRAMES):
T, _ = calib.find_marker(calib.latest_image(), K, dist)
if T is not None:
seen.append(T)
time.sleep(0.15)
moved = float(np.linalg.norm(np.subtract(_flange()[:3], start[:3])))
if moved > 1.0:
sys.exit(f"the arm moved {moved:.1f} mm: keep it still and start again")
T = None
if seen:
T = np.mean(seen, axis=0)
T[:3, :3] = _orthonormal(T[:3, :3])
rows.append({"body": head.status(), "T_cam_marker": None if T is None else T.tolist()})
print(f"yaw {yaw:4.0f} pitch {pitch:4.0f}: marker {'not seen' if T is None else T[:3, 3].round(0)}",
flush=True)
head.moveto([lift, waist, yaw0, pitch0], vel=20, acc=20)
MEASURED[which].write_text(json.dumps(rows))
print(f"saved {MEASURED[which].name}")
def _camera_poses(rows, X0, ref):
"""(yaw, pitch, camera pose in the arm frame) of every row, through the marker that stays put."""
rows = [r for r in rows if r["T_cam_marker"]]
at_ref = [r for r in rows if abs(r["body"][2] - ref[0]) < 0.5 and abs(r["body"][3] - ref[1]) < 0.5]
if not at_ref:
sys.exit("no row at the calibration's head pose: measure again")
M = X0 @ np.array(at_ref[0]["T_cam_marker"]) # the marker in the arm frame
return [(r["body"][2], r["body"][3], M @ np.linalg.inv(np.array(r["T_cam_marker"]))) for r in rows]
def _axis(poses, X0, sign_of):
"""(point, unit direction) of the rotation taking X0 to each pose; the direction turned so that a positive
angle (sign_of(pose) > 0) is a positive rotation."""
A, b, dirs = [], [], []
for p in poses:
R = p[2][:3, :3] @ X0[:3, :3].T
A.append(np.eye(3) - R) # rotation about a line through c: t' - c = R (t - c)
b.append(p[2][:3, 3] - R @ X0[:3, 3])
rv = cv2.Rodrigues(R)[0].ravel()
if np.degrees(np.linalg.norm(rv)) >= MIN_TURN_DEG:
dirs.append(rv / np.linalg.norm(rv) * np.sign(sign_of(p)))
point = np.linalg.lstsq(np.vstack(A), np.concatenate(b), rcond=None)[0]
u = np.mean(dirs, axis=0)
return point, u / np.linalg.norm(u)
def fit():
d = json.loads(RESULT.read_text())
X0, ref = np.array(d["T_base_cam"]), (d["body"][2], d["body"][3])
yaw_rows = [p for p in _camera_poses(json.loads(MEASURED["yaw"].read_text()), X0, ref)
if abs(p[1] - ref[1]) < 0.5]
pitch_rows = [p for p in _camera_poses(json.loads(MEASURED["pitch"].read_text()), X0, ref)
if abs(p[0] - ref[0]) < 0.5]
yp, yu = _axis(yaw_rows, X0, lambda p: p[0] - ref[0])
pp, pu = _axis(pitch_rows, X0, lambda p: p[1] - ref[1])
d["yaw_axis"] = {"point": yp.round(1).tolist(), "dir": yu.round(4).tolist()}
d["pitch_axis"] = {"point": pp.round(1).tolist(), "dir": pu.round(4).tolist()}
d["axes_time"] = time.strftime("%Y-%m-%d %H:%M")
RESULT.write_text(json.dumps(d, indent=1))
print(f"yaw axis through {yp.round(1)} along {yu.round(3)}; pitch axis through {pp.round(1)} along {pu.round(3)}")
worst = 0.0
for yaw, pitch, X in _camera_poses(json.loads(MEASURED["yaw"].read_text()), X0, ref) + \
_camera_poses(json.loads(MEASURED["pitch"].read_text()), X0, ref):
P = base_from_head(yaw, pitch)
e = float(np.linalg.norm(P[:3, 3] - X[:3, 3]))
a = float(np.degrees(np.linalg.norm(cv2.Rodrigues(P[:3, :3] @ X[:3, :3].T)[0])))
worst = max(worst, e)
print(f" yaw {yaw:6.1f} pitch {pitch:5.1f}: camera {e:4.1f} mm, {a:4.2f} deg off")
print(f"saved {RESULT.name}; worst {worst:.1f} mm")
def check():
from vision import calib
calib.CAMERA = "head"
K, dist, _ = calib.camera_model()
d = _load()
order, T_flange_marker = d["euler"], np.array(d["T_flange_marker"])
print("marker from the head camera vs from the arm, at the head pose now (Ctrl+C to stop)")
try:
while True:
T, _ = calib.find_marker(calib.latest_image(), K, dist)
expected = (calib.flange_pose(_flange(), order) @ T_flange_marker)[:3, 3]
if T is None:
print(" marker not in view", flush=True)
else:
seen = (base_from_head_now() @ T)[:3, 3]
print(f" head {head.status()[2:]} camera {seen.round(0)} arm {expected.round(0)} difference "
f"{np.linalg.norm(seen - expected):.1f} mm", flush=True)
time.sleep(0.5)
except KeyboardInterrupt:
pass
if __name__ == "__main__":
what = sys.argv[1:2]
if what == ["measure"] and sys.argv[2:3] in (["yaw"], ["pitch"]):
measure(sys.argv[2])
elif what == ["fit"]:
fit()
elif what == ["check"]:
check()
else:
print(__doc__)
+201
View File
@@ -0,0 +1,201 @@
"""Objects on the table in front of the torso camera: class, colour, 3D position and size in the arm base frame.
The camera service (camview.py) runs YOLOv8n once per frame for people and objects alike; for the torso
camera it calls measure_all() with the non-person boxes and the aligned depth, and puts the result into
lumi_det_torso.json ("objects"). api/server.py serves it as GET /objects, the dashboard draws the boxes.
python vision/objects.py # print what the torso camera sees now (camera service must be running)
python vision/objects.py --watch # every second, until Ctrl+C
Positions are in the arm base frame (mm, z up) through camera_extrinsics.json (calib.py). The calibration was
made at one lift / waist position; other positions are not verified yet (docs/15 section 8).
Only the front of an object is visible, so for round things (cups, bottles, fruit) the centre is the visible
surface pushed back by half the width along the line of sight.
"""
import json
import sys
import time
from pathlib import Path
import cv2
import numpy as np
from vision import camview
ROOT = Path(__file__).resolve().parents[1] # the project folder
EXTRINSICS = ROOT / "data" / "camera_extrinsics.json"
CAMERA = "torso"
FG_MM = 60.0 # depth band around the object's centre depth that counts as the object
MIN_POINTS = 40 # fewer valid depth pixels than this -> no 3D for that box
MAX_POINTS = 4000 # depth pixels used per object (random subset)
MID_BAND = (0.3, 0.7) # width is measured on this height band of the object (the table edge stays out)
EDGE_PCT = (1, 99) # percentiles taken as the object's edges (robust to stray depth pixels)
MIN_SATURATION = 50 # HSV S below this is white / grey / black
EDGE_PX = 4 # a box this close to the bottom of the frame is cut off: height and centre z unknown
STALE_S = 1.5 # s; an older detection file means the camera service is not live
SURE_SCORE = 0.35 # a box scoring less (person.WEAK_SCORE) is kept only when depth measures this size there:
WEAK = {"cup": ((40, 110), (50, 250))} # name -> (width, height) mm ranges
WIDEST = {"cup": 100} # mm; a box measured wider is something else: a white plant pot read "cup" at 110 mm
# (2026-10-20); the widest cup the gripper takes reads ~84
COCO = ("person bicycle car motorcycle airplane bus train truck boat traffic_light fire_hydrant stop_sign "
"parking_meter bench bird cat dog horse sheep cow elephant bear zebra giraffe backpack umbrella handbag tie "
"suitcase frisbee skis snowboard sports_ball kite baseball_bat baseball_glove skateboard surfboard "
"tennis_racket bottle wine_glass cup fork knife spoon bowl banana apple sandwich orange broccoli carrot "
"hot_dog pizza donut cake chair couch potted_plant bed dining_table toilet tv laptop mouse remote keyboard "
"cell_phone microwave oven toaster sink refrigerator book clock vase scissors teddy_bear hair_drier "
"toothbrush").split()
COCO = [c.replace("_", " ") for c in COCO]
ROUND = {"cup", "bottle", "wine glass", "bowl", "apple", "orange", "banana", "vase", "sports ball", "donut"}
# OpenCV hue 0-180 -> colour name, upper bounds
HUES = ((8, "red"), (20, "orange"), (33, "yellow"), (85, "green"), (130, "blue"), (155, "purple"), (170, "pink"),
(181, "red"))
_extr = {"mtime": None, "T": None}
def base_from_camera():
"""4x4 camera -> arm base transform from calib.py, or None (re-read when the file changes)."""
try:
m = EXTRINSICS.stat().st_mtime
except FileNotFoundError:
return None
if m != _extr["mtime"]:
_extr["mtime"], _extr["T"] = m, np.array(json.loads(EXTRINSICS.read_text())["T_base_cam"])
return _extr["T"]
LIGHT = {"white", "grey"} # the same white cup reads "grey" in shade or from the head camera (2026-10-20)
def same_colour(asked, seen):
"""True when a thing seen as `seen` counts as the colour `asked` (None: any colour)."""
return asked is None or asked == seen or {asked, seen} <= LIGHT
def colour_name(bgr_pixels):
"""Dominant colour of an (N, 3) BGR pixel array."""
if len(bgr_pixels) == 0:
return None
hsv = cv2.cvtColor(bgr_pixels.reshape(-1, 1, 3).astype(np.uint8), cv2.COLOR_BGR2HSV).reshape(-1, 3)
vivid = hsv[hsv[:, 1] >= MIN_SATURATION]
if len(vivid) < 0.25 * len(hsv):
v = np.median(hsv[:, 2])
return "white" if v > 170 else "black" if v < 60 else "grey"
hist = np.bincount(vivid[:, 0], minlength=181)
hist[:8] += hist[170:].sum() # red wraps around 0
hist[170:] = 0
h = int(np.argmax(np.convolve(hist, np.ones(7), "same")))
return next(name for top, name in HUES if h < top)
def measure(color, depth, box, intr, T, round_=False):
"""3D facts of one box: colour, distance (m), centre, top, width, height (mm, arm base frame)."""
x1, y1, x2, y2 = box
d = depth[y1:y2, x1:x2]
out = {"colour": colour_name(color[y1:y2, x1:x2].reshape(-1, 3)), "distance_m": None, "position_mm": None,
"top_mm": None, "width_mm": None, "height_mm": None}
h, w = d.shape
core = d[h // 4:3 * h // 4, w // 4:3 * w // 4]
core = core[core > 0]
if core.size < MIN_POINTS:
return out
dc = float(np.median(core))
mask = (d > 0) & (np.abs(d - dc) < FG_MM)
vs, us = np.nonzero(mask)
out["colour"] = colour_name(color[y1:y2, x1:x2][mask])
out["distance_m"] = round(dc / 1000, 3)
if len(vs) < MIN_POINTS or T is None or intr is None:
return out
if len(vs) > MAX_POINTS:
pick = np.random.default_rng(0).choice(len(vs), MAX_POINTS, replace=False)
vs, us = vs[pick], us[pick]
z = d[vs, us].astype(np.float64)
K = np.array([[intr["fx"], 0, intr["cx"]], [0, intr["fy"], intr["cy"]], [0, 0, 1]])
px = np.stack([us + x1, vs + y1], axis=1).astype(np.float64).reshape(-1, 1, 2)
n = cv2.undistortPoints(px, K, np.array(intr["dist"])).reshape(-1, 2)
P = T[:3, :3] @ np.stack([n[:, 0] * z, n[:, 1] * z, z]) + T[:3, 3:4] # (3, N) in the arm base frame
bottom, top = np.percentile(P[2], EDGE_PCT)
band = (P[2] > bottom + MID_BAND[0] * (top - bottom)) & (P[2] < bottom + MID_BAND[1] * (top - bottom))
mid = P[:, band] if band.sum() >= MIN_POINTS // 2 else P
surface = np.median(mid, axis=1)
sight = surface[:2] - T[:2, 3] # horizontal line of sight from the camera
sight /= np.linalg.norm(sight) or 1.0
across = mid[:2].T @ np.array([-sight[1], sight[0]])
width = float(np.subtract(*np.percentile(across, EDGE_PCT[::-1])))
centre = np.array([*surface[:2], (top + bottom) / 2])
if round_: # the camera sees the front; the centre is behind it
centre[:2] += sight * width / 2
out.update(position_mm=[round(float(v)) for v in centre], top_mm=round(float(top)), width_mm=round(width),
height_mm=round(float(top - bottom)))
return out
def measure_all(color, depth, boxes, intr=None, T=None):
"""[{name, score, box, colour, distance_m, position_mm, top_mm, width_mm, height_mm}] for YOLO boxes
(x1, y1, x2, y2, score, coco_class) of one frame, nearest first. "cut": the object's bottom is below the
frame, so height_mm and position_mm z are None (top_mm, x, y and width still hold). intr / T default to the
torso camera's."""
if intr is None:
intr = camview.intrinsics(CAMERA)
if T is None:
T = base_from_camera()
result = []
for x1, y1, x2, y2, score, cls in boxes:
o = {"name": COCO[cls], "score": round(score, 2), "box": (x1, y1, x2, y2)}
if depth is None:
o["colour"] = colour_name(color[y1:y2, x1:x2].reshape(-1, 3))
else:
o.update(measure(color, depth, (x1, y1, x2, y2), intr, T, round_=o["name"] in ROUND))
if y2 >= color.shape[0] - EDGE_PX and o.get("height_mm") is not None: # the bottom is out of view
o.update(cut=True, height_mm=None)
o["position_mm"][2] = None
if score < SURE_SCORE and not sized_like(o):
continue
if (o.get("width_mm") or 0) > WIDEST.get(o["name"], float("inf")):
continue
result.append(o)
result.sort(key=lambda o: o.get("distance_m") or 99)
return result
def sized_like(o):
"""A weak box is believed only when depth measured a whole object of its class's size (WEAK)."""
size = WEAK.get(o["name"])
w, h = o.get("width_mm"), o.get("height_mm")
return bool(size and w is not None and h is not None and size[0][0] <= w <= size[0][1] and size[1][0] <= h <= size[1][1])
def latest(camera=CAMERA):
"""What the camera service saw last: {"age_s", "objects"}; objects is [] when it is not live. For the head
camera also "head_pose" [lift, waist, yaw, pitch] the positions were measured at."""
try:
d = json.loads(camview.det_path(camera).read_text())
except (FileNotFoundError, ValueError):
return {"age_s": None, "objects": []}
age = time.time() - d.get("time", 0)
return {"age_s": round(age, 2), "objects": d.get("objects", []) if age < STALE_S else [],
"head_pose": d.get("head_pose")}
def _print():
camview.want(CAMERA)
d = latest()
if d["age_s"] is None or d["age_s"] >= STALE_S:
print(f"camera service not live (age {d['age_s']})")
return
if not d["objects"]:
print("no objects")
for o in d["objects"]:
print(f"{o['name']:12s} {o.get('colour') or '?':7s} {o['score']:.2f} dist {o.get('distance_m')} m "
f"centre {o.get('position_mm')} mm width {o.get('width_mm')} height {o.get('height_mm')} "
f"top z {o.get('top_mm')}")
if __name__ == "__main__":
if "--watch" in sys.argv:
while True:
_print()
print("-" * 40)
time.sleep(1.0)
_print()
+473
View File
@@ -0,0 +1,473 @@
"""Find people in front of the robot: Orbbec colour + depth, YOLOv8s on the GPU (TensorRT engine) or, when that is not
available, YOLOv8n on the CPU (ONNX, OpenCV DNN). Both have the 80 COCO classes; only the speed and accuracy differ.
python vision/person.py # head camera, print the people seen (distance, angle) for 20 s
python vision/person.py torso --save # torso camera, also save person_view.jpg with boxes every second
The camera is chosen by name (head / torso), serial number or index. Names are safer: the index
order changes when USB cables are moved.
Each person: box in colour pixels, score, distance in metres (median depth inside the box centre; without
depth (depth=False, the head camera, see camview.py) a distance_hint function or the box size gives it),
angle in degrees from the robot's waist forward axis (positive = person is on the image's left side).
For the head camera the current head yaw is added, so the angle does not jump when the head turns.
"""
import pathlib
import sys
import threading
import time
import cv2
import numpy as np
from pyorbbecsdk import (AlignFilter, Config, Context, OBFormat, OBLogLevel, OBSensorType, OBStreamType,
Pipeline)
from vision import camview, reid
from robot import head
ROOT = pathlib.Path(__file__).resolve().parents[1] # the project folder
MODEL = ROOT / "models" / "yolov8n.onnx" # fallback: OpenCV DNN on the CPU
ENGINE = ROOT / "models" / "yolov8s.engine" # TensorRT engine built from yolov8s.onnx on this Thor (640, FP32)
COLOR_HFOV = 94.0 # deg, Gemini 2 L colour camera
SIZE = 640 # YOLO input size
MIN_SCORE = 0.5
OBJECT_SCORE = 0.35 # other COCO classes (cups, bottles...) are kept for objects.py above this ...
WEAK_SCORE = {41: 0.05} # ... and cups from this: a white tumbler 1.4 m away scored 0.03-0.25 (2026-10-16); objects.py
# keeps such a weak box only when depth measures a cup-sized thing there (objects.WEAK)
# Full-size px (x1, y1, x2, y2) looked at a second time, bigger (about 2.7x the whole-frame pass): the pick zone of the
# torso camera (a cup on a box there scored 0.15 in the whole frame and 0.73 in this crop, 2026-10-15), and the left
# and right of the band where table tops further away are seen (cups 1-3 m away were missed, 2026-10-16). ~45-50 ms
# each on the CPU.
ZOOM = {"torso": [(400, 300, 880, 720), (0, 180, 560, 600), (720, 180, 1280, 600)]}
ZOOM_EDGE_PX = 3 # a zoom box touching a crop side inside the frame is cut by it: not used
CAMERAS = {"head": "CPA9B52007A", "torso": "CPA9B520037"} # name -> serial number
# The head camera sits behind a USB 2.0 hub inside the head (shared with the mic and speaker).
# On USB 2 the default depth mode is 1280x800 at 10 fps with many broken framesets. 15 fps colour (MJPG)
# + 640x400 depth leaves room for the mic and gives clean frames; YOLO on the CPU runs ~15 fps anyway.
COLOR_MODE = (1280, 720, OBFormat.MJPG, 15)
DEPTH_MODE = (640, 400, OBFormat.Y16, 15)
FY_720 = 610.0 # px, colour focal length at 1280x720 (JAKA calibration of the Gemini 2 L)
PERSON_H, PERSON_W = 1.70, 0.50 # m, typical person height and width for a distance from the box size
OPEN_TRIES = 5 # 1 s apart
NEAR_RED = 1.2 # m; nearest person this close is drawn red even when lumi.py is not running
STALL_S = 2.0 # s without a full frame -> reopen the camera
REBOOT_IF_STUCK_AGAIN_S = 15.0 # s; stuck again this soon after a reopen -> reboot the device
REBOOT_WAIT_S = 6.0 # s for a rebooted camera to come back on USB
MAX_REBOOTS_10MIN = 3 # more than this -> the camera rests UNSTABLE_PAUSE_S before trying again
UNSTABLE_PAUSE_S = 60.0
HEAD_POLL_S = 0.2 # s between head yaw reads (head camera only)
def _profile(pipeline, sensor, mode):
"""The wanted stream mode, or the camera's default if it does not offer it."""
profiles = pipeline.get_stream_profile_list(sensor)
try:
return profiles.get_video_stream_profile(*mode)
except Exception:
return profiles.get_default_video_stream_profile()
_ctx = [] # one Orbbec context per program, kept alive while its devices are used
def open_camera(camera):
"""camera = name (head / torso), serial number or index -> (Pipeline, serial, name).
Only the camera service (camview.py) should call this: two programs opening cameras reset them."""
if not _ctx:
ctx = Context()
ctx.set_logger_level(OBLogLevel.NONE)
_ctx.append(ctx)
devices = _ctx[0].query_devices()
serials = [devices.get_device_serial_number_by_index(i) for i in range(devices.get_count())]
camera = str(camera)
wanted = CAMERAS.get(camera, camera)
if wanted in serials:
index = serials.index(wanted)
elif camera.isdigit() and int(camera) < len(serials):
index = int(camera)
else:
raise RuntimeError(f"camera {camera!r} not found; connected: {serials}")
name = next((n for n, sn in CAMERAS.items() if sn == serials[index]), f"#{index}")
return Pipeline(devices.get_device_by_index(index)), serials[index], name
def _jpeg_complete(data):
"""True if the JPEG ends with its end-of-image marker (FF D9), ignoring zero padding."""
end = len(data)
while end > 2 and data[end - 1] == 0:
end -= 1
return end > 2 and data[end - 2] == 0xFF and data[end - 1] == 0xD9
def _iou(a, b):
ix = max(0, min(a[2], b[2]) - max(a[0], b[0]))
iy = max(0, min(a[3], b[3]) - max(a[1], b[1]))
inter = ix * iy
return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter or 1)
class CvNet:
"""YOLO on the CPU through OpenCV DNN (the fallback)."""
name = "OpenCV DNN on the CPU (yolov8n)"
def __init__(self):
self.net = cv2.dnn.readNetFromONNX(str(MODEL))
def forward(self, blob):
self.net.setInput(blob)
return self.net.forward()
class TrtNet:
"""YOLO on the GPU through TensorRT: the engine file is deserialized once, input and output stay in GPU memory."""
name = "TensorRT on the GPU (yolov8s)"
def __init__(self, path=None):
import tensorrt as trt
from cuda.bindings import runtime as cr
self.cr = cr
path = path or ENGINE
self.engine = trt.Runtime(trt.Logger(trt.Logger.ERROR)).deserialize_cuda_engine(open(path, "rb").read())
if self.engine is None:
raise RuntimeError(f"cannot load {path}")
self.ctx = self.engine.create_execution_context()
self.inp, self.out = (self.engine.get_tensor_name(i) for i in range(2))
self.out_shape = tuple(self.engine.get_tensor_shape(self.out)) # (1, 84, 8400): box + 80 classes per anchor;
# the pose model (vision/pose.py): (1, 56, 8400)
self.in_bytes = 1 * 3 * SIZE * SIZE * 4
self.out_bytes = int(np.prod(self.out_shape)) * 4
self.d_in, self.d_out = self._malloc(self.in_bytes), self._malloc(self.out_bytes)
self.ctx.set_tensor_address(self.inp, int(self.d_in))
self.ctx.set_tensor_address(self.out, int(self.d_out))
self.stream = self._malloc_stream()
self.host_out = np.empty(self.out_shape, np.float32)
def _check(self, r):
"""cuda-python returns (error, value) or just the error."""
if isinstance(r, tuple):
err, val = r[0], (r[1] if len(r) > 1 else None)
else:
err, val = r, None
if err != self.cr.cudaError_t.cudaSuccess:
raise RuntimeError(f"CUDA error {err}")
return val
def _malloc(self, nbytes):
return self._check(self.cr.cudaMalloc(nbytes))
def _malloc_stream(self):
return self._check(self.cr.cudaStreamCreate())
def forward(self, blob):
"""blob: (1, 3, 640, 640) float32, as cv2.dnn.blobFromImage makes it. Returns out_shape."""
x = np.ascontiguousarray(blob, np.float32)
cr = self.cr
self._check(cr.cudaMemcpyAsync(self.d_in, x.ctypes.data, self.in_bytes,
cr.cudaMemcpyKind.cudaMemcpyHostToDevice, self.stream))
self.ctx.execute_async_v3(int(self.stream))
self._check(cr.cudaMemcpyAsync(self.host_out.ctypes.data, self.d_out, self.out_bytes,
cr.cudaMemcpyKind.cudaMemcpyDeviceToHost, self.stream))
self._check(cr.cudaStreamSynchronize(self.stream))
return self.host_out
def load_net():
"""The GPU detector when its engine loads, else the CPU one (the robot keeps working, only slower)."""
try:
return TrtNet()
except Exception as e: # no engine file, no GPU, no TensorRT: say why, then use the fallback
print(f"person: TensorRT not used ({e}); YOLOv8n on the CPU", flush=True)
return CvNet()
def detect_boxes(net, color):
"""YOLOv8 boxes: list of (x1, y1, x2, y2, score, COCO class id); class 0 is a person."""
h, w = color.shape[:2]
scale = SIZE / max(h, w)
canvas = np.zeros((SIZE, SIZE, 3), np.uint8) # letterbox, keep aspect ratio
canvas[:int(h * scale), :int(w * scale)] = cv2.resize(color, (int(w * scale), int(h * scale)))
out = net.forward(cv2.dnn.blobFromImage(canvas, 1 / 255.0, (SIZE, SIZE), swapRB=True))[0].T
# (8400, 84): cx, cy, w, h, 80 class scores
cls = out[:, 4:].argmax(axis=1)
scores = out[np.arange(len(out)), 4 + cls]
floor = np.array([WEAK_SCORE.get(int(c), OBJECT_SCORE) for c in cls])
keep = scores > np.where(cls == 0, MIN_SCORE, floor)
if not keep.any():
return []
cls = cls[keep]
cx, cy, bw, bh = (out[keep, i] / scale for i in range(4))
boxes = np.stack([cx - bw / 2, cy - bh / 2, bw, bh], axis=1)
idx = cv2.dnn.NMSBoxes(boxes.tolist(), scores[keep].tolist(), min(WEAK_SCORE.values()), 0.45)
result = []
for i in np.array(idx).flatten():
x, y, bw_, bh_ = boxes[i]
result.append((max(0, int(x)), max(0, int(y)), min(w - 1, int(x + bw_)), min(h - 1, int(y + bh_)),
float(scores[keep][i]), int(cls[i])))
return result
class PersonDetector:
def __init__(self, camera="head", head_sign=1.0, depth=True):
self.camera, self.use_depth = camera, depth
self.distance_hint = None # optional f(angle_deg) -> metres from another camera
self._open()
self.last_frame = time.time()
self.reopens, self.reboots, self.last_reopen = 0, 0, 0.0
self.head_sign, self.head_yaw = head_sign, 0.0
self.head_pose = None # [lift, waist, yaw, pitch] last read (head camera only)
self.focus_angle = None # set by lumi.py: the person it talks to is drawn red
self.bad_jpeg = 0 # colour frames dropped because they arrived incomplete
self.running = True
self.objects, self.depth = [], None # last frame: non-person boxes and aligned depth (objects.py)
if self.name == "head": # the head camera turns with the head
threading.Thread(target=self._follow_head, daemon=True).start()
self.align = AlignFilter(align_to_stream=OBStreamType.COLOR_STREAM) # depth pixels -> colour pixels
self.net = load_net()
# frames are grabbed at the camera's rate in their own thread (live video: on_raw gets every JPEG);
# read() detects people on the newest frame only, at whatever speed YOLO manages
self.on_raw = None # f(name, jpeg bytes), set by the camera service
self._latest, self._new = None, threading.Event()
threading.Thread(target=self._grab, daemon=True).start()
def _grab(self):
while self.running:
try:
frames = self.pipeline.wait_for_frames(200)
except Exception:
time.sleep(0.05)
continue
if frames is None:
continue
if self.on_raw is not None:
c = frames.get_color_frame()
if c is not None and str(c.get_format()).endswith("MJPG"):
data = np.asanyarray(c.get_data())
if _jpeg_complete(data):
try:
self.on_raw(self.name, data.tobytes())
except Exception:
pass
self._latest = frames
self._new.set()
def _open(self):
for attempt in range(OPEN_TRIES): # the live view in api/server.py may still be letting it go
try:
self.pipeline, self.serial, self.name = open_camera(self.camera)
config = Config()
self.color_profile = _profile(self.pipeline, OBSensorType.COLOR_SENSOR, COLOR_MODE)
config.enable_stream(self.color_profile)
if self.use_depth:
config.enable_stream(_profile(self.pipeline, OBSensorType.DEPTH_SENSOR, DEPTH_MODE))
self.pipeline.start(config)
return
except Exception:
if attempt == OPEN_TRIES - 1:
raise
time.sleep(1.0)
def intrinsics(self):
"""Colour camera matrix and distortion of the open mode (factory calibration), as a JSON-ready dict."""
i, d = self.color_profile.get_intrinsic(), self.color_profile.get_distortion()
return {"width": i.width, "height": i.height, "fx": i.fx, "fy": i.fy, "cx": i.cx, "cy": i.cy,
"dist": [d.k1, d.k2, d.p1, d.p2, d.k3, d.k4, d.k5, d.k6]} # OpenCV order
def _reopen(self):
"""The camera stopped sending. Seen on the head camera: sometimes it streams for ~1 s and then stops,
and opening it again does not help; a device reboot does. So: reopen first; stuck again soon -> reboot."""
now = time.time()
reboot = now - self.last_reopen < REBOOT_IF_STUCK_AGAIN_S
self.last_reopen = now
old = self.pipeline
self.reboot_times = [t for t in getattr(self, "reboot_times", []) if now - t < 600]
if reboot and len(self.reboot_times) >= MAX_REBOOTS_10MIN:
# it keeps failing (the head camera's USB 2 hub): rest instead of resetting the hub again and again,
# which also disturbs the microphone and the speaker on the same hub
print(f"{self.name} camera: unstable ({len(self.reboot_times)} reboots in 10 min) - pausing "
f"{UNSTABLE_PAUSE_S:.0f} s", flush=True)
t = threading.Thread(target=old.stop, daemon=True)
t.start()
t.join(2.0)
time.sleep(UNSTABLE_PAUSE_S)
self.reboot_times = self.reboot_times[-1:]
reboot = False
if reboot:
self.reboot_times.append(now)
try:
dev = old.get_device()
t = threading.Thread(target=dev.reboot, daemon=True)
t.start()
t.join(3.0)
print(f"{self.name} camera: stuck again - device rebooted", flush=True)
self.reboots += 1
except Exception as e:
print(f"{self.name} camera: reboot failed: {e}", flush=True)
time.sleep(REBOOT_WAIT_S) # the camera leaves the USB bus and comes back
elif not self.reboot_times or self.reboot_times[-1] != now:
t = threading.Thread(target=old.stop, daemon=True) # stop() can hang on a stuck device
t.start()
t.join(2.0)
try:
self._open()
self.reopens += 1
print(f"{self.name} camera: no frames for {STALL_S:.0f} s - reopened", flush=True)
except Exception as e:
print(f"{self.name} camera: reopen failed: {e}", flush=True)
self.last_frame = time.time()
def close(self):
self.running = False
self.pipeline.stop()
def _follow_head(self):
"""Keep self.head_yaw up to date (deg) so image angles can be turned into waist angles."""
while self.running:
try:
self.head_pose = head.status()
self.head_yaw = self.head_pose[2]
except Exception:
pass # keep the last value; the body API may be busy
time.sleep(HEAD_POLL_S)
def _frames(self):
"""(colour BGR image, depth in mm aligned to it) or (None, None)."""
if not self._new.wait(0.2):
return None, None
self._new.clear()
frames = self._latest
if frames is None:
return None, None
if not self.use_depth:
c = frames.get_color_frame()
return (self._decode(c), None) if c is not None else (None, None)
frames = self.align.process(frames)
if frames is None:
return None, None
frames = frames.as_frame_set()
c, d = frames.get_color_frame(), frames.get_depth_frame()
if c is None or d is None or len(d.get_data()) != d.get_width() * d.get_height() * 2:
return None, None
color = self._decode(c)
depth = np.frombuffer(d.get_data(), dtype=np.uint16).reshape(d.get_height(), d.get_width())
depth = depth.astype(np.float32) * d.get_depth_scale()
if color is None or color.shape[:2] != depth.shape:
return None, None
return color, depth
def _decode(self, c):
data = np.asanyarray(c.get_data())
if str(c.get_format()).endswith("MJPG"):
if not _jpeg_complete(data): # cut short on the busy USB 2 hub: skip it quietly
self.bad_jpeg += 1
return None
return cv2.imdecode(data, cv2.IMREAD_COLOR)
return cv2.cvtColor(data.reshape(c.get_height(), c.get_width(), 3), cv2.COLOR_RGB2BGR)
def _box_distance(self, x1, y1, x2, y2, h):
"""Rough distance from the box size: height for a whole person, width if the box is cut by the frame."""
f = FY_720 * h / 720
if y1 > 3 and y2 < h - 3 and y2 > y1:
return f * PERSON_H / (y2 - y1)
return f * PERSON_W / max(1, x2 - x1)
def _detect(self, color):
return detect_boxes(self.net, color)
def _zoomed(self, color, have):
"""Non-person boxes found in the ZOOM crops (full-frame px) that the whole frame and earlier crops missed."""
h, w = color.shape[:2]
out = []
for zx1, zy1, zx2, zy2 in ZOOM[self.name]:
for x1, y1, x2, y2, score, cls in self._detect(color[zy1:zy2, zx1:zx2]):
cut = (zx1 > 0 and x1 < ZOOM_EDGE_PX) or (zy1 > 0 and y1 < ZOOM_EDGE_PX) \
or (zx2 < w and x2 > zx2 - zx1 - 1 - ZOOM_EDGE_PX) or (zy2 < h and y2 > zy2 - zy1 - 1 - ZOOM_EDGE_PX)
if cls == 0 or cut:
continue
box = (x1 + zx1, y1 + zy1, x2 + zx1, y2 + zy1)
if not any(b[5] == cls and _iou(box, b[:4]) > 0.3 for b in have + out):
out.append((*box, score, cls))
return out
def read(self):
"""(colour image, [dict(box, score, distance_m, angle_deg)]) or (None, []) if no frame."""
color, depth = self._frames()
if color is None:
if time.time() - self.last_frame > STALL_S:
self._reopen()
return None, []
self.last_frame = time.time()
w = color.shape[1]
yaw = self.head_yaw # 0 for the torso camera
people, self.objects = [], []
self.depth = depth # aligned depth (mm) of this frame, for objects.py
boxes = self._detect(color)
for x1, y1, x2, y2, score, cls in boxes:
if cls != 0:
self.objects.append((x1, y1, x2, y2, score, cls))
continue
# centre part of the box (torso), ignore holes (0) in the depth image
cx1, cx2 = x1 + (x2 - x1) // 4, x2 - (x2 - x1) // 4
cy1, cy2 = y1 + (y2 - y1) // 4, y2 - (y2 - y1) // 2
angle = -((x1 + x2) / 2 - w / 2) / (w / 2) * (COLOR_HFOV / 2) + self.head_sign * yaw
src = "depth"
if depth is not None:
patch = depth[cy1:cy2, cx1:cx2]
valid = patch[patch > 0]
dist = float(np.median(valid)) / 1000 if valid.size > 50 else None
else:
dist = self.distance_hint(angle) if self.distance_hint else None
src = "other camera"
if dist is None:
dist, src = self._box_distance(x1, y1, x2, y2, color.shape[0]), "box size"
people.append({"box": (x1, y1, x2, y2), "score": round(score, 2),
"distance_m": None if dist is None else round(dist, 2), "angle_deg": round(angle, 1),
"distance_src": src, "look": reid.look(color, (x1, y1, x2, y2)),
"face": reid.face(color, (x1, y1, x2, y2)) if dist and dist <= reid.FACE_MAX_M else None})
people.sort(key=lambda p: p["distance_m"] if p["distance_m"] is not None else 99)
if self.focus_angle is not None and people:
f = min(people, key=lambda p: abs(p["angle_deg"] - self.focus_angle))
if abs(f["angle_deg"] - self.focus_angle) < 12:
f["focus"] = True
elif people and people[0]["distance_m"] is not None and people[0]["distance_m"] <= NEAR_RED:
people[0]["near"] = True # the nearest person in the greeting zone (drawn red too)
camview.publish(self.name, color, people, source=pathlib.Path(sys.argv[0]).name) # for /view in api/server.py
if self.name in ZOOM:
self.objects += self._zoomed(color, self.objects)
return color, people
def draw(color, people):
for p in people:
x1, y1, x2, y2 = p["box"]
cv2.rectangle(color, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(color, f"{p['distance_m']} m {p['angle_deg']} deg", (x1, max(20, y1 - 8)),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
return color
if __name__ == "__main__":
args = [a for a in sys.argv[1:] if not a.startswith("--")]
save = "--save" in sys.argv
if camview.service_pid(): # the camera service has the cameras: read its results
det = camview.RemoteDetector(args[0] if args else "head")
save = False
else:
det = PersonDetector(args[0] if args else "head")
print(f"{det.name} camera (SN {det.serial}) running; Ctrl+C to stop")
t0, last_save, n = time.time(), 0.0, 0
try:
while time.time() - t0 < 20:
color, people = det.read()
if color is None:
continue
n += 1
print(f"{n / (time.time() - t0):4.1f} fps " +
(", ".join(f"{p['distance_m']} m @ {p['angle_deg']} deg ({p['score']})" for p in people)
or "no person"))
if save and time.time() - last_save > 1:
cv2.imwrite(str(ROOT / "logs" / "person_view.jpg"), draw(color, people))
last_save = time.time()
except KeyboardInterrupt:
pass
finally:
det.close()
+87
View File
@@ -0,0 +1,87 @@
"""Body keypoints of the people in a colour frame: YOLO11s-pose on the GPU (TensorRT engine), 17 COCO keypoints.
python vision/pose.py [picture.jpg] # keypoints of the people in a picture (default: the head camera now)
The engine is built on this Thor from the ONNX file (exported with ultralytics, imgsz 640):
.venv/bin/python vision/yolo_engine.py models/yolo11s-pose.onnx models/yolo11s-pose.engine
Without the engine (other TensorRT, no GPU) load() returns None and callers say they can't tell.
Left / right are the person's own (their left hand is on the image's right when they face the camera).
"""
import sys
import threading
from pathlib import Path
import cv2
import numpy as np
from vision import person
ROOT = Path(__file__).resolve().parents[1] # the project folder
ENGINE = ROOT / "models" / "yolo11s-pose.engine"
SIZE = person.SIZE # 640, the model input
MIN_SCORE = 0.4 # person box score
KP_SEEN = 0.5 # keypoint confidence above this counts as seen
NAMES = ("nose", "left_eye", "right_eye", "left_ear", "right_ear", "left_shoulder", "right_shoulder", "left_elbow",
"right_elbow", "left_wrist", "right_wrist", "left_hip", "right_hip", "left_knee", "right_knee", "left_ankle",
"right_ankle")
K = {n: i for i, n in enumerate(NAMES)}
_net = {"net": None, "tried": False}
_lock = threading.Lock()
def load():
"""The TensorRT pose net, loaded once; None when it can't be loaded (says why once)."""
with _lock:
if not _net["tried"]:
_net["tried"] = True
try:
_net["net"] = person.TrtNet(ENGINE)
except Exception as e:
print(f"pose: engine not loaded ({e})", flush=True)
return _net["net"]
def detect(color):
"""[{box (x1, y1, x2, y2), score, kp: (17, 3) array of x, y px and confidence}] largest first; [] without the net."""
net = load()
if net is None:
return []
h, w = color.shape[:2]
scale = SIZE / max(h, w)
canvas = np.zeros((SIZE, SIZE, 3), np.uint8) # letterbox, as person._detect
canvas[:int(h * scale), :int(w * scale)] = cv2.resize(color, (int(w * scale), int(h * scale)))
with _lock: # one CUDA stream and output buffer per net
out = net.forward(cv2.dnn.blobFromImage(canvas, 1 / 255.0, (SIZE, SIZE), swapRB=True))[0].T.copy()
out = out[out[:, 4] > MIN_SCORE] # (N, 56): cx, cy, w, h, score, 17 x (x, y, conf)
if not len(out):
return []
out[:, :4] /= scale
boxes = np.stack([out[:, 0] - out[:, 2] / 2, out[:, 1] - out[:, 3] / 2, out[:, 2], out[:, 3]], axis=1)
keep = np.array(cv2.dnn.NMSBoxes(boxes.tolist(), out[:, 4].tolist(), MIN_SCORE, 0.45)).flatten()
people = []
for i in keep:
x, y, bw, bh = boxes[i]
kp = out[i, 5:].reshape(17, 3).copy()
kp[:, :2] /= scale
people.append({"box": (max(0, int(x)), max(0, int(y)), min(w - 1, int(x + bw)), min(h - 1, int(y + bh))),
"score": round(float(out[i, 4]), 2), "kp": kp})
people.sort(key=lambda p: -(p["box"][2] - p["box"][0]) * (p["box"][3] - p["box"][1]))
return people
def seen(kp, name):
"""(x, y) of a keypoint when it is seen, else None."""
x, y, c = kp[K[name]]
return (float(x), float(y)) if c > KP_SEEN else None
if __name__ == "__main__":
import time
img = cv2.imread(sys.argv[1] if len(sys.argv) > 1 else "/dev/shm/lumi_raw_head.jpg")
detect(img)
t = time.time()
people = detect(img)
print(f"{len(people)} people, {1000 * (time.time() - t):.0f} ms")
for p in people:
print(p["box"], p["score"], {n: tuple(int(v) for v in seen(p["kp"], n)) for n in NAMES if seen(p["kp"], n)})
+168
View File
@@ -0,0 +1,168 @@
"""Know a person again after they leave the view for a while: the face when it is seen, else the clothes' colours.
look(color, box) -> [floats] clothes signature of one person in one frame
face(color, box) -> [128 floats]|None face embedding of a near person facing the camera (YuNet + SFace, CPU)
same(a, b) -> 0..1 how alike two clothes signatures are (Bhattacharyya, averaged over the parts)
People() whom Lumi has met: .recall(look, face, now, taken), .add(look, face, now)
The camera service adds "look" (and "face" for people within FACE_MAX_M) to every person it detects. Faces decide
when both sides have one: many people here wear white shirts, the colours alone mixed up different people (0.83 for
two people, tests/data scenes). Without a face (turned away) the clothes decide. Numbers only: no picture is kept,
and People lives in lumi.py's memory (gone on restart and after FORGET_S); the embeddings never reach the disk.
Clothes: hue-saturation histograms with a brightness histogram for the colourless pixels (white, grey, black), one of
the upper body and one of the legs, from the middle half of the box (less background).
Models (models/, from github.com/opencv/opencv_zoo): face_detection_yunet_2023mar.onnx,
face_recognition_sface_2021dec.onnx. Without them face() gives None and only the clothes are used.
"""
import pathlib
import threading
import cv2
import numpy as np
ROOT = pathlib.Path(__file__).resolve().parents[1] # the project folder
FACE_DET = ROOT / "models" / "face_detection_yunet_2023mar.onnx"
FACE_REC = ROOT / "models" / "face_recognition_sface_2021dec.onnx"
PARTS = ((0.18, 0.50), (0.55, 0.90)) # parts of the box height: upper body, legs
H_BINS, S_BINS, V_BINS = 12, 3, 6 # hue x saturation for coloured pixels, brightness for the colourless ones
MIN_SAT = 50 # HSV S below this is white / grey / black (as objects.MIN_SATURATION)
MIN_PX = 200 # px in a part; fewer: the part is left empty (all zeros)
SAME = 0.90 # same() at least this: the same clothes. Head camera 2026-10-21: one person back
# after a while 0.66-0.91 (median 0.84), different people up to 0.86 (white
# shirts 0.83): colours barely tell people apart, so only a close match counts
FACE_MAX_M = 2.0 # m; faces are looked for only on people this close (~5 + 5 ms each)
FACE_SCORE = 0.85 # YuNet score below this: no face (turned away, cut by the frame). Head camera
# 2026-10-21, one person's faces against his other visits: score 0.80-0.85
# median cosine 0.36, 0.85-0.90 0.65, above 0.90 0.73
FACE_SAME = 0.30 # SFace cosine at least this: the same face. Head camera 2026-10-21, a new
# track's first 3 faces against the person's mean face: one person back
# 0.51-0.74 (6 returns seen by face), 13 other people -0.04..0.08
FORGET_S = 600.0 # s; someone not seen this long is forgotten
KEEP = 0.8 # clothes running mean: weight of the old signature per new frame
_face_lock = threading.Lock() # the camera service reads both cameras in two threads
_face_nets = None
def _part(hsv):
px = hsv.reshape(-1, 3)
if len(px) < MIN_PX:
return np.zeros(H_BINS * S_BINS + V_BINS, np.float32)
vivid = px[px[:, 1] >= MIN_SAT]
dull = px[px[:, 1] < MIN_SAT]
hs, _, _ = np.histogram2d(vivid[:, 0], vivid[:, 1], bins=(H_BINS, S_BINS), range=((0, 180), (MIN_SAT, 256)))
v, _ = np.histogram(dull[:, 2], bins=V_BINS, range=(0, 256))
h = np.concatenate([hs.ravel(), v]).astype(np.float32)
return h / h.sum()
def look(color, box):
"""Clothes signature of the person in this box (x1, y1, x2, y2 colour px), a plain list for JSON."""
x1, y1, x2, y2 = (int(v) for v in box)
w, h = x2 - x1, y2 - y1
cx1, cx2 = x1 + w // 4, x2 - w // 4
hsv = cv2.cvtColor(color[y1:y2, cx1:cx2], cv2.COLOR_BGR2HSV) if cx2 > cx1 and y2 > y1 else np.zeros((0, 0, 3))
return [round(float(x), 4) for x in np.concatenate([_part(hsv[int(a * h):int(b * h)]) for a, b in PARTS])]
def _nets():
global _face_nets
if _face_nets is None:
_face_nets = (cv2.FaceDetectorYN.create(str(FACE_DET), "", (320, 320), FACE_SCORE),
cv2.FaceRecognizerSF.create(str(FACE_REC), "")) if FACE_DET.exists() and FACE_REC.exists() else ()
return _face_nets
def face(color, box):
"""Face embedding (unit length) of the person in this box, None when no clear face is in its upper half."""
x1, y1, x2, y2 = (int(v) for v in box)
crop = color[y1:y1 + (y2 - y1) // 2, x1:x2]
if crop.shape[0] < 40 or crop.shape[1] < 40:
return None
with _face_lock:
nets = _nets()
if not nets:
return None
det, rec = nets
det.setInputSize((crop.shape[1], crop.shape[0]))
_, faces = det.detect(crop)
if faces is None:
return None
e = rec.feature(rec.alignCrop(crop, max(faces, key=lambda f: f[-1]))).ravel()
return [round(float(x), 4) for x in e / np.linalg.norm(e)]
def same(a, b):
"""0..1; parts empty in either signature (out of the frame) are not compared. 0 when nothing can be compared."""
a, b = np.asarray(a, np.float32), np.asarray(b, np.float32)
n = len(a) // len(PARTS)
scores = [float(np.sqrt(a[i:i + n] * b[i:i + n]).sum()) for i in range(0, len(a), n)
if a[i:i + n].any() and b[i:i + n].any()]
return sum(scores) / len(scores) if scores else 0.0
def blend(old, new):
"""Running mean of clothes signatures (a part empty in one keeps the other)."""
if old is None:
return list(new)
o, n = np.asarray(old, np.float32), np.asarray(new, np.float32)
k = len(o) // len(PARTS)
out = o.copy()
for i in range(0, len(o), k):
if n[i:i + k].any():
out[i:i + k] = KEEP * o[i:i + k] + (1 - KEEP) * n[i:i + k] if o[i:i + k].any() else n[i:i + k]
return out.tolist()
def blend_face(old, new):
"""Sum of the face embeddings seen (its direction is their mean): a running mean kept only the last few frames,
often a turned face as the person left, and one person back scored -0.06..0.48 against it (0.51-0.74 the sum)."""
if new is None:
return old
return list(new) if old is None else (np.asarray(old) + np.asarray(new)).tolist()
def likeness(look_a, face_a, look_b, face_b):
"""(by face, score) when both faces are known, else (by clothes, score); None when nothing can be compared."""
if face_a is not None and face_b is not None:
a, b = np.asarray(face_a), np.asarray(face_b)
return "face", float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
if look_a is not None and look_b is not None:
return "clothes", same(look_a, look_b)
return None
def alike(look_a, face_a, look_b, face_b):
m = likeness(look_a, face_a, look_b, face_b)
return m is not None and m[1] >= (FACE_SAME if m[0] == "face" else SAME)
class Person:
"""Someone Lumi has greeted: signatures, when last seen, and whether the conversation with them is still open."""
def __init__(self, look, face, now):
self.look, self.face, self.last_seen, self.talking = look, face, now, False
def seen(self, look, face, now):
if look is not None:
self.look = blend(self.look, look)
self.face = blend_face(self.face, face)
self.last_seen = now
class People:
def __init__(self):
self.known = []
def recall(self, look, face, now, taken=()):
"""The known person (not in `taken`: others in view now) this is, or None. A face match goes first."""
self.known = [p for p in self.known if now - p.last_seen < FORGET_S]
hits = [(likeness(look, face, p.look, p.face), p) for p in self.known
if p not in taken and alike(look, face, p.look, p.face)]
return max(hits, key=lambda h: (h[0][0] == "face", h[0][1]), default=(None, None))[1]
def add(self, look, face, now):
p = Person(look, face, now)
self.known.append(p)
return p
+611
View File
@@ -0,0 +1,611 @@
"""What Lumi sees now, as facts other modules can use: things in view, the person in front, what is in their hands.
sees(name=None, colour=None) -> [{name, colour, distance_m, bearing_deg, where, camera, position_mm, score}]
people() -> [{distance_m, bearing_deg, camera}] everyone in view, both cameras merged
person_in_front() -> {distance_m, bearing_deg, where, position_mm, camera, facing, gesture, raised, pointing,
clothes: {upper, lower, feet}, hands: {"left"|"right": {"position_mm", "object"}}} or None
person_holds(object=None) -> True / False / None (None: can't tell)
object_in_hand() -> {name, colour, hand, position_mm, distance_m, width_mm} or None
pointing_target() -> {"position_mm", "distance_m"} or None
ask_vlm(question, lang="en") -> one spoken sentence from gemma4 on the picture of the person, or None (slow: 3-20 s)
python vision/scene.py # print all of it for the cameras now
python vision/scene.py --save tests/data/x # save the frames now as a test fixture (x_head.jpg/.npz/.json, ...)
Sources: the camera service's files (camview.py: raw JPEG, aligned depth, people and objects with positions measured
by objects.py), and YOLO11s-pose (pose.py) run here on the raw frame, ~20 ms. Positions are in the arm base frame (mm,
z up) as objects.py gives them; distance_m is from the camera along its view. Every function takes `frames` (from
snapshot() or load()) so tests run on saved frames; without it the cameras are read now. Nothing here moves the robot.
Honest by design: a fact the cameras do not give is None, never a guess.
"""
import base64
import json
import sys
import threading
import time
import urllib.request
from pathlib import Path
import cv2
import numpy as np
from vision import camview, objects, person, pose
ROOT = Path(__file__).resolve().parents[1] # the project folder
CAMERAS = ("head", "torso") # the head camera watches people; the torso camera the table and the hands from below
FRESH_S = 1.5 # s; older detections are not "now"
WAIT_S = 1.2 # s to wait for a fresh detection when the camera service runs slow (idle: 1 per s)
DEPTH_AGE_S = 2.0 # s; depth frames are written every 0.5 s
FRONT_M = 3.0 # m; the person "in front" is nearer than this
SIDE_DEG = 15.0 # deg; a thing further left / right than this is "on my left / right"
SAME_DEG, SAME_M = 8.0, 0.35 # two cameras' detections closer than this (angle, distance) are the same thing
CAMS_APART_M = 0.25 # m; the head and torso cameras see a near person at angles apart by about atan(this / d)
STALE_DEPTH_M = 0.4 # m; depth this far off the camera service's distance of a person is from another moment
SELF_M = 0.8 # m; a box touching the frame edge at OWN_EDGE nearer than this (or unmeasured) is the
OWN_EDGE = {"head": "bottom", "torso": "top"} # robot's own body (head: the shoulder; torso: the arm and the hand)
EDGE_PX = 15
SAME_MM = 200 # ... or with arm-frame positions this close
DEPTH_R = 6 # px; half size of the depth patch at a keypoint
HAND_REACH = 0.35 # hand centre = wrist + this x (wrist - elbow): the palm and what it holds
HAND_R = 0.5 # hand region radius as a part of the forearm length
NO_DEPTH_R = 0.5 # without depth the box centre must be this part of the radius from the hand
WRIST_PCT = 20 # depth percentile at the wrist: the nearer part of the patch is the arm, not the room
HAND_DEPTH_M = 0.35 # m; an object this much further or nearer than the wrist is not in the hand
HAND_CROP_PX = 320 # px; the detector looks again at a square this big around each hand (small things)
HANDHELD = {"bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange",
"broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "cell phone", "remote", "mouse", "book",
"scissors", "toothbrush", "hair drier", "sports ball", "frisbee", "umbrella", "handbag", "backpack",
"laptop", "keyboard", "clock", "vase", "kite", "tennis racket", "baseball bat", "baseball glove"}
# classes a person may hold; a "teddy bear" was an arm with a clear cup (2026-10-20)
RAISED = 0.25 # wrist above the shoulder by this part of the torso length -> hand raised
POINT_ANGLE = 150.0 # deg; elbow straighter than this ...
POINT_LOW = 0.5 # ... and wrist above this part of the torso (an arm hanging out with a cup is not)
POINT_REACH = 0.8 # ... and wrist this far from the shoulder (x torso length, in the picture) -> pointing
POINT_STEP_PX, POINT_RAY_MM = 4, 120 # the pointing ray is followed in px steps; a depth point this close to it is hit
POINT_MIN_MM = 250 # mm past the hand before a hit counts (not the hand itself)
CHEST = 0.5 # the shirt colour is taken from this top part of shoulders -> hips
CLOTH_DEPTH_MM = 250 # mm; shirt pixels are this close to the chest depth (the room behind stays out)
CLOTH_MIN_PX = 60 # px; fewer clothes pixels in view than this: can't tell
THIGH = (0.1, 0.6) # the trousers colour from this part of hip -> knee (shorts and skirts cover it too)
LEG_W = 0.35 # thigh band width as a part of the hip keypoint distance
FOOT = (0.05, 0.35) # the shoe: this part of the shin length past the ankle, away from the knee
FOOT_W = 0.3 # shoe band width as a part of the shin length
WHITE_VS_SKIN = 1.2 # "grey" clothes this much brighter than the face are white in shade or against a
# bright window (a white shirt read V 107 by a nose at 70, 2026-10-21)
VLM_MODEL = "gemma4:26b" # multimodal; the conversation model, already loaded
VLM_URL = "http://127.0.0.1:11434/api/chat"
VLM_WIDTH = 448 # px; the picture sent (5 s on a quiet GPU, 20+ s while other LLM work runs)
VLM_TIMEOUT_S = 12.0
VLM_PROMPT = ("You are the eyes of a service robot. Look at the picture and answer the question in one short spoken "
"sentence in {lang}. Say only what is clearly visible. If it is not clearly visible, say that you "
"can't tell. Question: {q}")
_det_lock = threading.RLock()
_det = {"net": None}
# ---------- frames ----------
def _transform(camera, d):
if camera == "torso":
return objects.base_from_camera()
if d.get("head_pose"):
from vision import head_cam
return head_cam.base_from_head(*d["head_pose"][2:])
return None
def snapshot(cameras=CAMERAS):
"""[{camera, color, depth (mm uint16 or None), people, objects, head_yaw, intr, T}] of the cameras now."""
for c in cameras:
camview.want(c) # wakes an idle camera service to full speed
frames = []
for c in cameras:
end = time.time() + WAIT_S
while True:
try:
d = json.loads(camview.det_path(c).read_text())
except (FileNotFoundError, ValueError):
d = None
if (d and time.time() - d["time"] < FRESH_S) or time.time() > end:
break
time.sleep(0.05)
color = cv2.imread(str(camview.raw_path(c)))
if d is None or color is None or time.time() - d["time"] > FRESH_S:
continue
frames.append({"camera": c, "color": color, "depth": camview.depth(c, DEPTH_AGE_S), "people": d["people"],
"objects": d["objects"], "head_yaw": d.get("head_yaw") or 0.0,
"intr": camview.intrinsics(c), "T": _transform(c, d)})
return frames
def save(prefix, frames):
"""Frames -> <prefix>_<camera>.jpg / .npz (depth) / .json, a test fixture."""
for f in frames:
p = f"{prefix}_{f['camera']}"
cv2.imwrite(p + ".jpg", f["color"], [cv2.IMWRITE_JPEG_QUALITY, 92])
if f["depth"] is not None:
np.savez_compressed(p + ".npz", depth=f["depth"].astype(np.uint16))
meta = {k: f[k] for k in ("camera", "people", "objects", "head_yaw", "intr")}
meta["T"] = None if f["T"] is None else np.asarray(f["T"]).tolist()
Path(p + ".json").write_text(json.dumps(meta))
def load(prefix):
"""The frames save() wrote."""
frames = []
for c in CAMERAS:
p = f"{prefix}_{c}"
if not Path(p + ".json").exists():
continue
f = json.loads(Path(p + ".json").read_text())
f["color"] = cv2.imread(p + ".jpg")
f["depth"] = np.load(p + ".npz")["depth"] if Path(p + ".npz").exists() else None
f["T"] = None if f["T"] is None else np.array(f["T"])
frames.append(f)
return frames
# ---------- geometry ----------
def _bearing(f, x):
"""Angle (deg) of image column x from the waist forward axis, + = robot's left (as person.py)."""
w = f["color"].shape[1]
return round(-(x - w / 2) / (w / 2) * (person.COLOR_HFOV / 2) + f["head_yaw"], 1)
def where(bearing):
if bearing is None:
return None
return "on my left" if bearing > SIDE_DEG else "on my right" if bearing < -SIDE_DEG else "in front of me"
def _depth_at(f, x, y, r=DEPTH_R, pct=50):
"""Depth (mm) around a pixel: the median, or a lower percentile for a thin thing before the room (a wrist)."""
d = f["depth"]
if d is None:
return None
h, w = d.shape
x, y = int(round(x)), int(round(y))
patch = d[max(0, y - r):min(h, y + r + 1), max(0, x - r):min(w, x + r + 1)]
v = patch[patch > 0]
return float(np.percentile(v, pct)) if v.size >= 5 else None
def _to_base(f, x, y, z):
"""Pixel + depth (mm) -> arm base frame point (mm, numpy), or None without calibration."""
if f["T"] is None or f["intr"] is None or z is None:
return None
i = f["intr"]
K = np.array([[i["fx"], 0, i["cx"]], [0, i["fy"], i["cy"]], [0, 0, 1]])
n = cv2.undistortPoints(np.array([[[x, y]]], np.float64), K, np.array(i["dist"])).reshape(2)
T = np.asarray(f["T"])
return T[:3, :3] @ np.array([n[0] * z, n[1] * z, z]) + T[:3, 3]
def _mm(p):
return None if p is None else [round(float(v)) for v in p]
# ---------- things in view ----------
def _same(a, b):
if a["name"] != b["name"]:
return False
if a.get("position_mm") and b.get("position_mm") and None not in a["position_mm"][:2] + b["position_mm"][:2]:
return np.hypot(*np.subtract(a["position_mm"][:2], b["position_mm"][:2])) < SAME_MM
return abs(a["bearing_deg"] - b["bearing_deg"]) < SAME_DEG and \
abs((a["distance_m"] or 0) - (b["distance_m"] or 0)) < SAME_M
def own_body(f, o):
"""True for a box that is the robot itself: its shoulder in the head camera, its arm in the torso camera."""
x1, y1, x2, y2 = o["box"]
edge = OWN_EDGE[f["camera"]]
at_edge = y2 >= f["color"].shape[0] - EDGE_PX if edge == "bottom" else y1 <= EDGE_PX
return at_edge and (o.get("distance_m") is None or o["distance_m"] < SELF_M)
def things(frames=None):
"""Everything detected (not people), both cameras, the same thing seen twice kept once, nearest first."""
frames = snapshot() if frames is None else frames
out = []
for f in frames:
for o in f["objects"]:
if own_body(f, o):
continue
t = {"name": o["name"], "colour": o.get("colour"), "distance_m": o.get("distance_m"),
"bearing_deg": _bearing(f, (o["box"][0] + o["box"][2]) / 2), "camera": f["camera"],
"position_mm": o.get("position_mm"), "score": o.get("score"), "box": o["box"]}
t["where"] = where(t["bearing_deg"])
twin = next((u for u in out if _same(u, t)), None)
if twin is None:
out.append(t)
elif (t["score"] or 0) > (twin["score"] or 0):
out[out.index(twin)] = t
out.sort(key=lambda t: t["distance_m"] or 99)
return out
def sees(name=None, colour=None, frames=None):
"""Things of this COCO class (None: any) and colour (None: any; white and grey count as one) seen now."""
return [t for t in things(frames) if (name is None or t["name"] == name)
and objects.same_colour(colour, t["colour"])]
def _same_deg(d):
"""Angle (deg) within which the two cameras' views of one thing d m away fall."""
return SAME_DEG + (np.degrees(np.arctan(CAMS_APART_M / d)) if d else 0.0)
def people(frames=None):
"""Everyone in view, the two cameras merged: [{distance_m, bearing_deg, camera}] nearest first."""
frames = snapshot() if frames is None else frames
out = []
for f in frames:
for p in f["people"]:
q = {"distance_m": p.get("distance_m"), "bearing_deg": p["angle_deg"], "camera": f["camera"]}
if not any(abs(u["bearing_deg"] - q["bearing_deg"]) < _same_deg(u["distance_m"] or q["distance_m"]) and
(u["distance_m"] is None or q["distance_m"] is None or
abs(u["distance_m"] - q["distance_m"]) < SAME_M) for u in out):
out.append(q)
out.sort(key=lambda p: p["distance_m"] or 99)
return out
# ---------- the person in front ----------
def _box_net():
with _det_lock:
if _det["net"] is None:
_det["net"] = person.load_net()
return _det["net"]
def _hand_boxes(f, cx, cy):
"""Object boxes (x1, y1, x2, y2, score, cls) found by a second, zoomed look at the square around a hand."""
img = f["color"]
h, w = img.shape[:2]
s = HAND_CROP_PX // 2
x1, y1 = int(max(0, min(w - 2 * s, cx - s))), int(max(0, min(h - 2 * s, cy - s)))
with _det_lock:
boxes = person.detect_boxes(_box_net(), img[y1:y1 + 2 * s, x1:x1 + 2 * s])
return [(a + x1, b + y1, c + x1, d + y1, sc, cl) for a, b, c, d, sc, cl in boxes]
def _held(f, kp, side, body_h):
"""{position_mm, distance_m, object} for one hand, or None when the wrist is not seen."""
wr, el = pose.seen(kp, f"{side}_wrist"), pose.seen(kp, f"{side}_elbow")
if wr is None:
return None
if el is not None:
fore = np.subtract(wr, el)
cx, cy = np.add(wr, HAND_REACH * fore)
r = max(HAND_R * float(np.hypot(*fore)), 0.04 * body_h)
else:
(cx, cy), r = wr, 0.08 * body_h
z = _depth_at(f, *wr, r=2 * DEPTH_R, pct=WRIST_PCT)
hand = {"position_mm": _mm(_to_base(f, wr[0], wr[1], z)), "distance_m": None if z is None else round(z / 1000, 2),
"object": None}
boxes = [(*o["box"], o.get("score") or 0, objects.COCO.index(o["name"])) for o in f["objects"]
if not own_body(f, o)]
best = None
for x1, y1, x2, y2, score, cls in boxes + _hand_boxes(f, cx, cy):
name = objects.COCO[cls]
if name not in HANDHELD:
continue
gap = np.hypot(max(x1 - cx, 0, cx - x2), max(y1 - cy, 0, cy - y2)) # hand centre to the box, px
if f["depth"] is None: # no depth to tell before / behind: the box must be on
gap = np.hypot((x1 + x2) / 2 - cx, (y1 + y2) / 2 - cy) / NO_DEPTH_R # the hand, not touch its region
if gap > r:
continue
m = objects.measure(f["color"], f["depth"], (x1, y1, x2, y2), f["intr"], f["T"], round_=name in objects.ROUND) \
if f["depth"] is not None else {"colour": objects.colour_name(f["color"][y1:y2, x1:x2].reshape(-1, 3)),
"distance_m": None, "position_mm": None, "width_mm": None}
if f["depth"] is not None and (z is None or m["distance_m"] is None or
abs(m["distance_m"] - z / 1000) > HAND_DEPTH_M):
continue # behind or before the hand: not in it
o = {"name": name, "colour": m["colour"], "score": round(float(score), 2), "box": (x1, y1, x2, y2),
"distance_m": m["distance_m"], "position_mm": m.get("position_mm"), "width_mm": m.get("width_mm")}
if best is None or (gap, -score) < best[0]:
best = ((gap, -score), o)
hand["object"] = best[1] if best else None
return hand
def _named(f, mask, ref_z=None, skin_v=None):
"""Colour name of the pixels in mask, or None (too few). Depth near ref_z (default: their own median) keeps the
room out; objects.colour_name takes the main hue (a logo or a bit of floor does not move it). skin_v: the face's
brightness (HSV V, median), which tells a white shirt in poor light from a grey one."""
if mask.sum() < CLOTH_MIN_PX:
return None
px = f["color"][mask]
if f["depth"] is not None:
d = f["depth"][mask].astype(np.float32)
ref = ref_z if ref_z is not None else (np.median(d[d > 0]) if (d > 0).any() else None)
keep = (d > 0) & (np.abs(d - ref) < CLOTH_DEPTH_MM) if ref is not None else d > 0
if keep.sum() > 50:
px = px[keep]
name = objects.colour_name(px)
# ponytail: one skin reference, so a light grey shirt over dark skin may read white; a second reference if so
return "white" if name == "grey" and skin_v and np.median(px.max(axis=1)) >= WHITE_VS_SKIN * skin_v else name
def _clothes(f, kp, chest_z):
"""{upper, lower, feet}: the colour of the shirt (shoulders -> hips), the trousers (hips -> knees) and the shoes
(past the ankles, away from the knees); None for a part not in the picture (a keypoint outside the frame is
not seen: the pose model places ankles below the frame edge)."""
h, w = f["color"].shape[:2]
def at(n):
p = pose.seen(kp, n)
return np.array(p) if p and 0 <= p[0] < w and 0 <= p[1] < h else None
def band(a, b, t0, t1, width): # mask of a thick line along a -> b, from t0 to t1
m = np.zeros((h, w), np.uint8)
cv2.line(m, tuple(int(v) for v in a + t0 * (b - a)), tuple(int(v) for v in a + t1 * (b - a)), 1,
max(4, int(width)))
return m.astype(bool)
out = {"upper": None, "lower": None, "feet": None}
nose, eye = at("nose"), at("left_eye") if at("left_eye") is not None else at("right_eye")
skin_v = None
if nose is not None:
r = max(4, int(0.4 * np.linalg.norm(eye - nose))) if eye is not None else 6
x, y = int(nose[0]), int(nose[1])
patch = f["color"][max(0, y - r):y + r, max(0, x - r):x + r]
skin_v = float(np.median(patch.max(axis=2))) if patch.size else None
sh, hip = [at(f"{s}_shoulder") for s in ("left", "right")], [at(f"{s}_hip") for s in ("left", "right")]
if all(p is not None for p in sh):
xs, y1 = [p[0] for p in sh], max(p[1] for p in sh)
if all(p is not None for p in hip): # the chest: the arms hang over the belly side on
y2 = y1 + CHEST * (min(p[1] for p in hip) - y1)
else:
y2 = y1 + 1.2 * abs(xs[0] - xs[1]) # no hips in view: a shoulder width and a bit down
inset = 0.15 * abs(xs[0] - xs[1])
x1, x2 = int(max(0, min(xs) + inset)), int(min(w, max(xs) - inset))
y1, y2 = int(max(0, y1 + 0.1 * (y2 - y1))), int(min(h, y2 - 0.1 * (y2 - y1)))
if x2 - x1 >= 8 and y2 - y1 >= 8:
m = np.zeros((h, w), bool)
m[y1:y2, x1:x2] = True
out["upper"] = _named(f, m, chest_z, skin_v)
hip_w = np.linalg.norm(hip[0] - hip[1]) if all(p is not None for p in hip) else None
legs, feet = np.zeros((h, w), bool), np.zeros((h, w), bool)
for s, hp in zip(("left", "right"), hip):
knee, ankle = at(f"{s}_knee"), at(f"{s}_ankle")
if hp is not None and knee is not None: # the thigh: trousers, shorts and skirts all cover it
legs |= band(hp, knee, *THIGH, LEG_W * (hip_w or np.linalg.norm(knee - hp) / 2))
if knee is not None and ankle is not None:
end = ankle + FOOT[1] * (ankle - knee)
if 0 <= end[0] < w and 0 <= end[1] < h: # the whole shoe in the picture
feet |= band(knee, ankle, 1 + FOOT[0], 1 + FOOT[1], FOOT_W * np.linalg.norm(ankle - knee))
out["lower"] = _named(f, legs, None, skin_v) if legs.any() else None
out["feet"] = _named(f, feet, None, skin_v) if feet.any() else None
return out
def _angle(a, b, c):
"""Angle at b (deg) of a-b-c in the picture."""
v1, v2 = np.subtract(a, b), np.subtract(c, b)
cos = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2) or 1)
return float(np.degrees(np.arccos(np.clip(cos, -1, 1))))
def _gesture(kp):
"""(raised: [sides], pointing: side or None) from the keypoints of one picture."""
sh = {s: pose.seen(kp, f"{s}_shoulder") for s in ("left", "right")}
hips = [pose.seen(kp, f"{s}_hip") for s in ("left", "right")]
known = [p for p in sh.values() if p]
if not known:
return [], None
shoulder_y = np.mean([p[1] for p in known])
if all(hips) and all(sh.values()):
torso = abs(np.mean([p[1] for p in hips]) - shoulder_y)
elif all(sh.values()):
torso = 1.5 * abs(sh["left"][0] - sh["right"][0])
else:
torso = None
raised, pointing = [], None
for s in ("left", "right"):
wr, el = pose.seen(kp, f"{s}_wrist"), pose.seen(kp, f"{s}_elbow")
if wr is None or sh[s] is None or not torso:
continue
if wr[1] < sh[s][1] - RAISED * torso:
raised.append(s)
elif el is not None and wr[1] < shoulder_y + POINT_LOW * torso and _angle(sh[s], el, wr) > POINT_ANGLE and \
np.hypot(*np.subtract(wr, sh[s])) > POINT_REACH * torso:
pointing = s
return raised, pointing
def _facing(kp):
eyes = [pose.seen(kp, n) for n in ("left_eye", "right_eye")]
if all(eyes) and pose.seen(kp, "nose"):
return True
if any(eyes) or pose.seen(kp, "left_shoulder") or pose.seen(kp, "right_shoulder"):
return False # side on, or the back turned
return None
def _describe_person(f, p):
kp, (x1, y1, x2, y2) = p["kp"], p["box"]
body_h = y2 - y1
sh = [pose.seen(kp, n) for n in ("left_shoulder", "right_shoulder")]
chest = tuple(np.mean([s for s in sh if s], axis=0)) if any(sh) else ((x1 + x2) / 2, y1 + 0.3 * body_h)
hips = [pose.seen(kp, n) for n in ("left_hip", "right_hip")]
if any(sh) and any(hips): # a bit below the shoulders: the chest
chest = (chest[0], chest[1] + 0.3 * (np.mean([h[1] for h in hips if h]) - chest[1]))
z = _depth_at(f, *chest, r=3 * DEPTH_R)
raised, pointing = _gesture(kp)
hands = {s: _held(f, kp, s, body_h) for s in ("left", "right")}
out = {"camera": f["camera"], "box": p["box"], "distance_m": None if z is None else round(z / 1000, 2),
"bearing_deg": _bearing(f, chest[0]), "position_mm": _mm(_to_base(f, chest[0], chest[1], z)),
"facing": _facing(kp), "raised": raised, "pointing": pointing,
"gesture": "hand_raised" if raised else "pointing" if pointing else None,
"clothes": _clothes(f, kp, z),
"hands": hands, "seen": int((kp[:, 2] > pose.KP_SEEN).sum()), "_f": f, "_kp": kp}
out["where"] = where(out["bearing_deg"])
if out["distance_m"] is None: # no depth there: the camera service's distance
near = [q for q in f["people"] if abs(q["angle_deg"] - out["bearing_deg"]) < SAME_DEG]
if near:
out["distance_m"] = near[0]["distance_m"]
return out
def _depth_fits(f):
"""False when the depth frame is from another moment than the people found (depth is written every 0.5 s): a
person's distance measured with the picture differs from the depth there now."""
if f["depth"] is None:
return False
for p in f["people"]:
if p.get("distance_m") and p.get("distance_src", "depth") == "depth":
x1, y1, x2, y2 = p["box"]
z = _depth_at(f, (x1 + x2) / 2, y1 + (y2 - y1) * 3 / 8, r=max(4, (x2 - x1) // 6))
if z is None or abs(z / 1000 - p["distance_m"]) > STALE_DEPTH_M:
return False
return True
def _persons(frames):
"""Every person the pose model finds, described, nearest first (the cameras not merged)."""
out = []
for f in frames:
if not f["people"]: # the camera service saw nobody: skip the pose run
continue
if not _depth_fits(f): # someone moved since the depth frame: go without it
f = {**f, "depth": None}
out += [_describe_person(f, p) for p in pose.detect(f["color"])]
out.sort(key=lambda p: (p["distance_m"] or 99, -p["seen"]))
return out
def _public(p):
return {k: v for k, v in p.items() if not k.startswith("_")}
def _front(frames):
"""The nearest person within FRONT_M, the other camera's view of the same person filling in the hands."""
persons = [p for p in _persons(frames) if p["distance_m"] is None or p["distance_m"] <= FRONT_M]
if not persons:
return None
me = persons[0]
for other in persons[1:]: # the same person in the other camera
if other["camera"] == me["camera"] or abs(other["bearing_deg"] - me["bearing_deg"]) > _same_deg(me["distance_m"]):
continue
for s in ("left", "right"):
mine, theirs = me["hands"][s], other["hands"][s]
if theirs and (mine is None or (mine["object"] is None and theirs["object"] is not None)):
me["hands"][s] = theirs
for k in ("upper", "lower", "feet"):
me["clothes"][k] = me["clothes"][k] or other["clothes"][k]
if me["facing"] is None:
me["facing"] = other["facing"]
return me
def person_in_front(frames=None):
"""The person nearest in front (see the module docstring), or None when nobody is within FRONT_M."""
p = _front(snapshot() if frames is None else frames)
return _public(p) if p else None
def object_in_hand(frames=None):
"""What the person in front holds: {name, colour, hand, position_mm, distance_m, width_mm} or None."""
p = _front(snapshot() if frames is None else frames)
if p is None:
return None
for s in ("right", "left"):
h = p["hands"][s]
if h and h["object"]:
o = h["object"]
return {"name": o["name"], "colour": o["colour"], "hand": s, "position_mm": o["position_mm"],
"distance_m": o["distance_m"], "width_mm": o["width_mm"]}
return None
def person_holds(object=None, frames=None):
"""True: a thing (of this COCO class) is in a hand. False: no such thing in the hands seen. None: can't tell
(nobody in front, or no hand in view)."""
p = _front(snapshot() if frames is None else frames)
if p is None:
return None
hands = [h for h in p["hands"].values() if h]
if any(h["object"] and (object is None or h["object"]["name"] == object) for h in hands):
return True
if any(h["object"] for h in hands):
return False # something else is in a hand
return False if hands and all(h["distance_m"] is not None for h in hands) else None # empty only with depth
def pointing_target(frames=None):
"""Where the person in front points: the first depth point along the shoulder -> wrist line past the hand,
{"position_mm", "distance_m"} or None (not pointing, no depth, nothing hit in the picture)."""
p = _front(snapshot() if frames is None else frames)
if p is None or not p["pointing"]:
return None
f, kp, s = p["_f"], p["_kp"], p["pointing"]
if f["depth"] is None:
return None
sh, wr = pose.seen(kp, f"{s}_shoulder"), pose.seen(kp, f"{s}_wrist")
A, B = _to_base(f, *sh, _depth_at(f, *sh)), _to_base(f, *wr, _depth_at(f, *wr))
if A is None or B is None or np.linalg.norm(B - A) < 1:
return None
ray = (B - A) / np.linalg.norm(B - A)
step = np.subtract(wr, sh)
step = step / (np.linalg.norm(step) or 1) * POINT_STEP_PX
h, w = f["depth"].shape
x, y = wr
while 0 <= x < w and 0 <= y < h:
x, y = x + step[0], y + step[1]
z = f["depth"][int(min(h - 1, max(0, y))), int(min(w - 1, max(0, x)))]
if not z:
continue
P = _to_base(f, x, y, float(z))
along = np.dot(P - B, ray)
if along > POINT_MIN_MM and np.linalg.norm(P - B - along * ray) < POINT_RAY_MM:
return {"position_mm": _mm(P), "distance_m": round(float(z) / 1000, 2)}
return None
# ---------- open questions: the VLM ----------
def ask_vlm(question, lang="en", frames=None):
"""One sentence about the person in front (or the whole head view when nobody is there) from gemma4 with the
picture, or None on a timeout / error. Slow: use it only for what detections can't answer (glasses, a hat...)."""
frames = snapshot() if frames is None else frames
if not frames:
return None
p = _front(frames)
if p is not None:
f, (x1, y1, x2, y2) = p["_f"], p["box"]
mx, my = (x2 - x1) // 6, (y2 - y1) // 10
img = f["color"][max(0, y1 - my):y2 + my, max(0, x1 - mx):x2 + mx]
else:
img = next((f for f in frames if f["camera"] == "head"), frames[0])["color"]
img = cv2.resize(img, (VLM_WIDTH, max(1, int(img.shape[0] * VLM_WIDTH / img.shape[1]))))
b64 = base64.b64encode(cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 85])[1]).decode()
body = {"model": VLM_MODEL, "stream": False, "think": False, "keep_alive": -1,
"options": {"temperature": 0, "num_predict": 60},
"messages": [{"role": "user", "images": [b64],
"content": VLM_PROMPT.format(lang="Korean" if lang == "ko" else "English", q=question)}]}
try:
req = urllib.request.Request(VLM_URL, json.dumps(body).encode(), {"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=VLM_TIMEOUT_S) as r:
return json.loads(r.read())["message"]["content"].strip() or None
except Exception as e:
print(f"scene: VLM gave no answer ({e})", flush=True)
return None
def _print(frames):
t = time.time()
p = person_in_front(frames)
print(f"person in front ({1000 * (time.time() - t):.0f} ms):", json.dumps(p, default=str))
print("in hand:", object_in_hand(frames), " holds:", person_holds(None, frames), " points at:", pointing_target(frames))
print("people:", people(frames))
for o in things(frames):
print(f" {o['name']:12s} {o['colour'] or '?':7s} {o['distance_m']} m {o['where']} ({o['camera']}, {o['score']})")
if __name__ == "__main__":
if "--save" in sys.argv:
save(sys.argv[sys.argv.index("--save") + 1], snapshot())
elif "--load" in sys.argv:
_print(load(sys.argv[sys.argv.index("--load") + 1]))
else:
_print(snapshot())
+30
View File
@@ -0,0 +1,30 @@
"""Build the TensorRT engine that vision/person.py runs on the GPU, from an ONNX model. Run it on this Thor after a
JetPack or TensorRT change (an engine only works with the TensorRT version and GPU it was built with):
.venv/bin/python vision/yolo_engine.py models/yolov8s.onnx models/yolov8s.engine # about 100 s
"""
import sys
import tensorrt as trt
def build(onnx_path, engine_path):
logger = trt.Logger(trt.Logger.WARNING)
builder = trt.Builder(logger)
net = builder.create_network(0)
parser = trt.OnnxParser(net, logger)
if not parser.parse(open(onnx_path, "rb").read()):
for i in range(parser.num_errors):
print("parse error:", parser.get_error(i))
raise SystemExit(1)
engine = builder.build_serialized_network(net, builder.create_builder_config())
if engine is None:
raise SystemExit("engine not built")
open(engine_path, "wb").write(engine)
print("wrote", engine_path)
if __name__ == "__main__":
if len(sys.argv) != 3:
sys.exit(__doc__)
build(sys.argv[1], sys.argv[2])