Files
kinect/tracker/joint_mapping.py
T
kinect-botandsisyphus-dev-ai a90b2af6e9 fix(tracker): port core/mapping's hand averaging + Holt smoothing exactly
"i don't know what calibration you're talking about because i never had to
callibrate on the windows version" and "i'm having the problem from earlier
[...] difficult to move the cursor down" - both pointed at the same thing:
calibration was a workaround for a real pipeline discrepancy, not the fix.
On Windows the user only ever used the hardcoded default gains (3.2/2.6, no
calibration run) and it worked; if the Linux tracker needs calibration to
reach the same place with the same defaults, the two pipelines aren't
actually equivalent. Went back to core/mapping.cpp (the C++ module
joint_mapping.py's own docstring already claims to mirror "exactly") and
found two real, concrete divergences from that claim:

1. HAND joint averaging. core/mapping.cpp's hand_landmark() averages four
   points (wrist + index/pinky knuckles + thumb, each 0.25 weight) - the
   individual finger landmarks are MediaPipe's noisiest output, so this is a
   deliberate accuracy/jitter fix (~35% less jitter, lands on the palm
   centre matching real Kinect). joint_mapping.py's _kinect_joint_landmarks
   only averaged index+pinky (2 points, no wrist, no thumb) - a different
   hand position every frame than the Windows tracker computes for the same
   physical hand. Ported hand_landmark() exactly (same weights, same
   visibility-gated fallback to the wrist alone).

2. No smoothing at all. tracker-native/src/frame_pipeline.cpp runs every
   published joint through core/mapping's SkeletonMapper, which owns one
   Holt (double-exponential) smoothing filter per joint with jitter-radius
   damping, prediction, and a max-deviation clamp - applied to literally
   every frame of the main publish loop, not just during calibration. The
   Python tracker published a fresh, completely unsmoothed position every
   frame - a real behavioral gap (jitter/prediction/damping characteristics
   the Windows cursor feel was built around), not cosmetic.

Ported both into tracker/joint_mapping.py: HoltSmoothingFilter (the exact
filter math) and SkeletonMapper (owns one filter per joint, holds the last
smoothed position when a joint's visibility drops below VIS_TRACKED instead
of publishing a fresh low-confidence one - matching
core/mapping.cpp::SkeletonMapper::map exactly). FrameContractPublisher now
owns one SkeletonMapper instance persisting across publish() calls (matching
frame_pipeline.cpp owning one SkeletonMapper for the tracker session),
replacing the stateless per-frame map_pose_to_kinect_joints() call (still
kept, now only used by calibration.py and as the first-frame reference).

Verified against the C++ test suite's own fixtures, not just "looks
similar": tests/test_joint_mapping_py.py ports
test_mapping.cpp::HoltFilterMatchesPrecomputedGoldenSequence's exact raw/
expected values (1e-7 precision match) and
::OccludedJointIsInferredAndHoldsLastSmoothedPosition. Full suite: 98/98
passing (tests/test_tracker.py's existing fixed-pose comparison test still
matches exactly, since a fresh filter's first update is a pure passthrough -
no smoothing history yet - proven by a dedicated new test).

This does not touch the cursor arm-gain calibration added earlier - that
remains available but optional, same as it always was on Windows.

Co-authored-by: sisyphus-dev-ai <sisyphus-dev-ai@users.noreply.github.com>
2026-11-30 13:14:14 -05:00

296 lines
11 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
# 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 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."""
width, height = depth_size
joints = []
for u, v, world_z, visibility in _kinect_joint_landmarks(pose):
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
joints.append((x, 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], ...]:
width, height = depth_size
joints = []
for index, (u, v, world_z, visibility) in enumerate(_kinect_joint_landmarks(pose)):
tracked = visibility >= VIS_TRACKED
filt = self._filters[index]
if not tracked and filt.initialized:
joints.append((*filt.output, tracking_state_for(visibility)))
continue
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)
raw_x = (depth_x - width / 2.0) * (320.0 / width) * DEPTH_PROJECTION_SCALE * z
raw_y = -(depth_y - height / 2.0) * (240.0 / height) * DEPTH_PROJECTION_SCALE * z
smoothed = filt.update((raw_x, raw_y, z, 1.0))
joints.append((*smoothed, tracking_state_for(visibility)))
return tuple(joints)