worldoracle-validation / scripts /visualize_human_hand.py
mu-tao's picture
Add Human Hand joint visualization example
0ada1ba
Raw History Blame Contribute Delete
9.6 kB
#!/usr/bin/env python3
"""Project released Human Hand validation joints onto released top_head frames.
The script reads one local public validation episode. It contains no episode
inventory, server path, credential, private calibration constant, or other
non-public metadata.
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import cv2
import numpy as np
HAND_EDGES = (
(0, 1), (1, 2), (2, 3), (3, 4),
(0, 5), (5, 6), (6, 7), (7, 8),
(0, 9), (9, 10), (10, 11), (11, 12),
(0, 13), (13, 14), (14, 15), (15, 16),
(0, 17), (17, 18), (18, 19), (19, 20),
(5, 9), (9, 13), (13, 17),
)
REQUIRED_NPZ_KEYS = (
"left_positions_camera",
"right_positions_camera",
"left_valid",
"right_valid",
"camera_valid",
"camera_position_world",
"camera_quaternion_world_xyzw",
)
def quaternion_xyzw_to_matrix(quaternion: np.ndarray) -> np.ndarray:
"""Convert an XYZW quaternion to a 3-by-3 rotation matrix."""
q = np.asarray(quaternion, dtype=np.float64)
if q.shape != (4,):
raise ValueError(f"expected quaternion shape (4,), got {q.shape}")
norm = np.linalg.norm(q)
if not np.isfinite(norm) or norm < 1e-8:
raise ValueError("invalid quaternion")
x, y, z, w = q / norm
return np.asarray(
[
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
],
dtype=np.float64,
)
def xyz(record: dict) -> np.ndarray:
return np.asarray([record["x"], record["y"], record["z"]], dtype=np.float64)
def xyzw(record: dict) -> np.ndarray:
return np.asarray(
[record["x"], record["y"], record["z"], record["w"]],
dtype=np.float64,
)
def project_joints(
points_stored: np.ndarray,
camera_position_world: np.ndarray,
camera_quaternion_world_xyzw: np.ndarray,
top_head: dict,
) -> tuple[np.ndarray, np.ndarray]:
"""Apply the released camera transforms and virtual pinhole projection."""
points_stored = np.asarray(points_stored, dtype=np.float64)
if points_stored.shape != (21, 3):
raise ValueError(f"expected 21x3 hand joints, got {points_stored.shape}")
# Stored/world-referenced points -> tracked camera reference frame L.
rotation_world_from_left = quaternion_xyzw_to_matrix(
camera_quaternion_world_xyzw
)
points_left = (
rotation_world_from_left.T
@ (points_stored - np.asarray(camera_position_world, dtype=np.float64)).T
).T
# Tracked camera reference frame L -> physical fisheye optical frame F.
extrinsic = top_head["extrinsics"]["extrinsic_head_fisheye_T_left"]
rotation_left_from_fisheye = quaternion_xyzw_to_matrix(
xyzw(extrinsic["rotation"])
)
translation_left_from_fisheye = xyz(extrinsic["translation"])
points_fisheye = (
rotation_left_from_fisheye.T
@ (points_left - translation_left_from_fisheye).T
).T
# Physical fisheye F -> rectified virtual top_head camera V.
rotation_virtual_from_fisheye = np.asarray(
top_head["rectification"]["source_to_virtual_rotation"],
dtype=np.float64,
)
if rotation_virtual_from_fisheye.shape != (3, 3):
raise ValueError("source_to_virtual_rotation must be a 3x3 matrix")
points_virtual = (rotation_virtual_from_fisheye @ points_fisheye.T).T
# Virtual pinhole camera -> image pixels; points behind it are invalid.
intrinsics = top_head["intrinsics"]
depth_valid = points_virtual[:, 2] > 1e-6
pixels = np.full((21, 2), np.nan, dtype=np.float64)
pixels[depth_valid, 0] = (
float(intrinsics["Fx"])
* points_virtual[depth_valid, 0]
/ points_virtual[depth_valid, 2]
+ float(intrinsics["Cx"])
)
pixels[depth_valid, 1] = (
float(intrinsics["Fy"])
* points_virtual[depth_valid, 1]
/ points_virtual[depth_valid, 2]
+ float(intrinsics["Cy"])
)
return pixels, depth_valid
def draw_hand(
image: np.ndarray,
pixels: np.ndarray,
depth_valid: np.ndarray,
color: tuple[int, int, int],
label: str,
) -> None:
"""Draw a 21-joint hand skeleton inside the image bounds."""
height, width = image.shape[:2]
visible = (
depth_valid
& np.isfinite(pixels).all(axis=1)
& (pixels[:, 0] >= 0)
& (pixels[:, 0] < width)
& (pixels[:, 1] >= 0)
& (pixels[:, 1] < height)
)
rounded = np.rint(pixels).astype(np.int32, casting="unsafe", copy=False)
for start, end in HAND_EDGES:
if visible[start] and visible[end]:
cv2.line(
image, tuple(rounded[start]), tuple(rounded[end]), color, 3,
cv2.LINE_AA,
)
for index, point in enumerate(rounded):
if visible[index]:
radius = 7 if index == 0 else 4
cv2.circle(image, tuple(point), radius, (255, 255, 255), -1, cv2.LINE_AA)
cv2.circle(image, tuple(point), radius, color, 2, cv2.LINE_AA)
if visible[0]:
anchor = tuple(rounded[0] + np.asarray([8, -8]))
cv2.putText(
image, label, anchor, cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 2,
cv2.LINE_AA,
)
def list_frames(frames_dir: Path) -> list[Path]:
frames = sorted(frames_dir.glob("frame_*.jpg"))
if not frames:
frames = sorted(frames_dir.glob("frame_*.png"))
if not frames:
raise FileNotFoundError(f"no frame_*.jpg or frame_*.png in {frames_dir}")
return frames
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Visualize one released Human Hand validation episode."
)
parser.add_argument("--npz", type=Path, required=True)
parser.add_argument("--calibration", type=Path, required=True)
parser.add_argument("--frames-dir", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--fps", type=float, default=15.0)
return parser.parse_args()
def main() -> None:
args = parse_args()
if args.fps <= 0:
raise ValueError("fps must be positive")
calibration = json.loads(args.calibration.read_text(encoding="utf-8"))
top_head = calibration["cameras"]["top_head"]
frames = list_frames(args.frames_dir)
with np.load(args.npz, allow_pickle=False) as archive:
missing = [key for key in REQUIRED_NPZ_KEYS if key not in archive]
if missing:
raise KeyError(f"NPZ is missing required arrays: {', '.join(missing)}")
data = {key: archive[key] for key in REQUIRED_NPZ_KEYS}
frame_count = len(frames)
mismatched = {
key: len(value)
for key, value in data.items()
if len(value) != frame_count
}
if mismatched:
raise ValueError(
f"frame count is {frame_count}, but NPZ lengths differ: {mismatched}"
)
sample = cv2.imread(str(frames[0]), cv2.IMREAD_COLOR)
if sample is None:
raise FileNotFoundError(frames[0])
height, width = sample.shape[:2]
header_height = 54
args.output.parent.mkdir(parents=True, exist_ok=True)
writer = cv2.VideoWriter(
str(args.output),
cv2.VideoWriter_fourcc(*"mp4v"),
args.fps,
(width * 2, height + header_height),
)
if not writer.isOpened():
raise RuntimeError(f"cannot open output video: {args.output}")
try:
for frame_index, frame_path in enumerate(frames):
raw = cv2.imread(str(frame_path), cv2.IMREAD_COLOR)
if raw is None:
raise FileNotFoundError(frame_path)
if raw.shape[:2] != (height, width):
raise ValueError(f"inconsistent frame size: {frame_path}")
overlay = raw.copy()
camera_valid = bool(data["camera_valid"][frame_index])
hands = (
(data["left_positions_camera"][frame_index],
bool(data["left_valid"][frame_index]), (0, 220, 0), "L"),
(data["right_positions_camera"][frame_index],
bool(data["right_valid"][frame_index]), (0, 80, 255), "R"),
)
for joints, hand_valid, color, label in hands:
if camera_valid and hand_valid:
pixels, depth_valid = project_joints(
joints,
data["camera_position_world"][frame_index],
data["camera_quaternion_world_xyzw"][frame_index],
top_head,
)
draw_hand(overlay, pixels, depth_valid, color, label)
canvas = np.zeros(
(height + header_height, width * 2, 3), dtype=np.uint8
)
canvas[header_height:] = np.hstack([raw, overlay])
cv2.putText(
canvas, "Released top_head frame", (12, 34),
cv2.FONT_HERSHEY_SIMPLEX, 0.66, (245, 245, 245), 2,
cv2.LINE_AA,
)
cv2.putText(
canvas,
f"Released joint projection | frame {frame_index:05d}",
(width + 12, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.66,
(245, 245, 245), 2, cv2.LINE_AA,
)
writer.write(canvas)
finally:
writer.release()
print(f"Wrote {frame_count} frames to {args.output}")
if __name__ == "__main__":
main()