Files
kinect/tests/test_tracker.py
T
kinect-bot 0af22f1783
ci / Linux C++ core (cmake + ctest) (push) Canceled after 0s
ci / Python tracker (pytest) (push) Canceled after 0s
feat(calibration,contract,tracker): T-pose calibration + seqlock fix + articulated-depth wiring (wave 8a; todos 11,20,21 done)
2026-11-25 05:47:19 -05:00

233 lines
8.4 KiB
Python

"""Data-path tests for the webcam tracker (plan todo 5).
These exercise landmarks -> contract packing -> shared-memory publish -> read
back entirely with the fake pose provider, so the IPC path is verified without
MediaPipe. A live MediaPipe run is a separate smoke script, not a unit test.
"""
import ctypes
import os
import socket
import sys
import time
import numpy as np
import pytest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
from tracker import contract as c # noqa: E402
from tracker import control # noqa: E402
from tracker.fake_pose import FakeFrameSource, FakePoseProvider, make_fake_pose # noqa: E402
from tracker.joint_mapping import map_pose_to_kinect_joints # noqa: E402
from tracker.publisher import ( # noqa: E402
PROVISIONAL_BODY_DEPTH_MM,
FrameContractPublisher,
pack_depth_word,
)
from tracker.tracker import Tracker # noqa: E402
@pytest.fixture
def publisher():
pub = FrameContractPublisher(depth_size=(160, 120), color_size=(160, 120))
try:
yield pub
finally:
pub.close()
def test_region_layout_and_version(publisher):
expected = ctypes.sizeof(c.FrameContract) + c.FRAME_SLOT_COUNT * (
publisher.depth_bytes + publisher.color_bytes
)
assert publisher.region_size == expected
assert publisher.contract.contract_version == c.CONTRACT_VERSION
assert publisher.contract.published_sequence == 0
assert publisher.read_latest_frame() is None
def test_publish_and_read_back_fake_pose(publisher):
pose = make_fake_pose(frame_index=0, image_width=160, image_height=120)
color = np.full((120, 160, 3), 200, dtype=np.uint8)
seq = publisher.publish(pose, color)
assert seq == 1
assert publisher.contract.published_sequence == 1
frame = publisher.read_latest_frame()
assert frame is not None
assert frame.frame_number == 1
assert frame.skeleton.skeleton_tracking_id == 1
mapped = map_pose_to_kinect_joints(pose, (160, 120))
for j in range(c.JOINT_COUNT):
joint = frame.skeleton.joints[j]
assert joint.position.x == pytest.approx(mapped[j][0], abs=1e-5)
assert joint.position.y == pytest.approx(mapped[j][1], abs=1e-5)
assert joint.position.z == pytest.approx(mapped[j][2], abs=1e-5)
assert joint.position.w == pytest.approx(1.0)
assert joint.tracking_state == c.JointTrackingState.TRACKED
assert frame.depth.width == 160 and frame.depth.height == 120
assert frame.color.width == 160 and frame.color.height == 120
assert frame.depth.pitch == 160 * 2
assert frame.color.pitch == 160 * 4
slot = publisher.latest_slot_index()
depth = publisher.read_depth(slot)
body_word = pack_depth_word(PROVISIONAL_BODY_DEPTH_MM, 1)
assert int(depth.max()) == body_word
assert np.count_nonzero(depth) > 0
assert np.count_nonzero(depth == 0) > 0
color_out = publisher.read_color(slot)
assert color_out.shape == (120, 160, 4)
assert np.all(color_out[:, :, 3] == 255)
assert int(color_out[:, :, 0].max()) == 200
def test_joint_depth_uses_z0_placement_and_has_body_relief(publisher):
pose = make_fake_pose(frame_index=0, image_width=160, image_height=120)
publisher.publish(pose, None)
frame = publisher.read_latest_frame()
depths_mm = [
round(frame.skeleton.joints[index].position.z * 1000)
for index in range(c.JOINT_COUNT)
]
assert min(depths_mm) >= 800
assert max(depths_mm) <= 4000
assert max(depths_mm) - min(depths_mm) >= 100
def test_no_person_publishes_no_body_frame(publisher):
seq = publisher.publish(None, None)
assert seq == 1
frame = publisher.read_latest_frame()
assert frame is not None
assert frame.skeleton.skeleton_tracking_id == 0
for j in range(c.JOINT_COUNT):
joint = frame.skeleton.joints[j]
assert joint.tracking_state == c.JointTrackingState.NOT_TRACKED
assert joint.position.x == 0.0 and joint.position.y == 0.0 and joint.position.z == 0.0
depth = publisher.read_depth(publisher.latest_slot_index())
assert int(depth.max()) == 0
def test_low_visibility_marks_inferred_and_not_tracked(publisher):
# Joints 4/5/6 (SHOULDER_LEFT/ELBOW_LEFT/WRIST_LEFT) map directly from a
# single MediaPipe landmark each (11/13/15, nui-contracts.md section 1.2),
# so their tracking state follows that one landmark's visibility exactly.
pose = make_fake_pose(image_width=160, image_height=120)
pose.visibility[11] = 0.0
pose.visibility[13] = 0.2
pose.visibility[15] = 0.9
publisher.publish(pose, None)
frame = publisher.read_latest_frame()
assert frame.skeleton.joints[4].tracking_state == c.JointTrackingState.NOT_TRACKED
assert frame.skeleton.joints[5].tracking_state == c.JointTrackingState.INFERRED
assert frame.skeleton.joints[6].tracking_state == c.JointTrackingState.TRACKED
def test_sequence_increments_newest_wins(publisher):
for i in range(7):
publisher.publish(make_fake_pose(frame_index=i, image_width=160, image_height=120), None)
assert publisher.contract.published_sequence == 7
frame = publisher.read_latest_frame()
assert frame.frame_number == 7
def test_tracker_loop_paces_to_monotonic_clock():
publisher = FrameContractPublisher(depth_size=(80, 60), color_size=(80, 60))
source = FakeFrameSource(n_frames=None, width=80, height=60)
provider = FakePoseProvider(image_width=80, image_height=60)
tracker = Tracker(source, provider, publisher, target_fps=50.0)
period = 1.0 / 50.0
start = time.monotonic()
published = tracker.run(max_frames=5)
elapsed = time.monotonic() - start
try:
assert published == 5
assert publisher.contract.published_sequence == 5
assert elapsed >= 4 * period * 0.7
frame = publisher.read_latest_frame()
assert frame.skeleton.skeleton_tracking_id == 1
finally:
source.release()
publisher.close()
def test_tracker_loop_stops_at_source_end_without_crash():
publisher = FrameContractPublisher(depth_size=(80, 60), color_size=(80, 60))
source = FakeFrameSource(n_frames=4, width=80, height=60)
provider = FakePoseProvider(image_width=80, image_height=60, no_person=True)
tracker = Tracker(source, provider, publisher, target_fps=200.0)
try:
published = tracker.run(max_frames=1000)
assert published >= 1
frame = publisher.read_latest_frame()
assert frame.skeleton.skeleton_tracking_id == 0
finally:
source.release()
publisher.close()
def test_control_messages_roundtrip():
a, b = socket.socketpair()
try:
a.sendall(control.build_handshake(client_version=c.CONTRACT_VERSION, capabilities=7))
raw = b.recv(ctypes.sizeof(c.HandshakeMessage))
msg = control.parse_message(raw)
assert isinstance(msg, c.HandshakeMessage)
assert msg.header.message_type == c.ControlMessageType.HANDSHAKE_VERSION
assert msg.header.contract_version == c.CONTRACT_VERSION
assert msg.capabilities == 7
a.sendall(control.build_heartbeat(sequence=42, timestamp_micros=123456))
raw = b.recv(ctypes.sizeof(c.HeartbeatMessage))
hb = control.parse_message(raw)
assert isinstance(hb, c.HeartbeatMessage)
assert hb.header.message_type == c.ControlMessageType.HEARTBEAT
assert hb.sequence == 42
assert hb.timestamp_micros == 123456
finally:
a.close()
b.close()
def test_control_server_handshake_then_heartbeat(tmp_path):
sock_path = str(tmp_path / "control.sock")
server = control.ControlPlaneServer(sock_path)
server.start()
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
client.settimeout(2.0)
try:
deadline = time.monotonic() + 2.0
while time.monotonic() < deadline:
try:
client.connect(sock_path)
break
except (FileNotFoundError, ConnectionRefusedError):
continue
else:
pytest.fail("could not connect to control server")
raw = client.recv(ctypes.sizeof(c.HandshakeMessage))
msg = control.parse_message(raw)
assert isinstance(msg, c.HandshakeMessage)
assert server.send_heartbeat(99) is True
raw = client.recv(ctypes.sizeof(c.HeartbeatMessage))
hb = control.parse_message(raw)
assert isinstance(hb, c.HeartbeatMessage)
assert hb.sequence == 99
finally:
client.close()
server.close()