motionmirror 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,28 @@
1
+ """MotionMirror: webcam motion capture applied to a built-in 3D mannequin.
2
+
3
+ The whole pipeline lives in this package - camera capture, MediaPipe pose and
4
+ face tracking, smoothing, retargeting, real-time 3D rendering and BVH export.
5
+ No Blender, no game engine, no external assets.
6
+
7
+ Quick start::
8
+
9
+ motionmirror demo # synthetic performer, no camera needed
10
+ motionmirror run # track yourself with the webcam
11
+ motionmirror run --bvh me.bvh # ...and record it for Blender
12
+ """
13
+ from __future__ import annotations
14
+
15
+ __version__ = "0.1.0"
16
+
17
+ from .bvh import BVHReader, BVHWriter
18
+ from .pipeline import Driver
19
+ from .retarget import Pose, Retargeter, local_rotations
20
+ from .skeleton import Skeleton
21
+ from .smoothing import LandmarkSmoother, OneEuroFilter, ParamSmoother
22
+ from .tracking import DemoSource, Frame, WebcamSource, ensure_model
23
+
24
+ __all__ = [
25
+ "BVHReader", "BVHWriter", "Driver", "Pose", "Retargeter", "Skeleton",
26
+ "LandmarkSmoother", "OneEuroFilter", "ParamSmoother", "DemoSource",
27
+ "Frame", "WebcamSource", "ensure_model", "local_rotations", "__version__",
28
+ ]
@@ -0,0 +1,6 @@
1
+ """``python -m motionmirror`` entry point."""
2
+ import sys
3
+
4
+ from .cli import main
5
+
6
+ sys.exit(main())
motionmirror/bvh.py ADDED
@@ -0,0 +1,216 @@
1
+ """Biovision Hierarchy (BVH) motion-capture writer + minimal reader.
2
+
3
+ Channel order used everywhere: ``Zrotation Xrotation Yrotation`` which, per
4
+ the BVH specification, composes to the matrix product ``R = Rz @ Rx @ Ry``
5
+ (angles in degrees; column-vector convention). The included
6
+ :class:`BVHReader` performs FK with exactly this convention, so the writer is
7
+ verified end-to-end by the test-suite.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+ from typing import Dict, List, Optional, Tuple
13
+
14
+ import numpy as np
15
+
16
+ from .mathutils import euler_zxy_from_quat, matrix_from_euler_zxy
17
+ from .skeleton import Skeleton
18
+
19
+
20
+ class BVHWriter:
21
+ """Records a MotionMirror session as a standard BVH file.
22
+
23
+ Buffers frames in memory and writes the complete file on :meth:`close`
24
+ (frame count is only known then).
25
+ """
26
+
27
+ def __init__(self, path, skeleton: Skeleton, fps: float = 30.0):
28
+ self.skel = skeleton
29
+ self.fps = float(fps)
30
+ self.path = Path(path)
31
+ self._frames: List[str] = []
32
+ self.joint_order: List[str] = []
33
+ self._children: Dict[str, List[str]] = {n: [] for n in skeleton.names}
34
+ for n in skeleton.names:
35
+ p = skeleton.parent_idx[skeleton.index[n]]
36
+ if p is not None:
37
+ self._children[skeleton.names[p]].append(n)
38
+ self._dfs("hips")
39
+ self._header = self._build_header()
40
+
41
+ def _dfs(self, name: str) -> None:
42
+ self.joint_order.append(name)
43
+ for c in self._children[name]:
44
+ self._dfs(c)
45
+
46
+ def _block(self, name: str, indent: str) -> List[str]:
47
+ skel = self.skel
48
+ i = skel.index[name]
49
+ lines = []
50
+ if skel.parent_idx[i] is None:
51
+ off = skel.rest_positions[i]
52
+ lines.append(f"{indent}ROOT {name}")
53
+ lines.append(f"{indent}{{")
54
+ lines.append(f"{indent} OFFSET {off[0]:.6f} {off[1]:.6f} {off[2]:.6f}")
55
+ lines.append(f"{indent} CHANNELS 6 Xposition Yposition Zposition "
56
+ "Zrotation Xrotation Yrotation")
57
+ else:
58
+ off = skel.offsets[i]
59
+ lines.append(f"{indent}JOINT {name}")
60
+ lines.append(f"{indent}{{")
61
+ lines.append(f"{indent} OFFSET {off[0]:.6f} {off[1]:.6f} {off[2]:.6f}")
62
+ lines.append(f"{indent} CHANNELS 3 Zrotation Xrotation Yrotation")
63
+ for c in self._children[name]:
64
+ lines.extend(self._block(c, indent + " "))
65
+ tip = skel.tip_by_parent.get(name)
66
+ if tip is not None and not self._children[name]:
67
+ o = skel.tip_offsets[tip]
68
+ lines.append(f"{indent} End Site")
69
+ lines.append(f"{indent} {{")
70
+ lines.append(f"{indent} OFFSET {o[0]:.6f} {o[1]:.6f} {o[2]:.6f}")
71
+ lines.append(f"{indent} }}")
72
+ lines.append(f"{indent}}}")
73
+ return lines
74
+
75
+ def _build_header(self) -> str:
76
+ return "\n".join(self._block("hips", ""))
77
+
78
+ def write_frame(self, root_pos: np.ndarray, local_quats: Dict[str, np.ndarray]) -> None:
79
+ vals = [f"{root_pos[0]:.6f}", f"{root_pos[1]:.6f}", f"{root_pos[2]:.6f}"]
80
+ for name in self.joint_order:
81
+ z, x, y = euler_zxy_from_quat(local_quats.get(name))
82
+ deg = np.degrees
83
+ vals += [f"{deg(z):.6f}", f"{deg(x):.6f}", f"{deg(y):.6f}"]
84
+ self._frames.append(" ".join(vals))
85
+
86
+ @property
87
+ def frame_count(self) -> int:
88
+ return len(self._frames)
89
+
90
+ def close(self) -> None:
91
+ if self.path.parent and str(self.path.parent):
92
+ self.path.parent.mkdir(parents=True, exist_ok=True)
93
+ with open(self.path, "w", encoding="utf-8") as f:
94
+ f.write("HIERARCHY\n")
95
+ f.write(self._header + "\n")
96
+ f.write("MOTION\n")
97
+ f.write(f"Frames: {len(self._frames)}\n")
98
+ f.write(f"Frame Time: {1.0 / self.fps:.6f}\n")
99
+ f.write("\n".join(self._frames) + "\n")
100
+
101
+ def __enter__(self):
102
+ return self
103
+
104
+ def __exit__(self, *exc):
105
+ self.close()
106
+
107
+
108
+ class BVHReader:
109
+ """Minimal BVH parser with forward kinematics (for round-trip checks and
110
+ playback). Supports the channel set written by :class:`BVHWriter`."""
111
+
112
+ def __init__(self, path):
113
+ text = Path(path).read_text(encoding="utf-8")
114
+ self.joints: List[str] = []
115
+ self.parents: List[Optional[int]] = []
116
+ self.offsets: List[np.ndarray] = []
117
+ self.channels: List[List[str]] = []
118
+ self._frames: List[np.ndarray] = []
119
+ self.fps: float = 30.0
120
+ self.num_frames: int = 0
121
+ self._skip_offset = False
122
+ lines = text.splitlines()
123
+ self._parse_hierarchy(text[:text.index("MOTION")].split())
124
+ self._parse_motion(lines)
125
+
126
+ def _parse_hierarchy(self, tk: List[str]) -> None:
127
+ i, stack = 0, []
128
+ cur = -1
129
+ while i < len(tk):
130
+ t = tk[i]
131
+ if t in ("ROOT", "JOINT"):
132
+ self.joints.append(tk[i + 1])
133
+ self.parents.append(cur if cur >= 0 else None)
134
+ self.offsets.append(np.zeros(3))
135
+ self.channels.append([])
136
+ cur = len(self.joints) - 1
137
+ i += 2
138
+ elif t == "End":
139
+ self._skip_offset = True # End Site offsets are not joints
140
+ i += 2 # skip "End Site", let its "{" balance the "}"
141
+ elif t == "OFFSET":
142
+ if self._skip_offset:
143
+ self._skip_offset = False
144
+ else:
145
+ self.offsets[cur] = np.array(
146
+ [float(tk[i + 1]), float(tk[i + 2]), float(tk[i + 3])])
147
+ i += 4
148
+ elif t == "CHANNELS":
149
+ n = int(tk[i + 1])
150
+ self.channels[cur] = tk[i + 2:i + 2 + n]
151
+ i += 2 + n
152
+ elif t == "{":
153
+ stack.append(cur)
154
+ i += 1
155
+ elif t == "}":
156
+ stack.pop()
157
+ cur = stack[-1] if stack else -1
158
+ i += 1
159
+ else:
160
+ i += 1
161
+
162
+ def _parse_motion(self, lines: List[str]) -> None:
163
+ in_motion = False
164
+ for line in lines:
165
+ stripped = line.strip()
166
+ if not in_motion:
167
+ if stripped == "MOTION":
168
+ in_motion = True
169
+ continue
170
+ if not stripped:
171
+ continue
172
+ parts = stripped.split()
173
+ if parts[0] == "Frames:":
174
+ self.num_frames = int(parts[1])
175
+ elif parts[0] == "Frame":
176
+ self.fps = 1.0 / float(parts[2])
177
+ else:
178
+ self._frames.append(np.array([float(x) for x in parts]))
179
+
180
+ def fk_positions(self, frame_index: int) -> Dict[str, np.ndarray]:
181
+ """World joint positions for one motion frame."""
182
+ row = self._frames[frame_index]
183
+ out: Dict[str, np.ndarray] = {}
184
+ rots: List[np.ndarray] = []
185
+ pos: List[np.ndarray] = []
186
+ for j, name in enumerate(self.joints):
187
+ off = self.offsets[j]
188
+ ch = self.channels[j]
189
+ vals = {}
190
+ k = 0
191
+ for jn in range(j):
192
+ k += len(self.channels[jn])
193
+ for c in ch:
194
+ vals[c] = row[k]
195
+ k += 1
196
+ p = self.parents[j]
197
+ if p is None:
198
+ t = np.array([vals.get("Xposition", 0.0),
199
+ vals.get("Yposition", 0.0),
200
+ vals.get("Zposition", 0.0)])
201
+ R = self._rot(vals)
202
+ pos.append(t)
203
+ else:
204
+ R = rots[p] @ self._rot(vals)
205
+ pos.append(pos[p] + rots[p] @ off)
206
+ rots.append(R)
207
+ out[name] = pos[j]
208
+ return out
209
+
210
+ @staticmethod
211
+ def _rot(ch_vals: Dict[str, float]) -> np.ndarray:
212
+ return matrix_from_euler_zxy(
213
+ np.radians(ch_vals.get("Zrotation", 0.0)),
214
+ np.radians(ch_vals.get("Xrotation", 0.0)),
215
+ np.radians(ch_vals.get("Yrotation", 0.0)),
216
+ )
motionmirror/cli.py ADDED
@@ -0,0 +1,87 @@
1
+ """Command line interface.
2
+
3
+ motionmirror run [-h] [--camera N] [--no-mirror] [--bvh FILE] ...
4
+ motionmirror demo [-h] [--fps N] [--no-mirror] [--bvh FILE] ...
5
+
6
+ ``run`` : live webcam tracking (needs a camera + mediapipe).
7
+ ``demo`` : synthetic performer, no camera or models needed — try this first.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import sys
13
+
14
+
15
+ def _common(p: argparse.ArgumentParser) -> None:
16
+ p.add_argument("--no-mirror", action="store_true",
17
+ help="disable mirror view (avatar moves like you, not like a reflection)")
18
+ p.add_argument("--bvh", metavar="FILE", default=None,
19
+ help="record the session to a BVH motion file")
20
+ p.add_argument("--frames", type=int, default=None,
21
+ help="stop after N frames (default: run until closed)")
22
+ p.add_argument("--headless", action="store_true",
23
+ help="no 3D window (for servers / CI / recording only)")
24
+ p.add_argument("--no-preview", action="store_true",
25
+ help="hide the camera preview window")
26
+ p.add_argument("--smooth", metavar="MIN_CUTOFF", type=float, default=1.4,
27
+ help="One Euro filter min cutoff: lower = smoother, higher = snappier")
28
+ p.add_argument("--beta", metavar="BETA", type=float, default=0.06,
29
+ help="One Euro filter beta: higher = more responsive to fast moves")
30
+
31
+
32
+ def build_parser() -> argparse.ArgumentParser:
33
+ parser = argparse.ArgumentParser(
34
+ prog="motionmirror",
35
+ description="Capture your movement with a webcam and drive a 3D mannequin "
36
+ "in real time - fully self-contained, no Blender/game engine.")
37
+ sub = parser.add_subparsers(dest="command", required=True)
38
+
39
+ run = sub.add_parser("run", help="track yourself with the webcam (live)")
40
+ run.add_argument("--camera", type=int, default=0, help="camera index (default 0)")
41
+ run.add_argument("--width", type=int, default=1280, help="capture width")
42
+ run.add_argument("--height", type=int, default=720, help="capture height")
43
+ run.add_argument("--pose-model", choices=["lite", "full", "heavy"], default="lite",
44
+ help="MediaPipe pose model size (default lite = fastest)")
45
+ _common(run)
46
+
47
+ demo = sub.add_parser("demo", help="synthetic performer - no camera needed")
48
+ demo.add_argument("--fps", type=float, default=30.0, help="demo frame rate")
49
+ _common(demo)
50
+ return parser
51
+
52
+
53
+ def main(argv=None) -> int:
54
+ args = build_parser().parse_args(argv)
55
+
56
+ if args.command == "demo":
57
+ from .tracking import DemoSource
58
+
59
+ source = DemoSource(fps=args.fps)
60
+ else:
61
+ from .tracking import WebcamSource
62
+
63
+ source = WebcamSource(camera=args.camera, width=args.width,
64
+ height=args.height, pose_model=args.pose_model)
65
+
66
+ from .pipeline import Driver
67
+
68
+ try:
69
+ driver = Driver(source, mirror=not args.no_mirror, bvh_path=args.bvh,
70
+ headless=args.headless, camera_preview=not args.no_preview,
71
+ min_cutoff=args.smooth, beta=args.beta)
72
+ except Exception as e:
73
+ print(f"[motionmirror] failed to start: {e}", file=sys.stderr)
74
+ return 1
75
+
76
+ print("=" * 62)
77
+ print(f" MotionMirror | mode: {args.command} | mirror: {not args.no_mirror}")
78
+ print(" A 3D window will open. Close it (or press q / Ctrl+C) to stop.")
79
+ if args.bvh:
80
+ print(f" Recording BVH -> {args.bvh}")
81
+ print("=" * 62)
82
+ driver.run(max_frames=args.frames)
83
+ return 0
84
+
85
+
86
+ if __name__ == "__main__":
87
+ sys.exit(main())
@@ -0,0 +1,181 @@
1
+ """Procedural humanoid mannequin built entirely from trimesh primitives.
2
+
3
+ No external assets: capsules for limbs/torso, spheres for joints and head,
4
+ plus animated face features (eyes that blink, brows that raise, a mouth that
5
+ opens and smiles). Every body part is a scene node whose 4x4 transform is
6
+ recomputed each frame from the retargeted pose — geometry is static.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from typing import Dict, List, Tuple
11
+
12
+ import numpy as np
13
+
14
+ from .mathutils import compose, quat_from_axis_angle, quat_from_two_vectors
15
+
16
+ try:
17
+ import pyrender
18
+ import trimesh
19
+ except ImportError as _e: # pragma: no cover
20
+ raise ImportError("motionmirror needs pyrender + trimesh: pip install -e .") from _e
21
+
22
+
23
+ def _mat(r: float, g: float, b: float) -> "pyrender.MetallicRoughnessMaterial":
24
+ return pyrender.MetallicRoughnessMaterial(
25
+ baseColorFactor=[r, g, b, 1.0], metallicFactor=0.0, roughnessFactor=0.85)
26
+
27
+ COLORS = {
28
+ "body": _mat(0.29, 0.44, 0.66),
29
+ "skin": _mat(0.88, 0.70, 0.57),
30
+ "joint": _mat(0.17, 0.20, 0.27),
31
+ "feet": _mat(0.20, 0.22, 0.26),
32
+ "white": _mat(0.92, 0.93, 0.95),
33
+ "pupil": _mat(0.08, 0.09, 0.11),
34
+ "brow": _mat(0.23, 0.18, 0.15),
35
+ "mouth": _mat(0.55, 0.18, 0.22),
36
+ }
37
+
38
+ # (from joint, to joint-or-tip, radius, material role)
39
+ CAPSULES: List[Tuple[str, str, float, str]] = [
40
+ ("hips", "spine", 0.100, "body"),
41
+ ("spine", "chest", 0.118, "body"),
42
+ ("chest", "neck", 0.095, "body"),
43
+ ("neck", "head", 0.042, "skin"),
44
+ ("l_shoulder", "l_forearm", 0.048, "body"),
45
+ ("l_forearm", "l_hand", 0.040, "body"),
46
+ ("l_hand", "l_hand_end", 0.034, "skin"),
47
+ ("r_shoulder", "r_forearm", 0.048, "body"),
48
+ ("r_forearm", "r_hand", 0.040, "body"),
49
+ ("r_hand", "r_hand_end", 0.034, "skin"),
50
+ ("l_thigh", "l_shin", 0.075, "body"),
51
+ ("l_shin", "l_foot", 0.058, "body"),
52
+ ("l_foot", "l_toe", 0.044, "feet"),
53
+ ("r_thigh", "r_shin", 0.075, "body"),
54
+ ("r_shin", "r_foot", 0.058, "body"),
55
+ ("r_foot", "r_toe", 0.044, "feet"),
56
+ ]
57
+
58
+ JOINT_SPHERES: Dict[str, float] = {
59
+ "l_shoulder": 0.056, "r_shoulder": 0.056,
60
+ "l_forearm": 0.046, "r_forearm": 0.046,
61
+ "l_hand": 0.038, "r_hand": 0.038,
62
+ "l_thigh": 0.062, "r_thigh": 0.062,
63
+ "l_shin": 0.056, "r_shin": 0.056,
64
+ "l_foot": 0.046, "r_foot": 0.046,
65
+ "neck": 0.048,
66
+ }
67
+
68
+ HEAD_RADIUS = 0.105
69
+ EYE_LOCAL = (0.038, 0.020, 0.090)
70
+ EYE_R = 0.019
71
+ PUPIL_DZ = 0.011
72
+ PUPIL_R = 0.0085
73
+ BROW_LOCAL = (0.038, 0.060, 0.092)
74
+ BROW_SIZE = (0.052, 0.010, 0.014)
75
+ BROW_TILT = 0.12
76
+ MOUTH_LOCAL = (0.0, -0.048, 0.088)
77
+ MOUTH_SCALE = (0.030, 0.008, 0.012)
78
+
79
+
80
+ def _sphere(radius: float, subdivisions: int = 2) -> "trimesh.Trimesh":
81
+ return trimesh.creation.icosphere(subdivisions=subdivisions, radius=radius)
82
+
83
+
84
+ def _capsule(radius: float, length: float) -> "trimesh.Trimesh":
85
+ cyl = max(length - 2.0 * radius, 0.02)
86
+ return trimesh.creation.capsule(radius=radius, height=cyl)
87
+
88
+
89
+ class Mannequin:
90
+ """Builds the mannequin into a pyrender scene and animates it per frame."""
91
+
92
+ def __init__(self):
93
+ self._caps: List[Tuple[str, str, "pyrender.Node"]] = []
94
+ self._joint_nodes: List[Tuple[str, "pyrender.Node"]] = []
95
+ self._head_node = None
96
+ self._eye_nodes: List["pyrender.Node"] = []
97
+ self._brow_nodes: List["pyrender.Node"] = []
98
+ self._mouth_node = None
99
+
100
+ # -------------------------------------------------------------- build
101
+ def build(self, scene: "pyrender.Scene") -> "Mannequin":
102
+ from .skeleton import Skeleton
103
+
104
+ skel = Skeleton()
105
+ for a, b, radius, role in CAPSULES:
106
+ length = float(np.linalg.norm(
107
+ skel.position(b) - skel.position(a))) if b in skel.index else skel.tip_lengths[b]
108
+ mesh = pyrender.Mesh.from_trimesh(_capsule(radius, length),
109
+ material=COLORS[role])
110
+ node = scene.add(mesh)
111
+ self._caps.append((a, b, node))
112
+ for name, radius in JOINT_SPHERES.items():
113
+ mesh = pyrender.Mesh.from_trimesh(_sphere(radius), material=COLORS["joint"])
114
+ self._joint_nodes.append((name, scene.add(mesh)))
115
+
116
+ head_mesh = pyrender.Mesh.from_trimesh(
117
+ _sphere(HEAD_RADIUS, subdivisions=3), material=COLORS["skin"])
118
+ self._head_node = scene.add(head_mesh)
119
+
120
+ for sgn in (+1, -1):
121
+ eye = scene.add(
122
+ pyrender.Mesh.from_trimesh(_sphere(EYE_R), material=COLORS["white"]),
123
+ parent_node=self._head_node)
124
+ scene.add(
125
+ pyrender.Mesh.from_trimesh(_sphere(PUPIL_R), material=COLORS["pupil"]),
126
+ parent_node=eye, pose=compose(translation=(0.0, 0.0, PUPIL_DZ)))
127
+ self._eye_nodes.append(eye)
128
+
129
+ brow = scene.add(
130
+ pyrender.Mesh.from_trimesh(
131
+ trimesh.creation.box(BROW_SIZE), material=COLORS["brow"]),
132
+ parent_node=self._head_node)
133
+ self._brow_nodes.append(brow)
134
+
135
+ self._mouth_node = scene.add(
136
+ pyrender.Mesh.from_trimesh(_sphere(1.0, subdivisions=2),
137
+ material=COLORS["mouth"]),
138
+ parent_node=self._head_node)
139
+ return self
140
+
141
+ # ------------------------------------------------------------- animate
142
+ def update(self, pose) -> None:
143
+ z_axis = np.array([0.0, 0.0, 1.0])
144
+ for a, b, node in self._caps:
145
+ p1, p2 = pose.position(a), pose.position(b)
146
+ d = p2 - p1
147
+ n = float(np.linalg.norm(d))
148
+ q = quat_from_two_vectors(z_axis, d / n if n > 1e-9 else z_axis)
149
+ node.matrix = compose(translation=0.5 * (p1 + p2), quat=q)
150
+
151
+ for name, node in self._joint_nodes:
152
+ node.matrix = compose(translation=pose.position(name))
153
+
154
+ face = pose.face
155
+ blink_l = float(face.get("blink_l", 0.0))
156
+ blink_r = float(face.get("blink_r", 0.0))
157
+ mouth_open = float(face.get("mouth_open", 0.0))
158
+ smile = float(face.get("smile", 0.0))
159
+ brow = float(face.get("brow", 0.0))
160
+
161
+ self._head_node.matrix = compose(translation=pose.head_center,
162
+ quat=pose.head_quat)
163
+ for k, eye in enumerate(self._eye_nodes):
164
+ sy = max(0.12, 1.0 - (blink_l if k == 0 else blink_r))
165
+ ex = EYE_LOCAL[0] * (1 if k == 0 else -1)
166
+ eye.matrix = compose(translation=(ex, EYE_LOCAL[1], EYE_LOCAL[2]),
167
+ scale=(1.0, sy, 1.0))
168
+ for k, brow_node in enumerate(self._brow_nodes):
169
+ sgn = 1 if k == 0 else -1
170
+ brow_node.matrix = compose(
171
+ translation=(BROW_LOCAL[0] * sgn,
172
+ BROW_LOCAL[1] + 0.025 * brow,
173
+ BROW_LOCAL[2]),
174
+ quat=quat_from_axis_angle((0.0, 0.0, 1.0), -BROW_TILT * sgn))
175
+ sx = 1.0 + 0.8 * smile
176
+ sy = 1.0 + 5.0 * mouth_open
177
+ self._mouth_node.matrix = compose(
178
+ translation=(MOUTH_LOCAL[0],
179
+ MOUTH_LOCAL[1] - 0.012 * mouth_open,
180
+ MOUTH_LOCAL[2]),
181
+ scale=(MOUTH_SCALE[0] * sx, MOUTH_SCALE[1] * sy, MOUTH_SCALE[2]))