Skip to content

Commit 8081b50

Browse files
poses 3d-model control mvp
1 parent 1d05a54 commit 8081b50

10 files changed

Lines changed: 895 additions & 3 deletions

File tree

models/characters/CesiumMan.glb

428 KB
Binary file not shown.

models/characters/Fox.glb

159 KB
Binary file not shown.

models/characters/RiggedFigure.glb

48.9 KB
Binary file not shown.

src/apppose.py

Lines changed: 236 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,236 @@
1+
"""Control a 3D character with body pose keypoints."""
2+
3+
from __future__ import annotations
4+
5+
import argparse
6+
import time
7+
8+
import cv2
9+
import numpy as np
10+
11+
import ui
12+
from camera import CameraStream
13+
from character import MODEL_FILES, Character
14+
from mesh3d import MeshRenderer
15+
from pose import PoseTracker
16+
17+
WINDOW = "Hand Tracking Drawing"
18+
VIEWS = ("full3d", "pip_cam", "pip_3d")
19+
VIEW_LABELS = {
20+
"full3d": "3D CHARACTER",
21+
"pip_cam": "3D CHARACTER + camera inset",
22+
"pip_3d": "CAMERA + character inset",
23+
}
24+
PIP_RATIO = 0.30
25+
MODEL_NAMES = list(MODEL_FILES.keys())
26+
27+
HELP_LINES_POSE = (
28+
"POSES",
29+
" Stand so your shoulders, hips, arms and legs are visible",
30+
" The character mirrors your pose in real time",
31+
"",
32+
"KEYS",
33+
" K cycle view (3D only / cam inset / 3D inset)",
34+
" M next model N previous model",
35+
" Y / P yaw / pitch character view R reset view",
36+
" D debug H help Q quit",
37+
)
38+
39+
40+
class AppPose:
41+
"""Body-pose driven 3D character viewer."""
42+
43+
def __init__(self, args: argparse.Namespace) -> None:
44+
self.args = args
45+
self.cam = CameraStream(args.camera, args.width, args.height)
46+
self.h, self.w = self.cam.shape
47+
print(f"[i] camera: {self.w}x{self.h} @ {self.cam.source_fps:.0f} FPS", flush=True)
48+
49+
self.tracker = PoseTracker(args.pose_model, imgsz=args.pose_size, conf=args.pose_conf)
50+
print(f"[i] pose device: {self.tracker.device}", flush=True)
51+
52+
self.renderer = MeshRenderer(self.w, self.h)
53+
self.model_index = 0
54+
self.character: Character | None = None
55+
self._load_character()
56+
57+
self.view_index = 0
58+
self.yaw, self.pitch = 0.0, 0.0
59+
self.show_help = False
60+
self.show_debug = args.debug
61+
self.toast_text = ""
62+
self.toast_until = 0.0
63+
self.fps = 0.0
64+
self._last_t = time.perf_counter()
65+
self._no_pose_since: float | None = None
66+
67+
def _load_character(self) -> None:
68+
"""(Re)load the active character model."""
69+
name = MODEL_NAMES[self.model_index]
70+
self.character = Character.load(name)
71+
self.toast(f"Model: {name}")
72+
73+
def toast(self, text: str, seconds: float = 2.0) -> None:
74+
"""Show transient message."""
75+
self.toast_text = text
76+
self.toast_until = time.time() + seconds
77+
78+
def next_model(self, step: int) -> None:
79+
"""Switch to another character model."""
80+
self.model_index = (self.model_index + step) % len(MODEL_NAMES)
81+
self._load_character()
82+
83+
def reset_view(self) -> None:
84+
"""Back to the default camera angle."""
85+
self.yaw, self.pitch = 0.0, 0.0
86+
87+
def render_character(self, canvas_shape: tuple[int, int], pose) -> np.ndarray:
88+
"""Render the character posed by one detected person, or the rest pose."""
89+
h, w = canvas_shape
90+
out = np.zeros((h, w, 3), dtype=np.uint8)
91+
assert self.character is not None
92+
ch = self.character
93+
94+
rots = ch.local_rotations(pose) if pose is not None else {}
95+
globs = ch.pose_globals(rots)
96+
parts = ch.skin(globs)
97+
98+
if pose is not None:
99+
hip = ch.pose_hip_center(pose)
100+
cx = float(hip[0]) if hip is not None else w * 0.5
101+
else:
102+
cx = w * 0.5
103+
cy = h * 0.86
104+
focal = 1.15 * h
105+
106+
return self.renderer.render(
107+
out, parts, ch.triangles(),
108+
origin=(cx, cy), focal=focal, distance=3.0,
109+
yaw=self.yaw, pitch=self.pitch,
110+
)
111+
112+
def compose(self, frame: np.ndarray, pose) -> np.ndarray:
113+
"""Build the output frame for the current view mode."""
114+
view = VIEWS[self.view_index]
115+
char_img = self.render_character((self.h, self.w), pose)
116+
117+
if view == "full3d":
118+
out = char_img
119+
elif view == "pip_cam":
120+
out = char_img.copy()
121+
self._blit_pip(out, frame)
122+
else:
123+
out = frame.copy()
124+
self._blit_pip(out, char_img)
125+
return out
126+
127+
def _blit_pip(self, out: np.ndarray, source: np.ndarray) -> None:
128+
"""Draw a picture-in-picture inset bottom-left."""
129+
h, w = out.shape[:2]
130+
pw, ph = int(w * PIP_RATIO), int(h * PIP_RATIO)
131+
inset = cv2.resize(source, (pw, ph))
132+
x0, y0 = 16, h - ph - 16
133+
cv2.rectangle(out, (x0 - 3, y0 - 3), (x0 + pw + 3, y0 + ph + 3), (210, 210, 210), 2, cv2.LINE_AA)
134+
out[y0:y0 + ph, x0:x0 + pw] = inset
135+
136+
def render(self, frame: np.ndarray, poses: list) -> np.ndarray:
137+
"""Compose the full HUD frame."""
138+
pose = poses[0] if poses else None
139+
out = self.compose(frame, pose)
140+
141+
h, w = out.shape[:2]
142+
ui.panel(out, 0, 0, w, 60, 0.5)
143+
ui.put_text(out, VIEW_LABELS[VIEWS[self.view_index]], (16, 10), 20, (255, 255, 255))
144+
name = MODEL_NAMES[self.model_index]
145+
status = f"{name} {'tracking' if pose is not None else 'no person detected'}"
146+
ui.put_text(out, status, (16, 38), 16,
147+
(140, 230, 140) if pose is not None else (200, 160, 100))
148+
149+
right = f"{self.fps:.0f} FPS {self.tracker.device.upper()}"
150+
rw = ui._render_text(right, 16, (200, 200, 200))[0].shape[1]
151+
ui.put_text(out, right, (w - rw - 16, 14), 16, (200, 200, 200))
152+
ui.put_text(out, "H help", (w - rw - 16, 38), 15, (140, 140, 140))
153+
154+
if self.toast_text and time.time() < self.toast_until:
155+
tw = ui._render_text(self.toast_text, 18, (255, 255, 255))[0].shape[1]
156+
ui.panel(out, w // 2 - tw // 2 - 14, 74, tw + 28, 36, 0.65)
157+
ui.put_text(out, self.toast_text, (w // 2 - tw // 2, 82), 18, (255, 255, 255))
158+
159+
if self.show_debug and pose is not None:
160+
ui.panel(out, 12, h - 120, 260, 100, 0.6)
161+
ui.put_text(out, f"score {pose.confidence:.2f}", (20, h - 112), 15, (220, 220, 220))
162+
ui.put_text(out, f"yaw {np.degrees(self.yaw):+.0f} pitch {np.degrees(self.pitch):+.0f}",
163+
(20, h - 90), 15, (220, 220, 220))
164+
if self.show_help:
165+
ui.draw_help(out, HELP_LINES_POSE)
166+
return out
167+
168+
def handle_key(self, key: int) -> bool:
169+
"""Handle one keypress."""
170+
if key in (ord("q"), 27):
171+
return False
172+
if key == ord("k"):
173+
self.view_index = (self.view_index + 1) % len(VIEWS)
174+
self.toast(VIEW_LABELS[VIEWS[self.view_index]])
175+
elif key == ord("m"):
176+
self.next_model(1)
177+
elif key == ord("n"):
178+
self.next_model(-1)
179+
elif key == ord("y"):
180+
self.yaw += 0.25
181+
elif key == ord("p"):
182+
self.pitch = float(np.clip(self.pitch + 0.2, -1.2, 1.2))
183+
elif key == ord("r"):
184+
self.reset_view()
185+
self.toast("View reset")
186+
elif key == ord("d"):
187+
self.show_debug = not self.show_debug
188+
self.toast("Debug " + ("on" if self.show_debug else "off"))
189+
elif key == ord("h"):
190+
self.show_help = not self.show_help
191+
return True
192+
193+
def run(self) -> None:
194+
"""Run the main loop."""
195+
cv2.namedWindow(WINDOW, cv2.WINDOW_NORMAL)
196+
cv2.resizeWindow(WINDOW, self.w, self.h)
197+
print("[i] window open. H help, Q quit.", flush=True)
198+
self.toast("Stand back so your full body is visible")
199+
200+
reason = "loop finished"
201+
frames = 0
202+
seq = -1
203+
while True:
204+
frame, seq = self.cam.wait_next(seq)
205+
if self.cam.failed:
206+
reason = "camera stopped delivering frames"
207+
break
208+
if not self.args.no_mirror:
209+
frame = cv2.flip(frame, 1)
210+
if frame.shape[:2] != (self.h, self.w):
211+
frame = cv2.resize(frame, (self.w, self.h))
212+
213+
now = time.perf_counter()
214+
dt = max(now - self._last_t, 1e-4)
215+
self._last_t = now
216+
self.fps += 0.12 * (1.0 / dt - self.fps)
217+
218+
poses = self.tracker(frame, dt)
219+
out = self.render(frame, poses)
220+
cv2.imshow(WINDOW, out)
221+
222+
key = cv2.waitKey(1) & 0xFF
223+
frames += 1
224+
if frames % 150 == 0:
225+
print(f"[i] frames: {frames} {self.fps:.1f} FPS people: {len(poses)}", flush=True)
226+
227+
if key != 255 and not self.handle_key(key):
228+
reason = f"quit key pressed ({key})"
229+
break
230+
if cv2.getWindowProperty(WINDOW, cv2.WND_PROP_VISIBLE) < 1:
231+
reason = "window closed"
232+
break
233+
234+
print(f"[i] stopped: {reason} (frames processed: {frames})", flush=True)
235+
self.cam.release()
236+
cv2.destroyAllWindows()

0 commit comments

Comments
 (0)