Recover the arm from any pose, put down on a remembered table and wave back at people

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 18:22:46 +09:00
co-authored by Claude Opus 5.5
parent b4ab7c71b1
commit eb8975ff6e
25 changed files with 1613 additions and 108 deletions
+116
View File
@@ -0,0 +1,116 @@
"""Record people's keypoints from the head camera while Lumi reads out what to do: the waves (and the non-waves) the
wave greeting is tuned and tested on. Moves nothing; Lumi only speaks (POST /say).
python vision/wave_record.py [first_step] # writes tests/data/waves/<label>.jsonl and <label>/<n>.jpg
One line per frame: {t, n, people: [{box, kp (17 x [x, y, conf]), dist_m}]}; frame n at half size (640 x 360), for the
hand's own motion (the keypoints have no fingers: a wave from the wrist hardly moves the wrist keypoint). People in
the pictures: tests/data/waves/ stays local (.gitignore).
"""
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, pose
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "tests" / "data" / "waves"
CAM = "head"
READY_S = 5 # from the instruction to "Go": time to walk to the distance
# (label, what Lumi says, seconds recorded)
STEPS = [
("right_1m", "Stand one metre in front of me. Wave with your right hand.", 8),
("left_1m", "Now wave with your left hand.", 8),
("right_2m", "Step back to two metres. Wave with your right hand.", 8),
("left_2m", "Now your left hand.", 8),
("right_3m", "Step back to three metres. Wave with your right hand.", 8),
("left_3m", "Now your left hand.", 8),
("slow_2m", "Come to two metres. Wave slowly.", 8),
("fast_2m", "Now wave fast.", 8),
("pause_2m", "Wave, stop for three seconds when I say pause, then wave again.", 12),
("edge_left", "Go to the far left of my view and wave.", 8),
("edge_right", "Now the far right of my view, and wave.", 8),
("walk_wave", "Walk past me from one side to the other, waving.", 10),
("no_raised", "Two metres in front of me. Hold one hand up, still, like asking a question.", 6),
("no_scratch", "Scratch your head.", 6),
("no_phone", "Hold a phone to your ear and talk.", 6),
("no_point", "Point at something, then at another thing.", 6),
("no_glasses", "Touch your face or fix your hair.", 6),
("no_walk", "Walk past me from one side to the other, swinging your arms, no wave.", 10),
("no_still", "Just stand still.", 6),
]
def say(text):
req = urllib.request.Request("http://localhost:8100/say", json.dumps({"text": text}).encode(),
{"Content-Type": "application/json"})
try:
urllib.request.urlopen(req, timeout=30).read()
except OSError as e:
print(f"say failed ({e}): {text}", flush=True)
def dist_m(depth, kp):
"""Median head-camera depth around the shoulders' middle, m; None without depth."""
ls, rs = pose.seen(kp, "left_shoulder"), pose.seen(kp, "right_shoulder")
if depth is None or not (ls and rs):
return None
x, y = int((ls[0] + rs[0]) / 2), int((ls[1] + rs[1]) / 2)
patch = depth[max(0, y - 6):y + 7, max(0, x - 6):x + 7]
v = patch[patch > 0]
return round(float(np.median(v)) / 1000, 2) if v.size >= 5 else None
def record(label, seconds, pause_at=None):
raw = camview.raw_path(CAM)
last, n = 0.0, 0
(OUT / label).mkdir(exist_ok=True)
t_end = time.time() + seconds
with open(OUT / f"{label}.jsonl", "w") as f:
while time.time() < t_end:
camview.want(CAM)
if pause_at and time.time() > t_end - seconds + pause_at: # spoken aside, the frames keep coming
threading.Thread(target=lambda: (say("Pause."), time.sleep(3), say("Wave again.")), daemon=True).start()
pause_at = None
try:
m = raw.stat().st_mtime
except FileNotFoundError:
m = last
if m == last:
time.sleep(0.01)
continue
last = m
img = cv2.imread(str(raw))
if img is None:
continue
depth = camview.depth(CAM)
people = [{"box": p["box"], "kp": np.round(p["kp"].astype(float), 1).tolist(), "dist_m": dist_m(depth, p["kp"])}
for p in pose.detect(img)]
f.write(json.dumps({"t": round(m, 3), "n": n, "people": people}) + "\n")
cv2.imwrite(str(OUT / label / f"{n:04d}.jpg"), cv2.resize(img, (640, 360)), [cv2.IMWRITE_JPEG_QUALITY, 90])
n += 1
print(f"{label}: {n} frames, {n / seconds:.1f} per s", flush=True)
if __name__ == "__main__":
OUT.mkdir(parents=True, exist_ok=True)
pose.load()
first = sys.argv[1] if len(sys.argv) > 1 else STEPS[0][0]
steps = STEPS[[s[0] for s in STEPS].index(first):]
say("Let's record waves. Do what I say after I say go.")
for label, text, seconds in steps:
print(f"-- {label}", flush=True)
say(text)
time.sleep(READY_S)
say("Go.")
record(label, seconds, pause_at=4 if label == "pause_2m" else None)
say("Stop.")
time.sleep(1)
say("All done, thank you.")
+122
View File
@@ -0,0 +1,122 @@
"""Who is waving: a raised hand that moves side to side, back and forth, from the head camera.
The pose keypoints have no fingers, and a wave from the wrist hardly moves the wrist keypoint (a few px), so the hand
itself is measured: the sideways optical flow in a box over the palm (past the wrist, along the forearm), frame to
frame. A wave is that flow changing direction MIN_FLIPS times within WINDOW_S with the hand above the shoulder and
away from the head. A hand held up still, pointing or arms swinging while walking give no flips; a scratch, a phone
at the ear or a hand at the face move at the head (AT_HEAD) and do not count.
python vision/waving.py tests/data/waves/right_2m # a recording of vision/wave_record.py, frame by frame
Frames are taken at half size (640 x 360, as recorded); keypoints are full size (1280 x 720, pose.detect).
"""
import sys
from pathlib import Path
import cv2
import numpy as np
from vision import pose
SCALE = 0.5 # flow frame size / pose frame size
WINDOW_S = 2.0 # s of flow looked at ...
MIN_FLIPS = 2 # ... that has to change direction this often (a slow wave: one swing ~1 s)
FLOW_PX = 1.0 # px per frame (half size) of sideways hand flow that counts as a swing
MIN_MOVING = 20 # flow pixels in the hand box needed to measure the hand at all
PALM = 0.5 # the palm's centre: this much of the forearm past the wrist
BOX = 0.6 # half the hand box's side, in forearm lengths
MIN_BOX_PX = 8 # ... at least (half size)
AT_HEAD = 0.3 # shoulder widths: a palm this near the face or ears is at the head (scratching, a phone,
# glasses, hair; recorded 0.07-0.32), not waving (recorded waves 0.36 and more)
TRACK_PX = 120 # px (full size); a person's shoulder centre moves less than this between frames
LOST_S = 1.0 # s a person may be unseen before their history is dropped
def _hand(kp):
"""(centre (x, y) half size, half side px) of the higher raised hand away from the head, None when there is
none."""
best = None
ls, rs = pose.seen(kp, "left_shoulder"), pose.seen(kp, "right_shoulder")
face = [p for p in (pose.seen(kp, n) for n in ("nose", "left_eye", "right_eye", "left_ear", "right_ear")) if p]
if not (ls and rs):
return None
near = AT_HEAD * np.hypot(ls[0] - rs[0], ls[1] - rs[1])
for side in ("left", "right"):
w, e, s = (pose.seen(kp, f"{side}_{j}") for j in ("wrist", "elbow", "shoulder"))
if not (w and e and s) or w[1] >= s[1]:
continue
fx, fy = w[0] - e[0], w[1] - e[1]
palm = (w[0] + PALM * fx, w[1] + PALM * fy)
if any(np.hypot(palm[0] - f[0], palm[1] - f[1]) < near for f in face):
continue
c = (palm[0] * SCALE, palm[1] * SCALE)
r = max(MIN_BOX_PX, BOX * np.hypot(fx, fy) * SCALE)
if best is None or c[1] < best[0][1]:
best = (c, r)
return best
def _flow_x(prev, gray, hand):
"""Median sideways flow (px) of the moving pixels in the hand box, 0 when too little moves there."""
(cx, cy), r = hand
x0, y0, x1, y1 = int(max(0, cx - r)), int(max(0, cy - r)), int(cx + r), int(cy + r)
a, b = prev[y0:y1, x0:x1], gray[y0:y1, x0:x1]
if min(a.shape) < 8:
return 0.0
fx = cv2.calcOpticalFlowFarneback(a, b, None, 0.5, 2, 9, 3, 5, 1.1, 0)[..., 0]
moving = np.abs(fx) > FLOW_PX / 2
return float(np.median(fx[moving])) if moving.sum() >= MIN_MOVING else 0.0
def _flips(flows):
s = np.sign([f for f in flows if abs(f) > FLOW_PX])
return int((np.diff(s) != 0).sum()) if len(s) > 1 else 0
class Watcher:
"""Feed it every frame (update); it keeps a short flow history per person."""
def __init__(self):
self.prev = None
self.tracks = [] # {"at": (x, y) shoulder centre full size, "seen": t, "flows": [(t, flow)]}
def update(self, t, gray, people):
"""`gray`: the frame at half size, grey; `people`: pose.detect of the full-size frame. Returns
[(person, waving)] for every person seen, in that order."""
out = []
for p in people:
ls, rs = pose.seen(p["kp"], "left_shoulder"), pose.seen(p["kp"], "right_shoulder")
if not (ls and rs):
out.append((p, False))
continue
at = ((ls[0] + rs[0]) / 2, (ls[1] + rs[1]) / 2)
tr = min(self.tracks, key=lambda k: np.hypot(k["at"][0] - at[0], k["at"][1] - at[1]), default=None)
if tr is None or np.hypot(tr["at"][0] - at[0], tr["at"][1] - at[1]) > TRACK_PX or tr["seen"] == t:
tr = {"flows": []}
self.tracks.append(tr)
tr["at"], tr["seen"] = at, t
hand = _hand(p["kp"])
f = _flow_x(self.prev, gray, hand) if hand and self.prev is not None else 0.0
tr["flows"] = [(ft, v) for ft, v in tr["flows"] if t - ft <= WINDOW_S] + [(t, f)]
out.append((p, hand is not None and _flips([v for _, v in tr["flows"]]) >= MIN_FLIPS))
self.tracks = [k for k in self.tracks if t - k["seen"] <= LOST_S]
self.prev = gray
return out
def run_recording(folder):
"""[(t, [waving per person])] of a vision/wave_record.py recording."""
import json
folder = Path(folder)
w, out = Watcher(), []
for line in open(folder.with_suffix(".jsonl")):
d = json.loads(line)
gray = cv2.imread(str(folder / f"{d['n']:04d}.jpg"), cv2.IMREAD_GRAYSCALE)
people = [{**p, "kp": np.array(p["kp"])} for p in d["people"]]
out.append((d["t"], [v for _, v in w.update(d["t"], gray, people)]))
return out
if __name__ == "__main__":
for t, waving in run_recording(sys.argv[1]):
print(f"{t:.2f}", waving)