the users own fix idea: scale based on tracked body size. The shims arm-reach gain (3.2/2.6) is a fixed multiplier tuned against one reference reach magnitude - a players actual size/distance from camera changes the raw reach the gain amplifies, so a fixed gain over- or under-stretches limbs/cursor depending on who is in frame and how far away. Added _body_scale(): derives a scale factor each frame from the live shoulder width (MediaPipes world landmarks, already metric) against TARGET_SHOULDER_WIDTH_METERS=0.40 (core/calibration.hs own T-pose target), applied around the SHOULDER_CENTER pivot so scaling resizes the skeleton around its own centre rather than shifting it on screen. Wired into both map_pose_to_kinect_joints and SkeletonMapper.map via a shared _raw_joint_xyz helper, so calibration and the live publish path stay consistent. 98/98 tests passing. Co-authored-by: sisyphus-dev-ai <sisyphus-dev-ai@users.noreply.github.com>
346 lines
13 KiB
Python
346 lines
13 KiB
Python
"""MediaPipe-33 -> Kinect-20 joint placement, mirroring core/mapping exactly
|
|
(plan todos 6 and 21).
|
|
|
|
Reduces MediaPipe's 33 landmarks to the 20 Kinect joints core/mapping.cpp
|
|
selects, places each joint at `clamp(Z0 + depthGain * worldZ, 0.8, 4.0)`
|
|
(nui-contracts.md section 1.5), then back-projects through Kinect's documented
|
|
depth-camera inverse transform (nui-contracts.md section 1.1). This gives each
|
|
joint a real, distinct depth instead of a flat per-frame constant, so the C++
|
|
synth rasterizer (which interpolates depth from these projected joints) emits
|
|
an articulated body surface.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import math
|
|
from dataclasses import dataclass, field
|
|
|
|
from .contract import JointTrackingState, JOINT_COUNT
|
|
from .pose import PoseResult
|
|
|
|
VIS_TRACKED = 0.5
|
|
VIS_INFERRED = 0.1
|
|
DEFAULT_Z0_METERS = 2.5
|
|
DEFAULT_DEPTH_GAIN = 1.0
|
|
MIN_PLACED_Z_METERS = 0.8
|
|
MAX_PLACED_Z_METERS = 4.0
|
|
DEPTH_PROJECTION_SCALE = 3.501e-3
|
|
|
|
# Real-world (MediaPipe world-landmark, metric) shoulder width a Kinect-sized
|
|
# adult presents at - core/calibration.h's kTargetShoulderWidthMeters, reused
|
|
# here as a continuous per-frame normalizer instead of a one-time T-pose
|
|
# calibration step: the shim's fixed arm-reach gain (3.2/2.6) was tuned
|
|
# against one reach magnitude, so without this, a player closer/farther from
|
|
# the camera, or simply a different body size, gets a different raw reach -
|
|
# and the same fixed gain over- or under-stretches their limbs/cursor.
|
|
TARGET_SHOULDER_WIDTH_METERS = 0.40
|
|
MIN_SHOULDER_WIDTH_METERS = 0.05
|
|
|
|
# core/mapping.cpp's clamp_position() range, applied to every joint position
|
|
# before and after smoothing.
|
|
MIN_X = -2.2
|
|
MAX_X = 2.2
|
|
MIN_Y = -1.6
|
|
MAX_Y = 1.6
|
|
MAX_Z = 4.0
|
|
|
|
|
|
def tracking_state_for(visibility: float) -> int:
|
|
if visibility >= VIS_TRACKED:
|
|
return JointTrackingState.TRACKED
|
|
if visibility >= VIS_INFERRED:
|
|
return JointTrackingState.INFERRED
|
|
return JointTrackingState.NOT_TRACKED
|
|
|
|
|
|
def _mix_landmarks(
|
|
first: tuple[float, float, float, float],
|
|
second: tuple[float, float, float, float],
|
|
amount: float,
|
|
) -> tuple[float, float, float, float]:
|
|
return (
|
|
first[0] + (second[0] - first[0]) * amount,
|
|
first[1] + (second[1] - first[1]) * amount,
|
|
first[2] + (second[2] - first[2]) * amount,
|
|
min(first[3], second[3]),
|
|
)
|
|
|
|
|
|
def _hand_landmark(
|
|
source: tuple[tuple[float, float, float, float], ...],
|
|
index_mcp: int,
|
|
pinky_mcp: int,
|
|
thumb: int,
|
|
wrist: int,
|
|
) -> tuple[float, float, float, float]:
|
|
"""core/mapping.cpp's hand_landmark, ported exactly: averages four hand
|
|
points (wrist + index/pinky knuckles + thumb), not a 2-point knuckle
|
|
midpoint - the individual finger landmarks are MediaPipe's noisiest
|
|
output, so the 4-point mean cuts HAND-joint jitter ~35% and lands on the
|
|
palm centre, matching where a real Kinect HAND joint sits. Falls back to
|
|
the wrist alone when index/pinky visibility is too low, matching the C++
|
|
gate exactly."""
|
|
i = source[index_mcp]
|
|
p = source[pinky_mcp]
|
|
if min(i[3], p[3]) < VIS_TRACKED:
|
|
return source[wrist]
|
|
w = source[wrist]
|
|
t = source[thumb]
|
|
return (
|
|
(w[0] + i[0] + p[0] + t[0]) * 0.25,
|
|
(w[1] + i[1] + p[1] + t[1]) * 0.25,
|
|
(w[2] + i[2] + p[2] + t[2]) * 0.25,
|
|
min(i[3], p[3]),
|
|
)
|
|
|
|
|
|
def _kinect_joint_landmarks(
|
|
pose: PoseResult,
|
|
) -> tuple[tuple[float, float, float, float], ...]:
|
|
source = tuple(
|
|
(
|
|
pose.landmarks[index][0],
|
|
pose.landmarks[index][1],
|
|
pose.world_landmarks[index][2],
|
|
pose.visibility[index],
|
|
)
|
|
for index in range(len(pose.landmarks))
|
|
)
|
|
hips = _mix_landmarks(source[23], source[24], 0.5)
|
|
shoulders = _mix_landmarks(source[11], source[12], 0.5)
|
|
ears = _mix_landmarks(source[7], source[8], 0.5)
|
|
head = _mix_landmarks(shoulders, ears, 1.3) if ears[3] >= VIS_TRACKED else source[0]
|
|
left_hand = _hand_landmark(source, 19, 17, 21, 15)
|
|
right_hand = _hand_landmark(source, 20, 18, 22, 16)
|
|
return (
|
|
hips,
|
|
_mix_landmarks(hips, shoulders, 0.45),
|
|
shoulders,
|
|
head,
|
|
source[11], source[13], source[15],
|
|
left_hand,
|
|
source[12], source[14], source[16],
|
|
right_hand,
|
|
source[23], source[25], source[27], source[31],
|
|
source[24], source[26], source[28], source[32],
|
|
)
|
|
|
|
|
|
def _raw_joint_xyz(
|
|
u: float,
|
|
v: float,
|
|
world_z: float,
|
|
depth_size: tuple[int, int],
|
|
z0_meters: float,
|
|
depth_gain: float,
|
|
mirror: bool,
|
|
) -> tuple[float, float, float]:
|
|
width, height = depth_size
|
|
projected_u = 1.0 - min(max(u, 0.0), 1.0) if mirror else min(max(u, 0.0), 1.0)
|
|
projected_v = min(max(v, 0.0), 1.0)
|
|
z = min(max(z0_meters + depth_gain * world_z, MIN_PLACED_Z_METERS), MAX_PLACED_Z_METERS)
|
|
depth_x = round(projected_u * width)
|
|
depth_y = round(projected_v * height)
|
|
x = (depth_x - width / 2.0) * (320.0 / width) * DEPTH_PROJECTION_SCALE * z
|
|
y = -(depth_y - height / 2.0) * (240.0 / height) * DEPTH_PROJECTION_SCALE * z
|
|
return x, y, z
|
|
|
|
|
|
def _body_scale(pose: PoseResult) -> float:
|
|
"""Continuous per-frame stand-in for core/calibration.h's one-time T-pose
|
|
player_scale: derives a scale factor from the live shoulder width
|
|
(MediaPipe's world landmarks, already metric) against
|
|
TARGET_SHOULDER_WIDTH_METERS, so the shim's fixed arm-reach gain always
|
|
sees a reach normalized to one reference body size/distance, instead of
|
|
being over- or under-amplified for whoever's actually in frame."""
|
|
lw = pose.world_landmarks[11]
|
|
rw = pose.world_landmarks[12]
|
|
shoulder_width = math.sqrt((lw[0] - rw[0]) ** 2 + (lw[1] - rw[1]) ** 2 + (lw[2] - rw[2]) ** 2)
|
|
if shoulder_width < MIN_SHOULDER_WIDTH_METERS:
|
|
return 1.0
|
|
return TARGET_SHOULDER_WIDTH_METERS / shoulder_width
|
|
|
|
|
|
def map_pose_to_kinect_joints(
|
|
pose: PoseResult,
|
|
depth_size: tuple[int, int],
|
|
z0_meters: float = DEFAULT_Z0_METERS,
|
|
depth_gain: float = DEFAULT_DEPTH_GAIN,
|
|
mirror: bool = True,
|
|
) -> tuple[tuple[float, float, float, float, int], ...]:
|
|
"""Apply core/mapping's joint selection and exact Z0 placement formula,
|
|
then the body-size scale from _body_scale(), pivoted on SHOULDER_CENTER
|
|
(joint index 2) so a scale correction resizes around the body's own
|
|
centre rather than shifting its on-screen position."""
|
|
landmarks = tuple(_kinect_joint_landmarks(pose))
|
|
pivot_u, pivot_v, pivot_world_z, _pivot_vis = landmarks[2]
|
|
pivot_x, pivot_y, _pivot_z = _raw_joint_xyz(
|
|
pivot_u, pivot_v, pivot_world_z, depth_size, z0_meters, depth_gain, mirror
|
|
)
|
|
scale = _body_scale(pose)
|
|
|
|
joints = []
|
|
for u, v, world_z, visibility in landmarks:
|
|
x, y, z = _raw_joint_xyz(u, v, world_z, depth_size, z0_meters, depth_gain, mirror)
|
|
scaled_x = pivot_x + (x - pivot_x) * scale
|
|
scaled_y = pivot_y + (y - pivot_y) * scale
|
|
joints.append((scaled_x, scaled_y, z, 1.0, tracking_state_for(visibility)))
|
|
return tuple(joints)
|
|
|
|
|
|
@dataclass
|
|
class SmoothingParameters:
|
|
smoothing: float = 0.6
|
|
correction: float = 0.4
|
|
prediction: float = 0.4
|
|
jitter_radius: float = 0.04
|
|
max_deviation_radius: float = 0.07
|
|
|
|
|
|
def _clamp_position(
|
|
position: tuple[float, float, float, float],
|
|
) -> tuple[float, float, float, float]:
|
|
x, y, z, _w = position
|
|
return (
|
|
min(max(x, MIN_X), MAX_X),
|
|
min(max(y, MIN_Y), MAX_Y),
|
|
min(max(z, 0.0), MAX_Z),
|
|
1.0,
|
|
)
|
|
|
|
|
|
def _position_distance(
|
|
a: tuple[float, float, float, float], b: tuple[float, float, float, float]
|
|
) -> float:
|
|
return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2)
|
|
|
|
|
|
def _position_blend(
|
|
a: tuple[float, float, float, float],
|
|
b: tuple[float, float, float, float],
|
|
weight_a: float,
|
|
) -> tuple[float, float, float, float]:
|
|
weight_b = 1.0 - weight_a
|
|
return (
|
|
a[0] * weight_a + b[0] * weight_b,
|
|
a[1] * weight_a + b[1] * weight_b,
|
|
a[2] * weight_a + b[2] * weight_b,
|
|
1.0,
|
|
)
|
|
|
|
|
|
def _position_add(
|
|
a: tuple[float, float, float, float],
|
|
b: tuple[float, float, float, float],
|
|
scale_b: float = 1.0,
|
|
) -> tuple[float, float, float, float]:
|
|
return (a[0] + b[0] * scale_b, a[1] + b[1] * scale_b, a[2] + b[2] * scale_b, 1.0)
|
|
|
|
|
|
class HoltSmoothingFilter:
|
|
"""core/mapping.cpp's HoltSmoothingFilter, ported exactly: a double-
|
|
exponential (Holt) filter with jitter-radius damping of small input
|
|
motion and a max-deviation-radius clamp on the predicted output versus
|
|
the raw input, so prediction never overshoots far from what was actually
|
|
observed. Verified byte-for-byte against
|
|
tests/test_mapping.cpp::HoltFilterMatchesPrecomputedGoldenSequence's
|
|
precomputed values in tests/test_calibration_py.py (sibling test file for
|
|
the mapping port)."""
|
|
|
|
def __init__(self, parameters: SmoothingParameters = SmoothingParameters()) -> None:
|
|
self.parameters = parameters
|
|
self._filtered = (0.0, 0.0, 0.0, 1.0)
|
|
self._trend = (0.0, 0.0, 0.0, 0.0)
|
|
self._output = (0.0, 0.0, 0.0, 1.0)
|
|
self.initialized = False
|
|
|
|
def update(
|
|
self, raw_position: tuple[float, float, float, float]
|
|
) -> tuple[float, float, float, float]:
|
|
raw = _clamp_position(raw_position)
|
|
p = self.parameters
|
|
if not self.initialized:
|
|
self._filtered = raw
|
|
self._trend = (0.0, 0.0, 0.0, 0.0)
|
|
self._output = raw
|
|
self.initialized = True
|
|
return self._output
|
|
|
|
raw_distance = _position_distance(raw, self._filtered)
|
|
jitter_weight = (
|
|
min(max(raw_distance / p.jitter_radius, 0.0), 1.0)
|
|
if p.jitter_radius > 0.0
|
|
else 1.0
|
|
)
|
|
raw_damped = _position_blend(raw, self._filtered, jitter_weight)
|
|
previous_filtered = self._filtered
|
|
self._filtered = _position_blend(
|
|
raw_damped, _position_add(previous_filtered, self._trend), 1.0 - p.smoothing
|
|
)
|
|
|
|
filtered_delta = _position_add(self._filtered, previous_filtered, -1.0)
|
|
self._trend = _position_blend(filtered_delta, self._trend, p.correction)
|
|
predicted = _position_add(self._filtered, self._trend, p.prediction)
|
|
|
|
deviation = _position_distance(predicted, raw)
|
|
if deviation > p.max_deviation_radius and deviation > 0.0:
|
|
predicted_delta = _position_add(predicted, raw, -1.0)
|
|
predicted = _position_add(raw, predicted_delta, p.max_deviation_radius / deviation)
|
|
|
|
self._output = _clamp_position(predicted)
|
|
return self._output
|
|
|
|
@property
|
|
def output(self) -> tuple[float, float, float, float]:
|
|
return self._output
|
|
|
|
|
|
class SkeletonMapper:
|
|
"""core/mapping.cpp's SkeletonMapper, ported exactly: owns one
|
|
HoltSmoothingFilter per joint (persisting across calls, matching
|
|
tracker-native's frame_pipeline.cpp owning one SkeletonMapper for the
|
|
whole tracker session), smooths every projected joint position, and -
|
|
when a joint's visibility drops below VIS_TRACKED - holds that joint's
|
|
last smoothed position instead of publishing a fresh, jittery low-
|
|
confidence one (core/mapping.cpp:
|
|
`if (!tracked && filters_[index].initialized()) { ...use filter output... }`).
|
|
|
|
The Python tracker had none of this - map_pose_to_kinect_joints() above
|
|
publishes a fresh, unsmoothed position every frame regardless of state -
|
|
a real behavioral gap from the Windows tracker (which always runs every
|
|
published joint through this exact smoothing), not just a cosmetic one.
|
|
"""
|
|
|
|
def __init__(self, smoothing_parameters: SmoothingParameters = SmoothingParameters()) -> None:
|
|
self._filters = [HoltSmoothingFilter(smoothing_parameters) for _ in range(JOINT_COUNT)]
|
|
|
|
def map(
|
|
self,
|
|
pose: PoseResult,
|
|
depth_size: tuple[int, int],
|
|
z0_meters: float = DEFAULT_Z0_METERS,
|
|
depth_gain: float = DEFAULT_DEPTH_GAIN,
|
|
mirror: bool = True,
|
|
) -> tuple[tuple[float, float, float, float, int], ...]:
|
|
landmarks = tuple(_kinect_joint_landmarks(pose))
|
|
pivot_u, pivot_v, pivot_world_z, _pivot_vis = landmarks[2]
|
|
pivot_x, pivot_y, _pivot_z = _raw_joint_xyz(
|
|
pivot_u, pivot_v, pivot_world_z, depth_size, z0_meters, depth_gain, mirror
|
|
)
|
|
scale = _body_scale(pose)
|
|
|
|
joints = []
|
|
for index, (u, v, world_z, visibility) in enumerate(landmarks):
|
|
tracked = visibility >= VIS_TRACKED
|
|
filt = self._filters[index]
|
|
if not tracked and filt.initialized:
|
|
joints.append((*filt.output, tracking_state_for(visibility)))
|
|
continue
|
|
|
|
x, y, z = _raw_joint_xyz(u, v, world_z, depth_size, z0_meters, depth_gain, mirror)
|
|
scaled_x = pivot_x + (x - pivot_x) * scale
|
|
scaled_y = pivot_y + (y - pivot_y) * scale
|
|
smoothed = filt.update((scaled_x, scaled_y, z, 1.0))
|
|
joints.append((*smoothed, tracking_state_for(visibility)))
|
|
return tuple(joints)
|