Skip to content

Retarget human motion from video to an Adobe Mixamo-rigged 3D character.

Python

Merge branch 'max/set_extractor'

MaxLiu692f0f0f524d
diff --cc AGENTS.md
index cc07c76,a5960d1..71fdbed
--- a/AGENTS.md
+++ b/AGENTS.md
@@@ -36,8 -36,6 +36,10 @@@ m2mr run --video assets/video/dance.mp
m2mr run --image assets/image/pose.jpg --rig assets/mixamo/Y_Bot.fbx
m2mr run --skeleton outputs/<run>/skeleton_motion.npz --rig ... # reuse extraction, swap rig
m2mr run --output-dir DIR --progress-jsonl FILE --no-preview # Blender Extension / automation
+m2mr run --no-foot-lock ... # keep the raw retarget (planted feet are pinned by default)
++m2mr run --set-extractor gvhmr --detect-hands --hand-smooth 0.08 # HaMeR fingers; needs assets/body_models/mano/MANO_RIGHT.pkl
++m2mr doctor --detect-hands # also check the MANO file and HaMeR packages
+m2mr diagnose outputs/<run> [--visualize] [--threshold-cm N] # re-check self-intersection -> diagnostics.json (+ .html)
```
`--video` / `--image` and `--rig` combine freely (not `--video` with `--image`).
@@@ -78,7 -76,7 +80,8 @@@ When helping a user
Extensions. The **⚙** after the title shows / hides Setup. Setup: UI
Language, Install / Update Runtime, Choose SMPL-X Model, Device,
**Check Environment**; External Python and Project Directory are under
-- **Advanced**.
++ **Advanced**. Input: **Body Model**, and **Detect Hands** (off by default;
++ on shows finger smoothing and **Choose MANO Hand Model…**).
5. After add-on **code** changes they must rebuild the zip and reinstall.
The installed copy is not live from this repo. With the one-click runtime,
changes to `motion2mixamorig/` also need **Update Runtime** (weights are
@@@ -113,12 -103,8 +116,14 @@@ Each run writes `outputs/<YYYYMMDD_HHMM
## Code map
- `motion2mixamorig/paths.py` — all filesystem locations
--- `motion2mixamorig/extract.py` — video or still -> 3D human skeleton (GVHMR)
++- `motion2mixamorig/extract.py` — clip timing helpers, plus `foot_contact_from_raw`
++- `motion2mixamorig/extractors/` — body extractors (`gvhmr`) and the HaMeR finger pass (`hamer.py`, `--detect-hands`)
++- `motion2mixamorig/mixamo/hand_retarget.py` — MANO finger rotations onto the 30 Mixamo finger bones
- `motion2mixamorig/mixamo/` — FBX parsing, FK, retargeting, skinning, rendering
+- `motion2mixamorig/mixamo/foot_lock.py` — pins planted feet (ball first, else heel) with two-bone leg IK, shifting the hips when a straight leg cannot reach; summary in `run.json` → `foot_lock`
+- `motion2mixamorig/mixamo/ground.py` — shifts the hips so the planted sole sits on y = 0; summary in `run.json` → `ground`
+- `motion2mixamorig/diagnose.py` — self-intersection check on the GLB -> `diagnostics.json`
+- `motion2mixamorig/diagnose_report.py` — `diagnostics.html` (`--visualize`)
- `motion2mixamorig/pipeline.py` — one run end to end
- `motion2mixamorig/cli.py` — `m2mr doctor` / `m2mr run`
- `blender_extension/motion2mixamorig_blender/` — Blender 4.2+ Extension (UI + external process)
diff --cc CHANGELOG.md
index 189c325,f5605ab..5549712
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -6,10 -6,12 +6,15 @@@ All notable changes to this project wil
### Added
+- Self-intersection diagnostics: every `m2mr run` checks the finished `mixamo_character.glb` for one body part going into another and writes `diagnostics.json` (body-part pairs, frame ranges, worst frame, depth in cm) plus a one-line summary; the summary also goes into `run.json`. A failed check does not fail the run. `m2mr diagnose <run>` re-checks a run; `--visualize` also writes `diagnostics.html` with the source video beside the character, a timeline, and a clickable issue list; `--threshold-cm` sets the reporting depth (default 1 cm). Parts joined at a joint are not compared, and stretches of one pair at most 3 frames apart are reported as one range. The floor is not checked.
+- Blender add-on: a **Diagnostics** box under Progress shows the job's self-intersections as a 48-cell frame bar (red = intersecting; click a cell to go there), the parts intersecting on the current frame with their depth, and Previous / Next buttons that jump between problem ranges. **Open HTML Report** opens the interactive report in the browser; the first click builds it in the background (`m2mr diagnose --visualize`, about 15 s). Results generated before this version show a note to update the runtime and generate again.
-
+- Italian: a README, a user guide, and the add-on UI (**UI Language → Italiano**; Auto picks it when Blender or the system is set to Italian). The README and the add-on now come in 19 languages.
+ - `m2mr run --detect-hands` turns on the hand model that travels with the body extractor. With the default extractor, GVHMR, that model is HaMeR: it crops the wrists from the person and the frames GVHMR already chose, writes the finger rotations into `skeleton_motion.npz`, and drives the 30 Mixamo finger bones on the skinned character. Off by default; a plain `m2mr run` leaves those bones at rest. A wrist the body pass did not see clearly stays at rest for that hand.
+ - The flag needs `assets/body_models/mano/MANO_RIGHT.pkl` (register at https://mano.is.tue.mpg.de/ and download Models & Code). The first `m2mr run --detect-hands` downloads the HaMeR weights into `weights/hamer/` (~2.7 GB, once). `m2mr doctor --detect-hands` checks that file and the extra Python packages; `m2mr doctor` without the flag does not.
+ - A run with `--detect-hands` takes about twice as long as the same clip without it. The extra time is the hand pass on top of the body extraction.
+ - `--hand-smooth SECONDS` smooths the finger rotations (default `0.08`; `0` keeps the raw estimate). It applies whenever the skeleton file already contains hand motion, including a later `--skeleton` reuse. A reused skeleton that already has hand motion drives the fingers without `--detect-hands`. If it does not, `--detect-hands` can add them only while that run's body cache is still beside the file; otherwise run the video or still again with the flag.
+ - The README quick start documents `--detect-hands`, the MANO file, the extra runtime, and how reuse behaves.
+ - Blender add-on: the Input section has a **Body Model** menu (`--set-extractor`, currently GVHMR) and **Detect Hands** (`--detect-hands`, off by default). Turning hands on shows the about-twice runtime, finger smoothing, and **Choose MANO Hand Model…**. **Check Environment** runs `m2mr doctor` with the same two choices.
### Fixed
diff --cc README.md
index b7d7499,f7633ca..5a5f28e
--- a/README.md
+++ b/README.md
@@@ -139,23 -146,33 +146,47 @@@ m2mr run --image assets/image/pose.jpg
`--image` with no path uses the file most recently added to `assets/image/`.
-### 6. Fingers (`--detect-hands`)
+### 6. Check for self-intersection
+
+Every run also checks the finished character for **self-intersection** — one body part going into another, like a hand inside the head — and writes `diagnostics.json`. The terminal prints one line, e.g. `diagnostics: 14 self-intersection(s) over 116 of 719 frames, deepest 7.87 cm`. The floor is not checked.
+
+To re-check a run, or to see the problems:
+
+```bash
+m2mr diagnose outputs/<run> # rewrite diagnostics.json
+m2mr diagnose outputs/<run> --visualize # also diagnostics.html: source video beside the character, timeline, clickable issue list
+m2mr diagnose outputs/<run> --threshold-cm 2 # report only penetrations deeper than 2 cm (default 1)
+```
+
+Each issue in `diagnostics.json` is a pair of body parts with the frame ranges where they intersect, the worst frame, and its depth. Frame numbers count from 0, as the Blender timeline does after a glTF import. Parts joined at a joint (upper arm and forearm, torso and thigh, …) are not compared: their skins overlap around the joint in any pose. `diagnostics.html` embeds the source video (needs `ffmpeg`) and loads three.js from a CDN, so its 3D view needs an internet connection.
+
++### 7. Fingers (`--detect-hands`)
+
+ A plain `m2mr run` moves the body and leaves the Mixamo finger bones at rest. `--detect-hands` turns on the hand model that travels with the body extractor. With the default extractor, GVHMR, that model is [HaMeR](https://github.com/geopavlakos/hamer). HaMeR crops the wrists from the person and the frames GVHMR already chose. It does not search the clip for a second person.
+
+ **This about doubles the runtime.** A clip that finishes in a few minutes without the flag takes about twice that long with `--detect-hands`, because the hand pass runs on top of the body extraction. On a long video, plan for that extra time before you start.
+
+ Place `MANO_RIGHT.pkl` as in the table above, then:
+
+ ```bash
+ m2mr doctor --detect-hands
+ m2mr run --detect-hands
+ m2mr run --video assets/video/dance.mp4 --detect-hands --hand-smooth 0.08
+ ```
+
+ The first `--detect-hands` run downloads the HaMeR weights into `weights/hamer/` (~2.7 GB, once). Finger rotations are written into `skeleton_motion.npz` and drive the 30 Mixamo finger bones on the skinned character. A wrist the body pass did not see clearly stays at rest for that hand.
+
+ `--hand-smooth` is how many seconds of smoothing to apply to those rotations. The default is `0.08`. `0` keeps the raw estimate. Smoothing runs whenever the skeleton file already contains hand motion, including a later run that only reuses that file.
+
+ Reusing a previous skeleton:
+
+ - The file already contains hand motion: `--skeleton` drives the fingers by itself. `--detect-hands` is not required again.
+ - It does not, but that run's body cache is still beside it (`cache/<clip>/0_input_video.mp4`, plus `preprocess/vitpose.pt` and `preprocess/bbx.pt`): `--skeleton ... --detect-hands` adds the fingers without extracting the body again.
+ - That cache is gone: run the video or still again with `--detect-hands`.
+
## Outputs
-Each `m2mr run` creates a directory named by **the time the command started**. The four files at the root are the same for video and still; only the preview folder changes.
+Each `m2mr run` creates a directory named by **the time the command started**. The files at the root are the same for video and still; only the preview folder changes.
```
outputs/20260829_193205_dance/ # or …_pose/ for a still
@@@ -192,7 -207,9 +223,9 @@@ images
# right: 10° orbit of the rig (one full turn)
```
+ With `--detect-hands`, `skeleton_motion.npz` also stores the finger rotations, and `mixamo_rotations.npz` / `mixamo_character.glb` include the 30 finger bones. Without that flag, and without hand motion already stored in a reused skeleton, those bones stay at rest.
+
-Open `mixamo_character.glb` in Blender: File → Import → glTF 2.0 (.glb/.gltf). If the camera is framed on empty space, select the character mesh and use View → Frame Selected. The cluster of spheres on the head and hands is bone display, not the mesh: in the Outliner, hide **Icosphere** and the **armature**; leave the skinned mesh visible. Set scene FPS and the timeline end frame from `run.json` (`fps`, `n_frames`) so playback matches the source. Compare a video run against `videos/mixamo_character.mp4`, a still run against `images/mixamo_character.png` or the orbit clip.
+Open `mixamo_character.glb` in Blender: File → Import → glTF 2.0 (.glb/.gltf). If the camera is framed on empty space, select the character mesh and use View → Frame Selected. The cluster of spheres on the head and hands is bone display, not the mesh: in the Outliner, hide **Icosphere** and the **armature**; leave the skinned mesh visible. Set scene FPS from `run.json` (`fps`) and the timeline to frames 0 to `n_frames` − 1 so playback matches the source and frame numbers match `diagnostics.json`. Compare a video run against `videos/mixamo_character.mp4`, a still run against `images/mixamo_character.png` or the orbit clip.
## License
diff --cc blender_extension/motion2mixamorig_blender/properties.py
index bbb70f7,1dd7427..e57a45c
--- a/blender_extension/motion2mixamorig_blender/properties.py
+++ b/blender_extension/motion2mixamorig_blender/properties.py
@@@ -24,18 -25,16 +25,28 @@@ def _source_type_items(self, context)
return _SOURCE_TYPE_ITEMS
+def _update_show_floor_markers(self, context) -> None:
+ from .operators.import_result import apply_floor_marker_visibility
+
+ apply_floor_marker_visibility(bool(self.show_floor_markers))
+ screen = getattr(context, "screen", None) if context is not None else None
+ if screen is None:
+ return
+ for area in screen.areas:
+ if area.type == "VIEW_3D":
+ area.tag_redraw()
+
+
+ def _extractor_items(self, context):
+ from .i18n import t
+
+ global _EXTRACTOR_ITEMS
+ _EXTRACTOR_ITEMS = (
+ ("gvhmr", "GVHMR", t("extractor_gvhmr_desc")),
+ )
+ return _EXTRACTOR_ITEMS
+
+
def _device_items(self, context):
from .i18n import t
diff --cc blender_extension/motion2mixamorig_blender/services/backend.py
index b771e04,80a9b83..58466b7
--- a/blender_extension/motion2mixamorig_blender/services/backend.py
+++ b/blender_extension/motion2mixamorig_blender/services/backend.py
@@@ -35,22 -35,39 +35,51 @@@ def build_version_argv(python: str | Pa
return [os.fspath(as_user_path(python)), "--version"]
- def build_doctor_argv(python: str | Path) -> list[str]:
- return [os.fspath(as_user_path(python)), "-m", "motion2mixamorig.cli", "doctor"]
+ # Names the add-on may pass to `--set-extractor`. Keep this in step with
+ # motion2mixamorig.extractors; the add-on must not import that package.
+ EXTRACTORS = ("gvhmr",)
+ DEFAULT_EXTRACTOR = "gvhmr"
+
+
+ def mano_model_present(project_dir: str | Path) -> bool:
+ """True when the project already has a MANO right-hand file for `--detect-hands`."""
+ folder = as_user_path(project_dir) / "assets" / "body_models" / "mano"
+ return (folder / "MANO_RIGHT.pkl").is_file() or (folder / "MANO_RIGHT.npz").is_file()
+
+
+ def build_doctor_argv(
+ python: str | Path,
+ *,
+ extractor: str = DEFAULT_EXTRACTOR,
+ detect_hands: bool = False,
+ ) -> list[str]:
+ if extractor not in EXTRACTORS:
+ raise ValueError(f"extractor must be one of {EXTRACTORS}, got {extractor!r}")
+ cmd = [
+ os.fspath(as_user_path(python)),
+ "-m",
+ "motion2mixamorig.cli",
+ "doctor",
+ "--set-extractor",
+ extractor,
+ ]
+ if detect_hands:
+ cmd.append("--detect-hands")
+ return cmd
+def build_diagnose_argv(python: str | Path, run_dir: str | Path) -> list[str]:
+ """`m2mr diagnose <run> --visualize`: rewrites diagnostics.json and writes diagnostics.html."""
+ return [
+ os.fspath(as_user_path(python)),
+ "-m",
+ "motion2mixamorig.cli",
+ "diagnose",
+ os.fspath(as_user_path(run_dir)),
+ "--visualize",
+ ]
+
+
def build_run_argv(
python: str | Path,
*,
diff --cc motion2mixamorig/cli.py
index 693966f,1b8daaf..3865456
--- a/motion2mixamorig/cli.py
+++ b/motion2mixamorig/cli.py
@@@ -383,30 -461,39 +484,58 @@@ def build_parser() -> argparse.Argument
return parser
+def diagnose(args: argparse.Namespace) -> int:
+ from .diagnose import DEFAULT_THRESHOLD_CM, DIAGNOSTICS_HTML, DIAGNOSTICS_JSON, diagnose_run, summary_line
+
+ run_dir = Path(args.run_dir)
+ threshold = DEFAULT_THRESHOLD_CM if args.threshold_cm is None else args.threshold_cm
+ try:
+ report = diagnose_run(run_dir, threshold_cm=threshold, visualize=args.visualize)
+ except (FileNotFoundError, ValueError) as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+ print(summary_line(report))
+ print(f"report: {run_dir / DIAGNOSTICS_JSON}")
+ if args.visualize:
+ print(f"view: {run_dir / DIAGNOSTICS_HTML}")
+ return 0
+
+
+ def _add_detect_hands_arg(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument(
+ "--detect-hands",
+ action="store_true",
+ help=(
+ "turn on the hand detection bundled with the selected body extractor "
+ "(GVHMR uses HaMeR). Needs assets/body_models/mano/MANO_RIGHT.pkl. Off by default"
+ ),
+ )
+
+
+ def _add_extractor_arg(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument(
+ "--set-extractor",
+ default=DEFAULT_EXTRACTOR,
+ choices=list(extractor_names()),
+ help=(
+ "how to turn the video or still into skeleton_motion.npz "
+ f"(default: {DEFAULT_EXTRACTOR})"
+ ),
+ )
+
+
def main() -> None:
parser = build_parser()
args = parser.parse_args()
if args.command == "doctor":
- sys.exit(doctor())
+ sys.exit(
+ doctor(
+ getattr(args, "set_extractor", None),
+ detect_hands=bool(getattr(args, "detect_hands", False)),
+ )
+ )
+ if args.command == "diagnose":
+ sys.exit(diagnose(args))
sys.exit(run(args))
diff --cc motion2mixamorig/extract.py
index f9cff9d,3b82155..66da274
--- a/motion2mixamorig/extract.py
+++ b/motion2mixamorig/extract.py
@@@ -185,267 -140,3 +140,24 @@@ def playback_fps(video: Path, n_motion_
if native and native > 0:
return float(native)
return float(fallback) if fallback > 0 else 30.0
+
+
- def _to_numpy(x):
- if hasattr(x, "detach"):
- return x.detach().cpu().numpy()
- return np.asarray(x)
-
-
- def joints_world_from_smplx(params, device: str = "cpu") -> np.ndarray:
- """Convert GVHMR SMPL-X params to 24 SMPL joints without the gated SMPL .pkl.
-
- Official ``result.joints_world`` also loads SMPL faces from
- ``SMPL_NEUTRAL.pkl``. The joint math itself only needs SMPL-X plus the
- shipped ``smplx2smpl`` / ``J_regressor`` maps.
- """
- import torch
- from einops import einsum
- from gvhmr import PROJ_ROOT
- from gvhmr.utils.device import to_device
- from gvhmr.utils.smplx_utils import make_smplx
-
- if device == "mps":
- device = "cpu"
- torch_device = torch.device(device)
- smplx = make_smplx("supermotion").to(torch_device)
- smplx2smpl = torch.load(
- PROJ_ROOT / "gvhmr/utils/body_model/smplx2smpl_sparse.pt",
- weights_only=False,
- ).to(torch_device)
- j_regressor = torch.load(
- PROJ_ROOT / "gvhmr/utils/body_model/smpl_neutral_J_regressor.pt",
- weights_only=False,
- ).to(torch_device)
- with torch.no_grad():
- out = smplx(**to_device(dict(params), torch_device))
- verts = torch.stack([torch.matmul(smplx2smpl, v) for v in out.vertices])
- joints = einsum(j_regressor, verts, "j v, l v i -> l j i")
- return joints.cpu().numpy().astype(np.float32)
-
-
- def foot_contact_from_raw(raw) -> np.ndarray | None:
++def foot_contact_from_raw(raw):
+ """(F, 4) static probability of left ankle, left foot, right ankle, right foot.
+
+ GVHMR's static_conf_logits channels are [L_ankle, L_foot, R_ankle, R_foot,
+ L_wrist, R_wrist]; only the feet are kept.
+ """
++ import numpy as np
++
+ try:
- logits = _to_numpy(raw["net_outputs"]["static_conf_logits"])
++ logits = raw["net_outputs"]["static_conf_logits"]
+ except (KeyError, TypeError):
+ return None
++ if hasattr(logits, "detach"):
++ logits = logits.detach().cpu().numpy()
+ logits = np.asarray(logits, dtype=np.float64).reshape(-1, logits.shape[-1])
+ if logits.shape[-1] < 4:
+ return None
+ return (1.0 / (1.0 + np.exp(-logits[:, :4]))).astype(np.float32)
+
-
- def _stabilize_pose_cache(pose_cache: Path) -> bool:
- """Stabilize GVHMR's 2D-pose cache in place. True if the file changed.
-
- Idempotent: a cache that was already stabilized comes back unchanged. The
- pre-stabilization data is kept next to it (*_raw) so estimator-vs-
- stabilizer questions stay answerable after the fact.
- """
- import shutil
-
- import torch
-
- from .stabilize_kp2d import stabilize_coco17
-
- current = torch.load(pose_cache, weights_only=False)
- # Always stabilize the estimator's own output: a cache written by an older
- # rule must not be stabilized a second time on top of its earlier swaps.
- raw_backup = pose_cache.with_name(pose_cache.stem + "_raw" + pose_cache.suffix)
- source = torch.load(raw_backup, weights_only=False) if raw_backup.exists() else current
- fixed, swaps = stabilize_coco17(source)
- if np.allclose(fixed, _to_numpy(current).astype(np.float32)):
- return False
- if not raw_backup.exists():
- shutil.copy2(pose_cache, raw_backup)
- torch.save(torch.from_numpy(fixed), pose_cache)
- print(f"stabilized {pose_cache.name}: corrected {int(swaps.sum())}/{len(swaps)} left/right flips")
- return True
-
-
- def still_to_hold_video(
- image: Path,
- out_mp4: Path,
- *,
- n_frames: int = HOLD_FRAMES,
- fps: float = HOLD_FPS,
- ) -> Path:
- """Repeat a still as a short silent mp4 so GVHMR can treat it as a clip."""
- import shutil
- import subprocess
-
- import cv2
-
- image = Path(image)
- frame = cv2.imread(str(image), cv2.IMREAD_COLOR)
- if frame is None:
- raise ValueError(f"cannot decode image: {image}")
-
- h, w = frame.shape[:2]
- longest = max(h, w)
- if longest > HOLD_MAX_SIDE:
- scale = HOLD_MAX_SIDE / longest
- w = int(round(w * scale))
- h = int(round(h * scale))
- frame = cv2.resize(frame, (w, h), interpolation=cv2.INTER_AREA)
- h, w = frame.shape[:2]
- w -= w % 2
- h -= h % 2
- if w < 2 or h < 2:
- raise ValueError(f"image is too small: {image}")
- frame = frame[:h, :w]
-
- out_mp4 = Path(out_mp4)
- out_mp4.parent.mkdir(parents=True, exist_ok=True)
-
- ffmpeg = shutil.which("ffmpeg")
- if ffmpeg is not None:
- cmd = [
- ffmpeg, "-y", "-loglevel", "error",
- "-f", "rawvideo", "-pix_fmt", "bgr24",
- "-s", f"{w}x{h}", "-r", f"{fps:g}",
- "-i", "-",
- "-frames:v", str(n_frames),
- "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18",
- "-preset", "veryfast", "-movflags", "+faststart",
- str(out_mp4),
- ]
- proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
- assert proc.stdin is not None
- for _ in range(n_frames):
- proc.stdin.write(frame.tobytes())
- proc.stdin.close()
- if proc.wait() != 0:
- raise RuntimeError(f"ffmpeg failed writing {out_mp4}")
- return out_mp4
-
- writer = cv2.VideoWriter(
- str(out_mp4), cv2.VideoWriter_fourcc(*"mp4v"), float(fps), (w, h)
- )
- if not writer.isOpened():
- raise RuntimeError(f"Cannot open VideoWriter for {out_mp4}")
- for _ in range(n_frames):
- writer.write(frame)
- writer.release()
- return out_mp4
-
-
- @contextmanager
- def temp_hold_video(image: Path) -> Iterator[Path]:
- """Write the hold clip under the system temp dir; delete it afterwards.
-
- GVHMR needs a real video file, but that file is not a run artifact and
- must not land in cache/.
- """
- import shutil
- import tempfile
-
- tmp = Path(tempfile.mkdtemp(prefix="m2mr-hold-"))
- try:
- yield still_to_hold_video(image, tmp / f"{Path(image).stem}.mp4")
- finally:
- shutil.rmtree(tmp, ignore_errors=True)
-
-
- def _strip_cache_videos(root: Path) -> None:
- """Drop staged / overlay mp4s from a still-image extract.
-
- GVHMR always stages ``0_input_video.mp4`` (and may write overlay clips
- under preprocess/). Those are only useful for a video run.
- """
- if not root.is_dir():
- return
- for path in root.rglob("*"):
- if path.suffix.lower() in VIDEO_SUFFIXES and (path.is_file() or path.is_symlink()):
- path.unlink(missing_ok=True)
-
-
- def extract_motion(
- video: Path,
- output_npz: Path,
- *,
- work_dir: Path,
- device: str = "cpu",
- static_camera: bool = True,
- verbose: bool = True,
- source_image: Path | None = None,
- ) -> Path:
- """Run GVHMR on `video` and save skeleton_motion.npz to `output_npz`.
-
- `work_dir` holds GVHMR's per-video intermediates (2D pose cache, 3D lift).
- Re-running with the same work_dir reuses the expensive passes.
- `source_image` is recorded when the clip was built from a still.
- """
- export_gvhmr_env()
- import gvhmr
-
- video = Path(video).resolve()
- if not video.exists():
- raise FileNotFoundError(video)
-
- output_dir = Path(work_dir) / video.stem
-
- def recover():
- return gvhmr.recover(
- str(video),
- static_camera=static_camera,
- device=device,
- pose2d="rtmpose",
- output_dir=str(output_dir),
- output_root=str(work_dir),
- progress=verbose,
- )
-
- result = recover()
-
- # RTMPose labels left/right per frame and mislabels isolated frames, which
- # spins the recovered 3D heading for those frames. Stabilize the 2D cache
- # (segment majority, see stabilize_kp2d.py) and redo the 3D lift once if
- # anything was corrected.
- pose_cache = output_dir / "preprocess" / "vitpose.pt"
- if pose_cache.exists() and _stabilize_pose_cache(pose_cache):
- motion_cache = output_dir / "hmr4d_results.pt"
- motion_cache.unlink(missing_ok=True)
- result = recover()
-
- world = result.smpl_params_world
- joints_3d = joints_world_from_smplx(world, device=device)
- root_translation = _to_numpy(world["transl"]).astype(np.float32)
- root_orientation = _to_numpy(world["global_orient"]).astype(np.float32)
- reported = float(getattr(result, "fps", 0) or 0)
- fps = playback_fps(video, len(joints_3d), fallback=reported or HOLD_FPS)
- if verbose and reported > 0 and abs(fps - reported) > 1.5:
- print(
- f"source is {fps:.3g} fps ({len(joints_3d)} frames); "
- f"GVHMR reported {reported:g} fps — using the source rate so playback matches the video"
- )
- timestamps = np.arange(len(joints_3d), dtype=np.float64) / float(fps)
-
- output_npz = Path(output_npz)
- output_npz.parent.mkdir(parents=True, exist_ok=True)
- payload = dict(
- joints_3d=joints_3d,
- joint_names=np.array(SMPL_JOINT_NAMES),
- fps=np.float32(fps),
- timestamps=timestamps,
- root_translation=root_translation,
- root_orientation=root_orientation,
- camera=np.array(result.camera),
- video=np.array(str(video)),
- )
- contact = foot_contact_from_raw(getattr(result, "raw", None))
- if contact is not None and len(contact) == len(joints_3d):
- payload["foot_contact"] = contact
- if source_image is not None:
- payload["image"] = np.array(str(source_image))
- _strip_cache_videos(output_dir)
- np.savez_compressed(output_npz, **payload)
- if verbose:
- print(f"saved {output_npz}")
- return output_npz
diff --cc motion2mixamorig/extractors/gvhmr.py
index 0000000,ef21895..a164588
mode 000000,100644..100644
--- a/motion2mixamorig/extractors/gvhmr.py
+++ b/motion2mixamorig/extractors/gvhmr.py
@@@ -1,0 -1,392 +1,396 @@@
+ """GVHMR extractor: a video or still -> skeleton_motion.npz.
+
+ A still is repeated into a short hold clip first. GVHMR is a temporal model
+ and a one-frame "video" is too short to recover a stable pose. Torch and
+ ``gvhmr`` are imported only when a check or an extract actually needs them.
+ """
+
+ from __future__ import annotations
+
+ import importlib.util
+ from contextlib import contextmanager
+ from pathlib import Path
+ from typing import Iterator
+
+ import numpy as np
+
+ from .. import paths
-from ..extract import playback_fps
++from ..extract import foot_contact_from_raw, playback_fps
+ from .base import CheckResult, write_skeleton_npz
+
+ # GVHMR is a temporal model: a one-frame "video" is too short and often
+ # unstable. Repeating the still for about a second gives it a static clip
+ # without inventing motion, and the preview / .glb then hold the pose.
+ HOLD_FRAMES = 32
+ HOLD_FPS = 30.0
+ # Phone photos are often 4000px+; YOLO / RTMPose do not need that, and a
+ # huge still makes the hold-video encode the slow part of an image run.
+ HOLD_MAX_SIDE = 1920
+
+ SMPLX_HINT = (
+ "register at https://smpl-x.is.tue.mpg.de/ , download SMPLX_NEUTRAL.npz, "
+ "place it at assets/body_models/smplx/SMPLX_NEUTRAL.npz"
+ )
+
+
+ def _module_available(name: str) -> bool:
+ return importlib.util.find_spec(name) is not None
+
+
+ def _to_numpy(x):
+ if hasattr(x, "detach"):
+ return x.detach().cpu().numpy()
+ return np.asarray(x)
+
+
+ def joints_world_from_smplx(params, device: str = "cpu") -> np.ndarray:
+ """Convert GVHMR SMPL-X params to 24 SMPL joints without the gated SMPL .pkl.
+
+ Official ``result.joints_world`` also loads SMPL faces from
+ ``SMPL_NEUTRAL.pkl``. The joint math itself only needs SMPL-X plus the
+ shipped ``smplx2smpl`` / ``J_regressor`` maps.
+ """
+ import torch
+ from einops import einsum
+ from gvhmr import PROJ_ROOT
+ from gvhmr.utils.device import to_device
+ from gvhmr.utils.smplx_utils import make_smplx
+
+ if device == "mps":
+ device = "cpu"
+ torch_device = torch.device(device)
+ smplx = make_smplx("supermotion").to(torch_device)
+ smplx2smpl = torch.load(
+ PROJ_ROOT / "gvhmr/utils/body_model/smplx2smpl_sparse.pt",
+ weights_only=False,
+ ).to(torch_device)
+ j_regressor = torch.load(
+ PROJ_ROOT / "gvhmr/utils/body_model/smpl_neutral_J_regressor.pt",
+ weights_only=False,
+ ).to(torch_device)
+ with torch.no_grad():
+ out = smplx(**to_device(dict(params), torch_device))
+ verts = torch.stack([torch.matmul(smplx2smpl, v) for v in out.vertices])
+ joints = einsum(j_regressor, verts, "j v, l v i -> l j i")
+ return joints.cpu().numpy().astype(np.float32)
+
+
+ def _stabilize_pose_cache(pose_cache: Path) -> bool:
+ """Stabilize GVHMR's 2D-pose cache in place. True if the file changed.
+
+ Idempotent: a cache that was already stabilized comes back unchanged. The
+ pre-stabilization data is kept next to it (*_raw) so estimator-vs-
+ stabilizer questions stay answerable after the fact.
+ """
+ import shutil
+
+ import torch
+
+ from ..stabilize_kp2d import stabilize_coco17
+
+ current = torch.load(pose_cache, weights_only=False)
+ # Always stabilize the estimator's own output: a cache written by an older
+ # rule must not be stabilized a second time on top of its earlier swaps.
+ raw_backup = pose_cache.with_name(pose_cache.stem + "_raw" + pose_cache.suffix)
+ source = torch.load(raw_backup, weights_only=False) if raw_backup.exists() else current
+ fixed, swaps = stabilize_coco17(source)
+ if np.allclose(fixed, _to_numpy(current).astype(np.float32)):
+ return False
+ if not raw_backup.exists():
+ shutil.copy2(pose_cache, raw_backup)
+ torch.save(torch.from_numpy(fixed), pose_cache)
+ print(f"stabilized {pose_cache.name}: corrected {int(swaps.sum())}/{len(swaps)} left/right flips")
+ return True
+
+
+ def still_to_hold_video(
+ image: Path,
+ out_mp4: Path,
+ *,
+ n_frames: int = HOLD_FRAMES,
+ fps: float = HOLD_FPS,
+ ) -> Path:
+ """Repeat a still as a short silent mp4 so GVHMR can treat it as a clip."""
+ import shutil
+ import subprocess
+
+ import cv2
+
+ image = Path(image)
+ frame = cv2.imread(str(image), cv2.IMREAD_COLOR)
+ if frame is None:
+ raise ValueError(f"cannot decode image: {image}")
+
+ h, w = frame.shape[:2]
+ longest = max(h, w)
+ if longest > HOLD_MAX_SIDE:
+ scale = HOLD_MAX_SIDE / longest
+ w = int(round(w * scale))
+ h = int(round(h * scale))
+ frame = cv2.resize(frame, (w, h), interpolation=cv2.INTER_AREA)
+ h, w = frame.shape[:2]
+ w -= w % 2
+ h -= h % 2
+ if w < 2 or h < 2:
+ raise ValueError(f"image is too small: {image}")
+ frame = frame[:h, :w]
+
+ out_mp4 = Path(out_mp4)
+ out_mp4.parent.mkdir(parents=True, exist_ok=True)
+
+ ffmpeg = shutil.which("ffmpeg")
+ if ffmpeg is not None:
+ cmd = [
+ ffmpeg, "-y", "-loglevel", "error",
+ "-f", "rawvideo", "-pix_fmt", "bgr24",
+ "-s", f"{w}x{h}", "-r", f"{fps:g}",
+ "-i", "-",
+ "-frames:v", str(n_frames),
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18",
+ "-preset", "veryfast", "-movflags", "+faststart",
+ str(out_mp4),
+ ]
+ proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
+ assert proc.stdin is not None
+ for _ in range(n_frames):
+ proc.stdin.write(frame.tobytes())
+ proc.stdin.close()
+ if proc.wait() != 0:
+ raise RuntimeError(f"ffmpeg failed writing {out_mp4}")
+ return out_mp4
+
+ writer = cv2.VideoWriter(
+ str(out_mp4), cv2.VideoWriter_fourcc(*"mp4v"), float(fps), (w, h)
+ )
+ if not writer.isOpened():
+ raise RuntimeError(f"Cannot open VideoWriter for {out_mp4}")
+ for _ in range(n_frames):
+ writer.write(frame)
+ writer.release()
+ return out_mp4
+
+
+ @contextmanager
+ def temp_hold_video(image: Path) -> Iterator[Path]:
+ """Write the hold clip under the system temp dir; delete it afterwards.
+
+ GVHMR needs a real video file, but that file is not a run artifact and
+ must not land in cache/.
+ """
+ import shutil
+ import tempfile
+
+ tmp = Path(tempfile.mkdtemp(prefix="m2mr-hold-"))
+ try:
+ yield still_to_hold_video(image, tmp / f"{Path(image).stem}.mp4")
+ finally:
+ shutil.rmtree(tmp, ignore_errors=True)
+
+
+ def _strip_cache_videos(root: Path) -> None:
+ """Drop staged / overlay mp4s from a still-image extract.
+
+ GVHMR always stages ``0_input_video.mp4`` (and may write overlay clips
+ under preprocess/). Those are only useful for a video run.
+ """
+ if not root.is_dir():
+ return
+ for path in root.rglob("*"):
+ if path.suffix.lower() in paths.VIDEO_SUFFIXES and (path.is_file() or path.is_symlink()):
+ path.unlink(missing_ok=True)
+
+
+ def _smplx_checks() -> list[CheckResult]:
+ """SMPL-X lines in the shape doctor and preflight already print."""
+ from .. import checks
+
+ label = f"SMPL-X body model {paths.SMPLX_NEUTRAL.relative_to(paths.PROJECT_ROOT)}"
+ if not paths.SMPLX_NEUTRAL.exists():
+ return [
+ CheckResult(label, False, SMPLX_HINT, section="asset", audience="doctor"),
+ CheckResult(label, False, SMPLX_HINT, section="asset", audience="preflight"),
+ ]
+ problem = checks.check_smplx(paths.SMPLX_NEUTRAL)
+ if problem is None:
+ return [
+ CheckResult(label, True, section="asset", audience="doctor"),
+ CheckResult(label, True, section="asset", audience="preflight"),
+ CheckResult(
+ "SMPL-X loads SMPLX_NEUTRAL.npz",
+ True,
+ section="asset",
+ audience="preflight",
+ ),
+ ]
+ hint = f"{paths.SMPLX_NEUTRAL.name} {problem}"
+ return [
+ CheckResult(label, False, hint, section="asset", audience="doctor", invalid=True),
+ CheckResult(label, True, section="asset", audience="preflight"),
+ CheckResult(
+ "SMPL-X loads SMPLX_NEUTRAL.npz",
+ False,
+ hint,
+ section="asset",
+ audience="preflight",
+ invalid=True,
+ ),
+ ]
+
+
+ class GvhmrExtractor:
+ """Recover a world-grounded skeleton with GVHMR."""
+
+ name = "gvhmr"
+ hand_model = "hamer"
+ weights_note = "downloaded automatically into weights/ on the first `m2mr run` (~5 GB)"
+ hand_weights_note = (
+ "HaMeR hand weights (~2.7 GB) download into weights/hamer/ on the first "
+ "`m2mr run --detect-hands`"
+ )
+
+ def check(self, detect_hands: bool = False) -> list[CheckResult]:
+ from .hamer import hand_requirements
+
+ results = _smplx_checks()
+ for module in ("torch", "gvhmr"):
+ results.append(
+ CheckResult(
+ f"python module {module}",
+ _module_available(module),
+ "pip install -e .",
+ section="module",
+ audience="doctor",
+ )
+ )
+ if detect_hands:
+ results.extend(hand_requirements())
+ return results
+
+ def extract(
+ self,
+ source: Path,
+ output_npz: Path,
+ *,
+ work_dir: Path,
+ device: str = "cpu",
+ verbose: bool = True,
+ detect_hands: bool = False,
+ ) -> Path:
+ source = Path(source)
+ if paths.is_image(source):
+ with temp_hold_video(source) as hold:
+ return _extract_video(
+ hold,
+ output_npz,
+ work_dir=work_dir,
+ device=device,
+ verbose=verbose,
+ source_image=source,
+ detect_hands=detect_hands,
+ )
+ return _extract_video(
+ source,
+ output_npz,
+ work_dir=work_dir,
+ device=device,
+ verbose=verbose,
+ detect_hands=detect_hands,
+ )
+
+
+ def _extract_video(
+ video: Path,
+ output_npz: Path,
+ *,
+ work_dir: Path,
+ device: str = "cpu",
+ static_camera: bool = True,
+ verbose: bool = True,
+ source_image: Path | None = None,
+ detect_hands: bool = False,
+ ) -> Path:
+ """Run GVHMR on `video` and save skeleton_motion.npz to `output_npz`.
+
+ `work_dir` holds GVHMR's per-video intermediates (2D pose cache, 3D lift).
+ Re-running with the same work_dir reuses the expensive passes.
+ `source_image` is recorded when the clip was built from a still.
+ """
+ paths.export_gvhmr_env()
+ import gvhmr
+
+ video = Path(video).resolve()
+ if not video.exists():
+ raise FileNotFoundError(video)
+
+ output_dir = Path(work_dir) / video.stem
+
+ def recover():
+ return gvhmr.recover(
+ str(video),
+ static_camera=static_camera,
+ device=device,
+ pose2d="rtmpose",
+ output_dir=str(output_dir),
+ output_root=str(work_dir),
+ progress=verbose,
+ )
+
+ result = recover()
+
+ # RTMPose labels left/right per frame and mislabels isolated frames, which
+ # spins the recovered 3D heading for those frames. Stabilize the 2D cache
+ # (segment majority, see stabilize_kp2d.py) and redo the 3D lift once if
+ # anything was corrected.
+ pose_cache = output_dir / "preprocess" / "vitpose.pt"
+ if pose_cache.exists() and _stabilize_pose_cache(pose_cache):
+ motion_cache = output_dir / "hmr4d_results.pt"
+ motion_cache.unlink(missing_ok=True)
+ result = recover()
+
+ world = result.smpl_params_world
+ joints_3d = joints_world_from_smplx(world, device=device)
+ root_translation = _to_numpy(world["transl"]).astype(np.float32)
+ root_orientation = _to_numpy(world["global_orient"]).astype(np.float32)
+ reported = float(getattr(result, "fps", 0) or 0)
+ fps = playback_fps(video, len(joints_3d), fallback=reported or HOLD_FPS)
+ if verbose and reported > 0 and abs(fps - reported) > 1.5:
+ print(
+ f"source is {fps:.3g} fps ({len(joints_3d)} frames); "
+ f"GVHMR reported {reported:g} fps — using the source rate so playback matches the video"
+ )
+ timestamps = np.arange(len(joints_3d), dtype=np.float64) / float(fps)
+ image = None if source_image is None else np.array(str(source_image))
++ contact = foot_contact_from_raw(getattr(result, "raw", None))
++ if contact is not None and len(contact) != len(joints_3d):
++ contact = None
+ written = write_skeleton_npz(
+ output_npz,
+ extractor=GvhmrExtractor.name,
+ joints_3d=joints_3d,
+ fps=fps,
+ timestamps=timestamps,
+ root_translation=root_translation,
+ root_orientation=root_orientation,
+ camera=np.array(result.camera),
+ video=np.array(str(video)),
+ image=image,
++ foot_contact=contact,
+ )
+ if verbose:
+ print(f"saved {written}")
+ if detect_hands:
+ from .hamer import detect_and_append
+
+ if verbose:
+ print("detecting hands")
+ detect_and_append(
+ output_dir,
+ written,
+ len(joints_3d),
+ device=device,
+ verbose=verbose,
+ single_frame=source_image is not None,
+ )
+ if source_image is not None:
+ _strip_cache_videos(output_dir)
+ return written
diff --cc motion2mixamorig/mixamo/animation.py
index 1f95d14,297e1a4..c855a6e
--- a/motion2mixamorig/mixamo/animation.py
+++ b/motion2mixamorig/mixamo/animation.py
@@@ -17,8 -13,7 +17,9 @@@ from dataclasses import dataclass, fiel
import numpy as np
+from .foot_lock import lock_feet
+from .ground import plant_soles
+ from .hand_retarget import HandMapping, HandMotion
from .kinematics import forward_kinematics, world_positions_m
from .retarget import joint_mixamo, retarget_one_frame
from .skinned_mesh import YBotAsset, bone_palette, skin_mesh
@@@ -52,8 -45,8 +53,10 @@@ def build_animation
frames: list[int],
*,
verbose: bool = True,
+ foot_lock: bool = True,
+ asset: YBotAsset | None = None,
+ hands: HandMotion | None = None,
+ hand_mapping: HandMapping | None = None,
) -> RetargetedAnimation:
"""Retarget Human -> Mixamo, then carry the rest-relative motion onto the rig."""
skel = mapping.skeleton_rig
diff --cc motion2mixamorig/pipeline.py
index c0900a6,83e23f0..119d6be
--- a/motion2mixamorig/pipeline.py
+++ b/motion2mixamorig/pipeline.py
@@@ -22,8 -22,17 +22,18 @@@ import numpy as n
from . import paths
from .errors import classify_error
+from .diagnose import DIAGNOSTICS_JSON, diagnose_run, summary_line
+ from .extractors import DEFAULT_EXTRACTOR, get_extractor
+ from .extractors.base import read_extractor_name
+ from .extractors.hamer import (
+ detect_and_append,
+ find_body_cache,
+ read_hands_name,
+ skeleton_from_still,
+ skeleton_has_hands,
+ )
+ from .mixamo.hand_retarget import build_hand_mapping, load_hand_motion
-from .human_motion import HumanMotion, load_human_motion
+from .human_motion import HumanMotion, foot_contact_from_cache, load_human_motion
from .mixamo.animation import build_animation
from .mixamo.gltf import write_glb
from .mixamo.kinematics import quat_wxyz
@@@ -148,10 -151,25 +154,27 @@@ def run_pipeline
work_dir=run_dir / "cache",
device=device,
verbose=verbose,
+ detect_hands=detect_hands,
+ )
+ if detect_hands and skeleton_npz is not None and not skeleton_has_hands(motion_npz):
+ cache_dir = find_body_cache(Path(skeleton_npz).parent)
+ if cache_dir is None:
+ raise FileNotFoundError(
+ "hand detection needs the body cache next to the reused skeleton "
+ "(cache/*/0_input_video.mp4, vitpose.pt, bbx.pt)"
+ )
+ print("detecting hands on the reused skeleton")
+ detect_and_append(
+ cache_dir,
+ motion_npz,
+ load_human_motion(motion_npz).n_frames,
+ device=device,
+ verbose=verbose,
+ single_frame=image is not None or skeleton_from_still(motion_npz),
)
motion: HumanMotion = load_human_motion(motion_npz)
+ if motion.foot_contact is None and skeleton_npz is not None:
+ motion.foot_contact = foot_contact_from_cache(Path(skeleton_npz), motion.n_frames)
print(f"human motion {motion.n_frames} frames @ {motion.fps:g} fps")
stage = "retarget"
@@@ -167,8 -185,17 +190,19 @@@
print("retargeting")
frames = list(range(motion.n_frames))
+ hands = load_hand_motion(motion_npz, smooth_s=hand_smooth_s)
+ hand_mapping = None
+ if hands is not None:
+ hand_mapping = build_hand_mapping(asset.rig, hands.template_joints, verbose=verbose)
anim = build_animation(
- motion, mapping, frames, verbose=verbose, foot_lock=foot_lock, asset=asset
+ motion,
+ mapping,
+ frames,
+ verbose=verbose,
++ foot_lock=foot_lock,
++ asset=asset,
+ hands=hands,
+ hand_mapping=hand_mapping,
)
rotations_npz = run_dir / "mixamo_rotations.npz"
diff --cc pyproject.toml
index 16daeb3,c01722e..5ad08eb
--- a/pyproject.toml
+++ b/pyproject.toml
@@@ -7,7 -7,11 +7,12 @@@ dependencies =
"numpy",
"opencv-python",
"einops",
+ "scipy", # nearest-surface search in `m2mr diagnose` (also pulled in by gvhmr)
+ # Optional finger pass (`--detect-hands`): HaMeR + MANO. Not imported
+ # unless that flag is on.
+ "timm",
+ "smplx",
+ "scikit-image",
# Video -> 3D human skeleton. `preproc` = person detection/tracking,
# `rtmpose` = the ungated 2D-pose backend the pipeline uses.
"gvhmr[preproc,rtmpose]>=1.6",