diff --git a/assistant/lumi.py b/assistant/lumi.py index dac0e56..03ec99e 100644 --- a/assistant/lumi.py +++ b/assistant/lumi.py @@ -493,8 +493,8 @@ COME_TIMEOUT = 60.0 # s MAX_MOVE_M = 3.0 # m; "move forward N metres" is limited to this REACH_COME_M = 1.5 # m; a person further than this is driven to first (come_to, COME_STOP), the hand is # never held out from afar (owner, 2026-10-28) -HOME_WAIST_DEG = 85.8 # deg (+ left) from the front the waist rests at on the charger (owner's pose, - # 2026-11-04: body waist 65.5 deg); every drive turns it back to the front first +HOME_WAIST_DEG = 0.0 # deg (+ left) from the front the waist rests at on the charger (owner: the front, + # the robot stands facing the people); every drive turns it back to the front first IDLE_AFTER_S = 15.0 # s without a word to Lumi on the charger before the wave greeting waves now and then # (tasks/wave_greet.py IDLE_WAVE_EVERY_S; estimate) PASSER_MAX_M, PASSER_EVERY_S, PASSER_DEG = 3.0, 5.0, 20.0 # on the charger, nobody talking: the head turns to the nearest @@ -4046,7 +4046,8 @@ class Lumi: wave_greet.start(wave_greet_on, self.wave_free, wave_greet_off, free_every=0.05, rest=lambda: HOME_WAIST_DEG if on_charger() else 0.0, rest_arm=lambda: arm_route.HOME if on_charger() else arm_route.rest_pose(), - idle=lambda: time.time() - getattr(self, "last_activity", time.time()) > IDLE_AFTER_S and on_charger()) + idle=lambda: time.time() - getattr(self, "last_activity", 0.0) > IDLE_AFTER_S and on_charger()) # 0: idle + # from the start when nobody has talked yet log("ready") self.run_camera() if self.vision else self.run_desk() diff --git a/docs/TUNING.md b/docs/TUNING.md index 1e7978a..ad37161 100644 --- a/docs/TUNING.md +++ b/docs/TUNING.md @@ -145,7 +145,7 @@ Every value here is a constant at the top of its file, with a comment on what it | `tasks/fetch.py` | `RECEIVE_REACH_MM`, `RECEIVE_SHORT_MM`, `RECEIVE_MIN_MM` | 150, 100, 20 mm | "Take this from my hand" and "reach out to me": the hand moves at most this far from `give` towards the thing in the hand (or their hand), stops this far before it, leaves out a shorter move. Estimates | | `tasks/fetch.py` | `REACH_BODY_MM` | 300 mm | "Reach out to me" with no hand of theirs seen: the hand stops this far before the person's body. Estimate | | `assistant/lumi.py` | `REACH_COME_M` | 1.5 m | A hand-over by voice to a person further than this drives to them first (`COME_STOP`); "reach out to me" never turns or drives: the hand goes out the way the waist faces. Estimate | -| `assistant/lumi.py` | `HOME_WAIST_DEG`, `HOME_ARM_SPEED`, `HOME_DOCK_WAIT_S` | 85.8°, slow, 3 s | On the charger with nothing to do (arrived home, a conversation over) the empty arm goes from `rest` to `look` at this speed and the waist turns this far left of the front; any arm order or drive takes the arm to `rest` and the waist to the front first. The charger is asked this long after arriving home (estimate) | +| `assistant/lumi.py` | `HOME_WAIST_DEG`, `HOME_ARM_SPEED`, `HOME_DOCK_WAIT_S` | 0°, slow, 3 s | On the charger with nothing to do (arrived home, a conversation over) the empty arm goes from `rest` to `look` at this speed and the waist turns this far left of the front (0: it faces the front); any arm order or drive takes the arm to `rest` and the waist to the front first. The charger is asked this long after arriving home (estimate) | | `tasks/fetch.py` | `BAG_HANG_S` | 8 s | A mission's bag step ("take the bag to p1"): after the arm reaches the `bag` pose and Lumi asks for the bag, it waits this long before the next step drives (estimate) | | `assistant/lumi.py` | `REACH_HOLD_S` | 30 s | The hand stays held out this long after a reach without "thanks" / "okay", then the arm folds back to `look`. Estimate | | `tasks/fetch.py` | `POINT_STEPS_MM` | 0, ±50, ±100 mm | "Put it here" with pointing: spot grid around the pointed point | @@ -198,12 +198,16 @@ Every value here is a constant at the top of its file, with a comment on what it | File | Name | Default | What it does | |---|---|---|---| -| `tasks/wave_greet.py` | `GREET_M` | 3.0 m | People waving further away (head camera depth) are not answered | +| `tasks/wave_greet.py` | `GREET_MIN_M`, `GREET_M` | 1.0 m, 5.0 m | People waving nearer or further away are not answered (camera depth; without depth there, the shoulder width with `SHOULDER_M` 0.36 m) | +| `tasks/wave_greet.py` | `PASSER_M` | 3.0 m | A patrol's wave for people passing waves only at people this near | +| `vision/waving.py` | `FLOW_PX`, `FLOW_SHOULDER_PX` | 1.0 px, 80 px | Hand flow per frame that counts as a swing, for a person this wide at the shoulders; smaller (further) people need proportionally less | | `tasks/wave_greet.py` | `GONE_S` | 10 s | A greeted person out of both cameras' view this long is forgotten: their next wave gets an introduction again | -| `tasks/wave_greet.py` | `HOLD_S` | 40 s | The hand stays up this long after the last wave seen, then goes down to `look` | +| `tasks/wave_greet.py` | `HOLD_S` | 40 s | The waist stays on the last person who waved this long, then turns back to its rest; the hand stays up | | `tasks/wave_greet.py` | `DOWN_SPEED` | "normal" | `motion.JOINT_SPEED` of the way down; the way up is `arm_route.SPEED` / `wave.ARRIVE_SPEED` (route, the Cobo π limit) | | `tasks/wave_greet.py` | `SWING_SPEED` | "swing" | `motion.JOINT_SPEED` of its swings (an asked wave uses `wave.SWING_SPEED`) | | `robot/motion.py` | `SPEED_ACCEL_FACTOR` | swing 4.0 | A joint speed with its own acceleration factor instead of `JOINT_ACCEL_FACTOR`: "swing" (60 °/s, 240 °/s²) for the greeting's short swings. Higher = snappier swings, more shaking | +| `tasks/wave_greet.py` | `GREET_SWINGS` | 3 | Swings at least for someone who starts waving, more while they go on | +| `robot/gripper.py` | `FITTED` | False | The gripper is on the flange; while it is off AI_1 floats and is never read as closed or holding. True when it is back on | | `tasks/wave_greet.py` | `NEW_WAVE_S` | 5 s | No waving this long: the next wave gets a new greeting line | | `tasks/wave_greet.py` | `JOKE_AFTER_S`, `JOKE_EVERY_S` | 10 s, 12 s | Waving on and on: the first joke after this long, then one every this long | | `tasks/wave_greet.py`, `assistant/lumi.py` | `IDLE_WAVE_EVERY_S`, `IDLE_SWINGS`, `IDLE_AFTER_S` | 15 s, 3, 15 s | On the charger with the wave greeting on and nothing said to Lumi for `IDLE_AFTER_S`: the hand goes up and stays up, this many swings every `IDLE_WAVE_EVERY_S`; a call stops the swings (the hand stays up), a drive or an arm order takes it down. Estimates | diff --git a/robot/gripper.py b/robot/gripper.py index 6557ec0..7cae19e 100644 --- a/robot/gripper.py +++ b/robot/gripper.py @@ -19,6 +19,8 @@ import time from robot import arm +FITTED = False # the gripper is on the flange; False while it is off: AI_1 then floats (~486) and must + # not read as "closed on something" (that refuses every wave). True again when it is back on TOOL = 1 # set_digital_output type: 0 cabinet, 1 tool (TIO), 2 extended CLOSE_DO, OPEN_DO = 0, 1 # DO_1, DO_2 (0-based) CLOSED_AI = 400 # AI_1 above this = closed on something (open reads 130-165; an 82 mm metal cup @@ -42,7 +44,7 @@ def state(): time.sleep(READ_GAP_S) else: raise ConnectionError("the arm controller sends no tool I/O") - ai = d["tio_ain"][0] + ai = d["tio_ain"][0] if FITTED else AI_OPEN return {"closed": ai > CLOSED_AI, "holding": CLOSED_AI < ai < EMPTY_AI, "object_in_front": bool(d["tio_din"][SENSOR_DI]), "ai": d["tio_ain"], "do": d["tio_dout"], "di": d["tio_din"], "gap_mm": round(gap_mm(ai))} diff --git a/tasks/wave_greet.py b/tasks/wave_greet.py index b174390..f44c54e 100644 --- a/tasks/wave_greet.py +++ b/tasks/wave_greet.py @@ -3,13 +3,14 @@ runs in the process that owns the robot: the API's (api/server.py) while the ass (assistant/lumi.py) while it runs. There it waits while a drive, task, skill or conversation has the robot; a drive or turn brings a raised hand down first (lower()). -Someone waving within GREET_M of either camera (vision/waving.py; the head camera may look elsewhere): the head turns to them and the arm goes up at +Someone waving GREET_MIN_M .. GREET_M from either camera (vision/waving.py; the head camera may look elsewhere): the head turns to them and the arm goes up at once (manipulation/wave.py checks and plans the way, look -> wave_out -> wave_start, at the route speed), Lumi says a greeting (tasks/wave_lines.py; it introduces itself once to a person, until they leave the cameras' view: vision/reid.py face, else clothes), swings once even when they stopped meanwhile, then turns the waist to face them (fetch._waist_to, its sweep checked; the head stays on them). It swings back to back while they wave (one swing always queued behind -the running one, no stop between), stops when they stop and keeps the hand up; waving again swings again. A long wave gets a joke now and then. Nobody waving for HOLD_S: the arm -goes down slowly to look, the waist to the front, the head to rest. +the running one, no stop between), stops when they stop and keeps the hand up; waving again swings again. A long wave gets a joke now and then. Nobody waving for HOLD_S: the waist +back to its rest (the front unless start() says otherwise), the hand stays up (held, the idle swings now and then); only the switch turned off, +a drive or an order for the arm brings it down. Any stop or failure of the arm (STOP, a person too close while the arm goes up, a refused move) switches the greeting off: it never moves again by itself after a stop. @@ -30,8 +31,11 @@ from robot import arm from vision import camview, pose, reid, waving CAMERAS = ("head", "torso") # both watched: the head may look away while the person is in the torso camera's view -GREET_M = 3.0 # m; people waving further away are not answered -HOLD_S = 40.0 # s the hand stays up after the last wave seen, then down to look (owner: 60 too long) +GREET_MIN_M, GREET_M = 1.0, 5.0 # m; people waving nearer or further away are not answered (owner) +PASSER_M = 3.0 # m; a patrol's wave for people passing (passer_wave) waves only at people this near +SHOULDER_M = 0.36 # m between the shoulder keypoints: a waver's distance from their width in the image when + # depth has none there (far, or a colour-only camera); estimate (recordings 0.32-0.40) +HOLD_S = 40.0 # s the waist stays on the last one who waved, then back to its rest, the hand kept up GONE_S = 10.0 # s a greeted person may be out of both cameras' view and still be known (no new intro) SWING_POLL_S = 0.2 # s between looks at the controller's queue while swinging SWING_S = 1.5 # s one swing takes (measured 1.5-1.6 at "swing"); with the queue reading, at most one swing @@ -56,6 +60,7 @@ HEAD_TIMEOUT_S = 5.0 # s a head move may take; the body API now and then IDLE_WAVE_EVERY_S = 15.0 # s between two waves while nothing is asked of Lumi on the charger (owner: now and then for # the passers-by; estimate), from the end of the last one (or anyone's last wave) IDLE_SWINGS = 3 # swings of such a wave +GREET_SWINGS = 3 # swings at least for someone who starts waving, more while they go on (owner: one too few) IDLE_CLEAR_M = 1.0 # m; nobody this near in either camera when such a wave starts (one coming closer while the # arm goes up still stops it: _too_close); estimate RAISE_WAIT_S = 10.0 # s a drive waits for someone right by the arm to step back before the hand goes up @@ -133,14 +138,14 @@ def _watch(cam): if not (ls and rs): continue at = ((ls[0] + rs[0]) / 2, (ls[1] + rs[1]) / 2) - d = _dist(depth, at) + d = _dist(depth, at) or intr["fx"] * SHOULDER_M / max(1.0, math.hypot(ls[0] - rs[0], ls[1] - rs[1])) look = reid.look(img, p["box"]) face = reid.face(img, p["box"]) if is_waving and d is not None and d <= reid.FACE_MAX_M else None with _met_lock: # someone greeted, still in view: stays known known = _known(look, face, now) if known: known.seen(look, face, now) - if is_waving and d is not None and d <= GREET_M: + if is_waving and d is not None and GREET_MIN_M <= d <= GREET_M: wavers.append((yaw - math.degrees(math.atan((at[0] - intr["cx"]) / intr["fx"])), d, look, face)) _seen[cam].update(t=time.time(), wavers=sorted(wavers, key=lambda w: w[1])) @@ -284,6 +289,7 @@ def _swing_on(now): p = motion.poses() motion.move_path([(p[wave.SWING], SWING_SPEED), (p[wave.START], SWING_SPEED)], wait=False, queued=True) _st["swing_end"] = max(now, _st["swing_end"]) + SWING_S + _st["owed"] = max(0, _st["owed"] - 1) return True @@ -310,7 +316,7 @@ def _face(bearing): def _greet(w, lang): - """Head to them, a greeting, the arm up, one swing, the waist to them. False when the arm is refused.""" + """Head to them, a greeting, the arm up, GREET_SWINGS swings, the waist to them. False when the arm is refused.""" bearing = w[0] try: route, _ = wave.plan() @@ -322,7 +328,8 @@ def _greet(w, lang): _head_to(bearing) _say(_greeting(w), lang) _up(route) - _swing() # once, even if they stopped while the arm went up + for _ in range(GREET_SWINGS): # even if they stopped while the arm went up + _swing() w = _waver() _face(w[0] if w else bearing) return True @@ -411,11 +418,11 @@ def _nearest(m): def passer_wave(): """A drive with the hand up (lumi.Patrol, the base stopped): the head to the one waving, else the nearest person - within GREET_M, and IDLE_SWINGS swings, waited for, then the head ahead again; none when nobody is within GREET_M + within PASSER_M, and IDLE_SWINGS swings, waited for, then the head ahead again; none when nobody is within PASSER_M or someone is within IDLE_CLEAR_M of the arm. A stop or a failure switches the greeting off (_stopped) and raises. True when it swung.""" w = _waver() - bearing = w[0] if w else _nearest(GREET_M) + bearing = w[0] if w else _nearest(PASSER_M) if _on is None or not _on() or bearing is None or _someone_within(IDLE_CLEAR_M) or \ arm_route.where() not in (wave.START, wave.SWING): return False @@ -436,6 +443,19 @@ def passer_wave(): return True +def _rest_waist(): + """The waist back to _rest() with the hand kept up (its sweep checked, fetch._waist_to); the swings end first.""" + from tasks import fetch + _busy.set() + try: + if arm_route.where() is None: + _settle() + fetch._stop.clear() + _st["waist_out"] = not fetch._waist_to(_rest(), in_place=True) + finally: + _busy.clear() + + def _down(waist=None, arm_to=None): """Waist to its rest (`waist` deg from the front, else _rest()) first, the way it came with the hand up (in `look` the arm sticks out further and the same turn back can be blocked), then the arm slowly down (_rest_arm) and the @@ -458,7 +478,7 @@ def _down(waist=None, arm_to=None): _st = {"up": False, "last_wave": 0.0, "lang": 0, "next_joke": 0.0, "free": False, "free_at": 0.0, "refused_until": 0.0, "waist_out": False, "follow_at": 0.0, "swing_at": 0.0, - "swing_end": 0.0, "idle_at": 0.0, "held": False, "held_at": 0.0} # held: the hand kept up on the charger + "swing_end": 0.0, "idle_at": 0.0, "held": False, "held_at": 0.0, "owed": 0} # held: the hand kept up on the charger # (_idle_wave) # swing_end: when the swings sent so far should be done # waist_out: the way back to the front was blocked, tried again later @@ -480,11 +500,14 @@ def step(now): new = bool(w) and now - st["last_wave"] > NEW_WAVE_S if new: st["lang"], st["next_joke"] = random.randrange(2), now + JOKE_AFTER_S + st["owed"] = GREET_SWINGS # the hand up already: this many swings even if they stop sooner if w: st["last_wave"] = now + st["held"] = False # facing them now: after HOLD_S the waist goes back to its rest (held again) if not st["up"]: if w and now > st["refused_until"]: st["up"] = _greet(w, st["lang"]) + st["owed"] = 0 # _greet swung them if not st["up"]: st["refused_until"] = now + REFUSED_S elif not w and now > st["refused_until"] and now - max(st["idle_at"], st["last_wave"]) > IDLE_WAVE_EVERY_S: @@ -499,17 +522,17 @@ def step(now): fetch._stop.clear() st["waist_out"] = not fetch._waist_to(_rest(), in_place=True) st["refused_until"] = now + REFUSED_S - elif w: - if new: + elif w or st["owed"] > 0: # they stopped: the swings owed still run + if w and new: _say(_greeting(w), st["lang"]) - elif now > st["next_joke"]: + elif w and now > st["next_joke"]: _say(wave_lines.LONG, st["lang"]) st["next_joke"] = now + JOKE_EVERY_S - if abs(w[0]) > WAIST_FOLLOW_DEG and now > st["follow_at"]: + if w and abs(w[0]) > WAIST_FOLLOW_DEG and now > st["follow_at"]: st["follow_at"] = now + FOLLOW_EVERY_S _settle() _face(w[0]) # they moved: the waist turns to them again, between two swings - else: + elif w: _head_to(w[0]) if now > st["swing_at"]: st["swing_at"] = now + SWING_POLL_S @@ -528,9 +551,9 @@ def step(now): st["idle_at"] = now else: # an order moved the arm meanwhile: not held any more st["up"] = st["held"] = False - elif now - st["last_wave"] > HOLD_S: - _down() - st["up"] = False + elif now - st["last_wave"] > HOLD_S: # nobody waves: the hand stays up (owner), the waist to its rest + _rest_waist() + st["held"], st["idle_at"], st["held_at"] = True, now, 0.0 def _stopped(e): @@ -543,7 +566,7 @@ def _stopped(e): def _run(): - try: # the hand left up (an API restart mid-wave): it comes down after HOLD_S + try: # the hand left up (an API restart mid-wave): held after HOLD_S if arm_route.where() in (wave.START, wave.SWING): _st.update(up=True, last_wave=time.time()) except Exception as e: diff --git a/tests/test_arm.py b/tests/test_arm.py index d2965d5..012a0f2 100644 --- a/tests/test_arm.py +++ b/tests/test_arm.py @@ -31,6 +31,7 @@ from robot import gripper answers = [{}, {"joint_actual_position": [0] * 6}, {"tio_ain": [2300.0, 0.0], "tio_din": [0, 0], "tio_dout": [1, 0]}] arm.cmd = lambda name, **a: answers.pop(0) gripper.time.sleep = lambda s: None +gripper.FITTED = True # AI_1 read as with the gripper on assert gripper.state()["holding"] and not answers arm.cmd = lambda name, **a: {} try: diff --git a/tests/test_gripper.py b/tests/test_gripper.py index 6bfa622..9903d05 100644 --- a/tests/test_gripper.py +++ b/tests/test_gripper.py @@ -7,4 +7,11 @@ assert g.gap_mm(50) == 102.0 and g.gap_mm(5000) == 77.0 # re assert abs(g.gap_mm((g.AI_OPEN + g.AI_SHUT) / 2) - 89.5) < 0.01 # linear between assert g.gap_mm(g.AI_SHUT, "tips") == 73.0 and g.gap_mm(g.AI_OPEN, "shank") == 66.0 assert all(hasattr(g, n) for n in ("MOVE_S", "SENSOR_DI", "READ_TRIES", "READ_GAP_S", "CLOSED_AI", "EMPTY_AI")) + +reply = {"tio_ain": [486.0, 486.0], "tio_din": [0, 0], "tio_dout": [0, 1]} # AI_1 floating with no gripper on +g.arm.cmd = lambda *a, **k: reply +for fitted, holding in ((True, True), (False, False)): + g.FITTED = fitted + s = g.state() + assert s["holding"] is holding and s["closed"] is holding and s["ai"] == reply["tio_ain"], (fitted, s) print("gripper ok") diff --git a/tests/test_wave_greet.py b/tests/test_wave_greet.py index 885a6d1..c7584aa 100644 --- a/tests/test_wave_greet.py +++ b/tests/test_wave_greet.py @@ -1,6 +1,7 @@ """Self-check of the wave greeting (tasks/wave_greet.py) with a fake arm, head, waist and speech, no robot, and of the waving detector (vision/waving.py) on the recordings of vision/wave_record.py when they are here (tests/data/waves, local only: people in the pictures): python tests/test_wave_greet.py""" +import json from pathlib import Path import time @@ -87,11 +88,11 @@ def fresh(): plan_error["e"] = None -# someone waves 30 deg on the left at 2 m: head to them, a greeting, arm up at the route speed, one swing, waist to them +# someone waves 30 deg on the left at 2 m: head to them, a greeting, arm up at the route speed, GREET_SWINGS swings, waist to them fresh() waver["w"] = W(30.0) run(100.0, 100.0) -assert done == ["head +30", "up route", "swing", "waist +30 look 30.0"], done +assert done == ["head +30", "up route"] + ["swing"] * g.GREET_SWINGS + ["waist +30 look 30.0"], done assert len(said) == 1 and said[0] in sum(g.wave_lines.INTRO, ()), said # someone new: Lumi introduces itself assert g.busy() @@ -132,16 +133,16 @@ said.clear() run(115.5, 116.0) assert done.count("swing") == 1 and said == [], (done, said) -# nobody waves for HOLD_S: arm down slowly, waist to the front, head to rest; not before +# nobody waves for HOLD_S: the waist to the front, the hand stays up (held); not before waver["w"] = None done.clear() run(116.5, 116.0 + g.HOLD_S - 1) assert done == [], done run(116.0 + g.HOLD_S + 0.5, 116.0 + g.HOLD_S + 0.5) -assert done == ["waist +0 look None", "down normal", "head +0 rest"], done -assert not g.busy() and arm["at"] == "look" +assert done == ["waist +0 look None"], done +assert not g.busy() and arm["at"] == "wave_start" and g._st["up"] and g._st["held"] -# the waist's way back is blocked: the arm still goes down; the waist is tried again every REFUSED_S while nobody waves +# the waist's way back is blocked: the hand stays up there, held fresh() waver["w"] = W(30.0) run(150.0, 150.0) @@ -151,7 +152,7 @@ fetch._waist_to = lambda rel, in_place=False, look=None: done.append(f"waist {re blocked.update(n=blocked["n"] - 1) or False if blocked["n"] > 0 else True) done.clear() run(150.5 + g.HOLD_S, 150.5 + g.HOLD_S + g.REFUSED_S * 2.5) -assert done[:3] == ["waist +0", "down normal", "head +0 rest"] and done[3:] == ["waist +0"], done +assert done == ["waist +0"] and g._st["held"] and g._st["waist_out"], done fetch._waist_to = lambda rel, in_place=False, look=None: done.append(f"waist {rel:+.0f} look {look}") or True # beside a wall the full waist turn is blocked: it turns as far as its sweep is clear, the head on the person @@ -166,7 +167,7 @@ fetch._waist_to = lambda rel, in_place=False, look=None: done.append(f"waist {re fresh() waver["w"] = W(5.0) run(200.0, 200.0) -assert done == ["up route", "swing"], done # the head looks there already (within HEAD_MIN_DEG) +assert done == ["up route"] + ["swing"] * g.GREET_SWINGS, done # the head looks there already (within HEAD_MIN_DEG) # the switch is turned off with the hand up: down at once switch["on"] = False @@ -310,7 +311,7 @@ waver["w"] = W(0.0) run(621.0, 621.0) assert said[-1] in sum(g.wave_lines.INTRO, ()), said -# a loop patrol's wave for people passing: only with the hand up, someone within GREET_M, nobody by the arm +# a loop patrol's wave for people passing: only with the hand up, someone within PASSER_M, nobody by the arm near = {"m": None} waver["w"] = None g._someone_within = lambda m: near["m"] is not None and near["m"] < m @@ -329,8 +330,21 @@ assert not g.passer_wave() # the hand is not up arm["at"] = saved done.clear() +# the hand held up, someone waves for a moment and stops: GREET_SWINGS swings all the same, then no more +fresh() +arm["at"] = "wave_start" +g._st.update(up=True, held=True, idle_at=1e9) +waver["w"] = W(10.0) +run(400.0, 400.0) +waver["w"] = None +run(400.5, 420.0) +assert done.count("swing") == g.GREET_SWINGS and g._st["owed"] == 0, done +arm["at"] = "look" +done.clear() + # a hand at the head (scratching, a phone at the ear) is not a raised hand; the same hand held out to the side is import numpy as np # noqa: E402 +import cv2 # noqa: E402 kp = np.zeros((17, 3)) for name, xy in (("nose", (640, 200)), ("left_eye", (650, 190)), ("right_eye", (630, 190)), ("left_shoulder", (700, 320)), ("right_shoulder", (580, 320)), ("right_elbow", (560, 260)), ("right_wrist", (600, 210))): @@ -353,6 +367,18 @@ if DATA.exists(): assert first < 2.0, (f.name, first) # found within 2 s if f.name != "pause_2m": # (it stops waving half way) assert sum(seen) > 0.75 * len(seen), (f.name, sum(seen), len(seen)) + for name in ("right_3m", "left_3m"): # the same waves shrunk to 10 m: still found + w, n, hit, k = waving.Watcher(), 0, 0, 3 / 10 + for line in open(DATA / f"{name}.jsonl"): + d = json.loads(line) + g = cv2.imread(str(DATA / name / f"{d['n']:04d}.jpg"), cv2.IMREAD_GRAYSCALE) + far = np.full_like(g, 128) + small = cv2.resize(g, None, fx=k, fy=k, interpolation=cv2.INTER_AREA) + far[:small.shape[0], :small.shape[1]] = small + n += 1 + hit += any(v for _, v in w.update(d["t"], far, [{**p, "kp": np.array(p["kp"]) * [k, k, 1]} + for p in d["people"]])) + assert hit > 0.75 * n, (name, hit, n) r = waving.run_recording(DATA / "pause_2m") # stopped at ~6 s: no longer waving 2.5 s later assert not any(any(w) for t, w in r if t - r[0][0] > 8.5) else: diff --git a/vision/waving.py b/vision/waving.py index ade736c..87ca9fd 100644 --- a/vision/waving.py +++ b/vision/waving.py @@ -21,7 +21,9 @@ 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 +FLOW_PX = 1.0 # px per frame (half size) of sideways hand flow that counts as a swing ... +FLOW_SHOULDER_PX = 80 # ... for a person this wide at the shoulders (full size, ~3 m); smaller (further) people + # count proportionally less flow, their hand moves fewer px 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 @@ -65,7 +67,7 @@ def _hand(kp): return best -def _flow_x(prev, gray, hand): +def _flow_x(prev, gray, hand, swing_px): """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) @@ -73,12 +75,12 @@ def _flow_x(prev, gray, hand): 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 + moving = np.abs(fx) > swing_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]) +def _flips(flows, swing_px): + s = np.sign([f for f in flows if abs(f) > swing_px]) return int((np.diff(s) != 0).sum()) if len(s) > 1 else 0 @@ -105,9 +107,10 @@ class Watcher: 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 + swing_px = FLOW_PX * min(1.0, np.hypot(ls[0] - rs[0], ls[1] - rs[1]) / FLOW_SHOULDER_PX) + f = _flow_x(self.prev, gray, hand, swing_px) 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)) + out.append((p, hand is not None and _flips([v for _, v in tr["flows"]], swing_px) >= MIN_FLIPS)) self.tracks = [k for k in self.tracks if t - k["seen"] <= LOST_S] self.prev = gray return out