Files
kinect/tracker/pose.py
T
kinect-bot 4a66699d82
ci / Linux C++ core (cmake + ctest) (push) Canceled after 0s
ci / Python tracker (pytest) (push) Canceled after 0s
feat(mapping,tracker,tools): NUI mapping+smoothing, MediaPipe tracker, record/replay harness, mock NUI host (wave 3)
2026-11-25 04:21:18 -05:00

183 lines
7.6 KiB
Python

"""Pose data model + provider interface (plan todo 5).
The tracker is built around a small `PoseProvider` seam: the real pipeline uses
`MediaPipePoseProvider` (OpenCV frame -> MediaPipe Pose Landmarker), while tests
swap in `tracker.fake_pose.FakePoseProvider`. Everything downstream (the
shared-memory publisher, the control plane) consumes only `PoseResult`, so the
data path can be exercised end-to-end without MediaPipe installed.
`PoseResult` carries the *raw* MediaPipe output described by the plan:
* 33 normalized landmarks (x, y, z, visibility) in [0, 1] image space,
* 33 world landmarks (x, y, z) in meters (hip-centered, MediaPipe convention),
* per-landmark visibility,
* the segmentation mask (float32 HxW in [0, 1]) or None.
The MediaPipe-33 -> Kinect-20 joint *mapping* and the articulated synthetic
depth rasterizer are deliberately NOT here - they are plan todos 6 and 7. This
module and the publisher only move the raw pose through the frozen IPC contract.
"""
from __future__ import annotations
import abc
from dataclasses import dataclass
from typing import Optional, Sequence
try: # numpy is required for the mask; the skeleton path itself does not need it.
import numpy as np
except ImportError: # pragma: no cover - numpy is a hard dep of the tracker
np = None # type: ignore
# MediaPipe Pose emits 33 landmarks; see the Pose Landmarker landmark table.
LANDMARK_COUNT = 33
# Landmark index -> name, for readable debugging / downstream mapping (todo 6).
LANDMARK_NAMES: tuple[str, ...] = (
"nose", "left_eye_inner", "left_eye", "left_eye_outer", "right_eye_inner",
"right_eye", "right_eye_outer", "left_ear", "right_ear", "mouth_left",
"mouth_right", "left_shoulder", "right_shoulder", "left_elbow", "right_elbow",
"left_wrist", "right_wrist", "left_pinky", "right_pinky", "left_index",
"right_index", "left_thumb", "right_thumb", "left_hip", "right_hip",
"left_knee", "right_knee", "left_ankle", "right_ankle", "left_heel",
"right_heel", "left_foot_index", "right_foot_index",
)
assert len(LANDMARK_NAMES) == LANDMARK_COUNT
@dataclass
class PoseResult:
"""One frame of raw MediaPipe pose output.
`landmarks` and `world_landmarks` always have exactly `LANDMARK_COUNT`
entries so the publisher can pack a fixed-shape frame without branching on
length. A frame with no detected person is represented by `pose=None` at the
provider seam, never by an empty `PoseResult`.
"""
landmarks: Sequence[tuple[float, float, float, float]] # 33 x (x, y, z, visibility), normalized [0,1]
world_landmarks: Sequence[tuple[float, float, float]] # 33 x (x, y, z), meters
visibility: Sequence[float] # 33 x visibility [0,1]
image_width: int
image_height: int
mask: Optional["np.ndarray"] = None # HxW float32 in [0,1], or None
def __post_init__(self) -> None:
if len(self.landmarks) != LANDMARK_COUNT:
raise ValueError(f"expected {LANDMARK_COUNT} landmarks, got {len(self.landmarks)}")
if len(self.world_landmarks) != LANDMARK_COUNT:
raise ValueError(f"expected {LANDMARK_COUNT} world landmarks, got {len(self.world_landmarks)}")
if len(self.visibility) != LANDMARK_COUNT:
raise ValueError(f"expected {LANDMARK_COUNT} visibility values, got {len(self.visibility)}")
class PoseProvider(abc.ABC):
"""Turns a BGR image frame into a `PoseResult`, or None when no person is found."""
@abc.abstractmethod
def process(self, frame_bgr: "np.ndarray", timestamp_ms: Optional[int] = None) -> Optional[PoseResult]:
"""Run inference on one BGR frame. Returns None if no pose was detected."""
def close(self) -> None: # noqa: B027 - optional override
"""Release any held resources. Default is a no-op."""
# Model tier -> bundled Pose Landmarker model file name (plan references the
# Lite/Full/Heavy tiers; the tier is selected from measured fps, see tracker.py).
MODEL_FILES = {
"lite": "pose_landmarker_lite.task",
"full": "pose_landmarker_full.task",
"heavy": "pose_landmarker_heavy.task",
}
class MediaPipePoseProvider(PoseProvider):
"""Real provider: MediaPipe Tasks `PoseLandmarker` (VIDEO running mode).
mediapipe >= 1.x ships only the Tasks API (no legacy `mp.solutions.pose`),
which loads a `.task` model bundle. `model` may be a tier name ("lite" /
"full" / "heavy", resolved against `models_dir`) or an explicit file path.
"""
def __init__(
self,
model: str = "full",
models_dir: Optional[str] = None,
min_detection_confidence: float = 0.5,
min_tracking_confidence: float = 0.5,
min_presence_confidence: float = 0.5,
output_segmentation_masks: bool = True,
) -> None:
import os
import cv2 # noqa: F401 - imported here so the import error surfaces early
import mediapipe as mp
from mediapipe.tasks import python as mp_python
from mediapipe.tasks.python import vision
self._cv2 = cv2
self._mp = mp
if model in MODEL_FILES:
base = models_dir or os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
model_path = os.path.join(base, MODEL_FILES[model])
else:
model_path = model
if not os.path.exists(model_path):
raise FileNotFoundError(
f"Pose Landmarker model not found: {model_path}. "
f"Download a .task bundle (lite/full/heavy) into tracker/models/."
)
self.model_path = model_path
options = vision.PoseLandmarkerOptions(
base_options=mp_python.BaseOptions(model_asset_path=model_path),
running_mode=vision.RunningMode.VIDEO,
num_poses=1,
min_pose_detection_confidence=min_detection_confidence,
min_pose_presence_confidence=min_presence_confidence,
min_tracking_confidence=min_tracking_confidence,
output_segmentation_masks=output_segmentation_masks,
)
self._landmarker = vision.PoseLandmarker.create_from_options(options)
self._last_ts_ms = -1
def process(self, frame_bgr: "np.ndarray", timestamp_ms: Optional[int] = None) -> Optional[PoseResult]:
h, w = frame_bgr.shape[:2]
rgb = self._cv2.cvtColor(frame_bgr, self._cv2.COLOR_BGR2RGB)
mp_image = self._mp.Image(image_format=self._mp.ImageFormat.SRGB, data=rgb)
# VIDEO mode requires strictly-increasing timestamps.
ts = int(timestamp_ms) if timestamp_ms is not None else self._last_ts_ms + 1
if ts <= self._last_ts_ms:
ts = self._last_ts_ms + 1
self._last_ts_ms = ts
result = self._landmarker.detect_for_video(mp_image, ts)
if not result.pose_landmarks:
return None
norm = result.pose_landmarks[0]
world = result.pose_world_landmarks[0] if result.pose_world_landmarks else norm
landmarks = [(lm.x, lm.y, lm.z, getattr(lm, "visibility", 0.0) or 0.0) for lm in norm]
world_landmarks = [(lm.x, lm.y, lm.z) for lm in world]
visibility = [getattr(lm, "visibility", 0.0) or 0.0 for lm in norm]
mask = None
if result.segmentation_masks:
mask = np.ascontiguousarray(result.segmentation_masks[0].numpy_view(), dtype=np.float32)
if mask.ndim == 3 and mask.shape[-1] == 1:
mask = mask[..., 0]
return PoseResult(
landmarks=landmarks,
world_landmarks=world_landmarks,
visibility=visibility,
image_width=w,
image_height=h,
mask=mask,
)
def close(self) -> None:
self._landmarker.close()