Skip to content

Native Windows video motion capture with ExMR, FlowHMR and GVHMR, contact correction, humanoid retargeting, and FBX/VMD export.

Python

Update ExMR public API integration and bounded toe IK

toyxyze8475cff4623
diff --git a/README.md b/README.md
index 4e4b57b..474d99e 100644
--- a/README.md
+++ b/README.md
@@ -188,6 +188,7 @@ for conditions, per-model results and output differences.
- [User guide: installation, controls and settings](docs/USER_GUIDE.md)
- [Model guides: files, defaults, options and limitations](docs/models/README.md)
+- [Research papers and citations](docs/CITATIONS.md)
- [Recorded processing time, VRAM and RAM](docs/USER_GUIDE.md#recorded-processing-time-and-vram)
- [Resource modes and measured optimizations](docs/PERFORMANCE.md)
- [MAMMA: additional installation, model files and multi-video workflow](docs/MAMMA.md)
diff --git a/SOURCE_MANIFEST.json b/SOURCE_MANIFEST.json
index b6ba326..f140436 100644
--- a/SOURCE_MANIFEST.json
+++ b/SOURCE_MANIFEST.json
@@ -1,6 +1,6 @@
{
"schema": 1,
- "date": "2026-10-30",
+ "date": "2026-10-31",
"purpose": "Public source distribution; excludes model weights and runtime binaries",
"version": "git-source",
"files": [
@@ -26,8 +26,8 @@
},
{
"path": "README.md",
- "bytes": 9122,
- "sha256": "6b33954c96396e2f0be712adea9516ab1c0e050b3749f301bb49601a4c0bfc87"
+ "bytes": 9175,
+ "sha256": "e5cf105de43e78a691c2e224e1e996596a2d4803bfd4f375b25ec2b02a9d48f8"
},
{
"path": "RGBMoCap.cmd",
@@ -46,8 +46,8 @@
},
{
"path": "THIRD_PARTY_NOTICES.md",
- "bytes": 7646,
- "sha256": "76cb01055c4849441191ac4f5ea02c1829c76df7274743f3a19ae54726768d94"
+ "bytes": 7813,
+ "sha256": "37d98687a35d0ff41887e6895d96665c4ccc5f49386da2beac1247693cf1a3b2"
},
{
"path": "app.py",
@@ -96,18 +96,23 @@
},
{
"path": "docs/AGENT_GUIDE.md",
- "bytes": 28855,
- "sha256": "0c5bf9670e7993376b9ac6b6468d7c8d5b7134a66af9654950cb26c21ae702cf"
+ "bytes": 29976,
+ "sha256": "004b31957d249f0f4d02418d05fdc8c0744860fb7a738c02b70e1fb3e758722c"
},
{
"path": "docs/BUILD.md",
"bytes": 10223,
"sha256": "e14bd8897b0e567cc443ebdd295f6e0290157ef986bc9a44ce46d840136d2cf6"
},
+ {
+ "path": "docs/CITATIONS.md",
+ "bytes": 4748,
+ "sha256": "2ff56e6de80ae11315ac637a32c2bc5a1f04043665a1c6327a0b51ba58211d61"
+ },
{
"path": "docs/MAMMA.md",
- "bytes": 23344,
- "sha256": "7161d3ce639a2a7632cded345a3d2f4ae57823dfb4abba65ad6e26997c91bfc2"
+ "bytes": 23465,
+ "sha256": "eb1e97d8bb92d20847445678cc58ea6eea8b90e354186c8431748b16def1fbe1"
},
{
"path": "docs/MAMMA_AGENT_SETUP.md",
@@ -126,8 +131,8 @@
},
{
"path": "docs/VALIDATION.md",
- "bytes": 47178,
- "sha256": "2375b9be585f97c16e07ec3314f1b5cf7ae7aec6a811d07340872bcdd8a9887d"
+ "bytes": 51629,
+ "sha256": "6bc4706d45cdb0e767d1942722630b60e21a5d4e196eb1da0176d65168f07537"
},
{
"path": "docs/images/exmr-interaction-contact.png",
@@ -151,23 +156,23 @@
},
{
"path": "docs/models/EXMR.md",
- "bytes": 6441,
- "sha256": "77d2e4f447414996159ff32bab2eeea44af6da9e67d20c8eb97bf1cf6b3f52ee"
+ "bytes": 8147,
+ "sha256": "0081e43c413bab87a09d1b8303bf0755076c04fffcc578cb215d64566e80d84a"
},
{
"path": "docs/models/FLOWHMR.md",
- "bytes": 8204,
- "sha256": "2fd5844691a6a3dbd21d7db35b165648baf044a720895f42343adb0eed43a497"
+ "bytes": 8328,
+ "sha256": "0ca09d89c3a6a9fff248b2014a2f4d588be771203d43aa22e00be29ad4128332"
},
{
"path": "docs/models/GVHMR.md",
- "bytes": 5795,
- "sha256": "d2820d6bed07091b93d28f5a54129998801d3d96ef4dba11dfd62782ae614ab6"
+ "bytes": 5915,
+ "sha256": "a43b89cde13e9168431177655c9678a37cc74219436e055066b01137276ca09e"
},
{
"path": "docs/models/PROMPTHMR.md",
- "bytes": 14062,
- "sha256": "685160a1a11f585a6f1a80e29bb3ad7ea0937cddef9835a09502035a4a8cb700"
+ "bytes": 14194,
+ "sha256": "8ba469aba25a20d23514a72371cf9d2e121eecd7b7b41fcfc7a397c65d1ed0c2"
},
{
"path": "docs/models/README.md",
@@ -1156,8 +1161,13 @@
},
{
"path": "mocap/exmr_backend.py",
- "bytes": 20444,
- "sha256": "97247aaa6ad6901f2bee1dac4ee47e6372f35db1068492241121cd57dadb1432"
+ "bytes": 20661,
+ "sha256": "6d7c85ad5ee1341338be8375136808d5ea93adabbac3d6dc63fd9d6c178a1678"
+ },
+ {
+ "path": "mocap/exmr_camera.py",
+ "bytes": 1213,
+ "sha256": "6fa25021e9772fd7affe95e07d6157d8c5037a17d9c888d664db9b99ead2253b"
},
{
"path": "mocap/exmr_options.py",
@@ -1391,8 +1401,8 @@
},
{
"path": "mocap/models.py",
- "bytes": 29986,
- "sha256": "e7bfe4902919487ff8afe1ce1acb1f08c33a72c85611ff88c154f78ebd0ab9b6"
+ "bytes": 30979,
+ "sha256": "d97a6398a1dde3577bb37f0627a8666d48412e93ef9009f3033cd4b4ddd9e1e1"
},
{
"path": "mocap/motion_tools.py",
@@ -1951,13 +1961,13 @@
},
{
"path": "third_party/ExMR/README.md",
- "bytes": 9462,
- "sha256": "bc92d8dbf855b21b31fb3998e165c00c9ec9c9e75a3bca28865f6de4ac8aff1b"
+ "bytes": 12150,
+ "sha256": "95b8bf602a5db24226ecab773b558e749bbe635ad256309b178aa7aad5cd5f93"
},
{
"path": "third_party/ExMR/RGB_MOCAP_PROVENANCE.json",
- "bytes": 695,
- "sha256": "3322623b08c6c8d72d396d61a45371293462d9b9eb1e896045dbaea85f6e7ee1"
+ "bytes": 1016,
+ "sha256": "dcfadc134bc7beaed8b0253e2bde5eb26fdf41d8a376b0c5d0dfe0f008c6376a"
},
{
"path": "third_party/ExMR/THIRD_PARTY_NOTICES.md",
@@ -1969,10 +1979,25 @@
"bytes": 2072,
"sha256": "0e5eeb82752e47dfd01db8e13ccc4c5eba9bf83f53da8285523b8d3e87247aa3"
},
+ {
+ "path": "third_party/ExMR/constraints.txt",
+ "bytes": 1834,
+ "sha256": "ea109127c25ffc3c076c739f48580f788e917e5b8627ae194aaccc0b21549953"
+ },
+ {
+ "path": "third_party/ExMR/docs/INSTALL.md",
+ "bytes": 7486,
+ "sha256": "4c0fa9b82064c10e24fc4949227f1ac56087fa9880e35c890616012a72162ace"
+ },
+ {
+ "path": "third_party/ExMR/docs/OUTPUTS.md",
+ "bytes": 12851,
+ "sha256": "2e8b12f6fe5a3fd9545f186fdade94fcc76cf1d3130509a88b3e87fa0739da9f"
+ },
{
"path": "third_party/ExMR/exmr/__init__.py",
"bytes": 99,
- "sha256": "81b34ae480651383aeb822d1d67e6480549034f4ba751b078e2d6f55d1b9e19b"
+ "sha256": "5678d0e65b6426c07f2226cf75fc35e2ae594b6acbca1fe56db3b7597d20e4cc"
},
{
"path": "third_party/ExMR/exmr/assets.py",
@@ -1986,8 +2011,8 @@
},
{
"path": "third_party/ExMR/exmr/body_models/smplx_model.py",
- "bytes": 2581,
- "sha256": "bade2098a7bf9d88d78b361ef3a4029b165407ccbf70b81b78871556c1d69063"
+ "bytes": 3870,
+ "sha256": "a01d3a3c6e5f37cbe285477750eacc7df271fba2168c9b9a34f2c620605bc33d"
},
{
"path": "third_party/ExMR/exmr/body_models/smplx_skeleton.py",
@@ -1996,8 +2021,8 @@
},
{
"path": "third_party/ExMR/exmr/export.py",
- "bytes": 2293,
- "sha256": "2c04e35843ad25bd68fa135bd7e5a593ea87057add9efa4063160ba11f41c8b6"
+ "bytes": 9026,
+ "sha256": "cd791657a7ae1c75b4f468ff5d994ff9cd4b92c927fb4dbfaf8a9f4d4abdc09d"
},
{
"path": "third_party/ExMR/exmr/geometry/__init__.py",
@@ -2006,8 +2031,8 @@
},
{
"path": "third_party/ExMR/exmr/geometry/camera.py",
- "bytes": 3932,
- "sha256": "a67ba20e680785e8f99add358552560a0a59fecc8c889211f8a329f64aeca045"
+ "bytes": 4173,
+ "sha256": "ac18991c1912a3235535ebc8d8f89176e6667920d5f96e5d9d633c4de1e53ac0"
},
{
"path": "third_party/ExMR/exmr/geometry/kinematics.py",
@@ -2046,13 +2071,13 @@
},
{
"path": "third_party/ExMR/exmr/model/exmr.py",
- "bytes": 11007,
- "sha256": "a1ae9640f9c6795e1fe43997a76e87670f6c57a69f6a6ad2c2efa11477630535"
+ "bytes": 11623,
+ "sha256": "6e3a717275acd8e5409681fb9f608b8facc3b624e4821d2a4d47362490bc2bbd"
},
{
"path": "third_party/ExMR/exmr/model/global_traj.py",
- "bytes": 11356,
- "sha256": "7c26f3949a87d046755657ac184e844d99152627c84481f54c1250c3b4672d66"
+ "bytes": 15010,
+ "sha256": "1f08f147adfcba6b6aba654f38fdb9eee4458dfd5e4d542b985027f7ec46cb60"
},
{
"path": "third_party/ExMR/exmr/model/ik.py",
@@ -2071,8 +2096,8 @@
},
{
"path": "third_party/ExMR/exmr/pipeline.py",
- "bytes": 12737,
- "sha256": "3c6af5830f41eae7641ad5f7b0cce57533393c77ce738af9e4bc1e82ea9ee608"
+ "bytes": 21264,
+ "sha256": "a07902f2b2cf0c7ab802132ad62b19a3df70f5437955c7bbaa71032284aec2d7"
},
{
"path": "third_party/ExMR/exmr/preprocessing/__init__.py",
@@ -2081,13 +2106,13 @@
},
{
"path": "third_party/ExMR/exmr/preprocessing/body_features.py",
- "bytes": 7654,
- "sha256": "0c1185773cf2664bea2bab6cb91f32da9b83d709fde81cdfc63c5da9752dd308"
+ "bytes": 8434,
+ "sha256": "b85fc38e408df78bf063b5291d31ce9dae7321d5a19d597d38abec893cc6134c"
},
{
"path": "third_party/ExMR/exmr/preprocessing/hand_features.py",
- "bytes": 8651,
- "sha256": "d2d1af59b5c0e2edb44932262625d24db1e20b887beda510b0f437bf6806a39c"
+ "bytes": 8921,
+ "sha256": "a1ebc77933cd772700d0bac0789f41b7cbb52b4729964e66df876f381be2dc82"
},
{
"path": "third_party/ExMR/exmr/preprocessing/image_io.py",
@@ -2106,8 +2131,8 @@
},
{
"path": "third_party/ExMR/exmr/preprocessing/keypoints/rtmw.py",
- "bytes": 7668,
- "sha256": "6ff8d49b46e673e0dffeb45e73f7164ce276503093a0f1e4ee350f9eb966f7e4"
+ "bytes": 8047,
+ "sha256": "1e4207ed5814774dd923c0789f969ee0bed8383c10a3ce970fa23a7e64b12259"
},
{
"path": "third_party/ExMR/exmr/preprocessing/keypoints/sapiens2.py",
@@ -2116,18 +2141,18 @@
},
{
"path": "third_party/ExMR/exmr/preprocessing/tracker.py",
- "bytes": 7675,
- "sha256": "02ab4c306f38284ac5b2adc18ca91a77feaa16391e6b87edd3479ba3117c225b"
+ "bytes": 8300,
+ "sha256": "ab925f2193fe710fcfb9a379d2377779d2d48d6ad172f6903f5cb9ae2a292126"
},
{
"path": "third_party/ExMR/exmr/preprocessing/video.py",
- "bytes": 5179,
- "sha256": "cb11b338b781aebd1336da1a1d7b3d85824fbd46affdd0d7809793a46ad2b360"
+ "bytes": 7768,
+ "sha256": "14a603d7e29a0fdaf9dade4e4fc35524d430b3a8d79c5309e75e388c94886e68"
},
{
"path": "third_party/ExMR/exmr/preprocessing/visual_odometry.py",
- "bytes": 13442,
- "sha256": "79207f24f7c285a4767cb291b4021299dcfd4460b8f589dfe8b1872196a32d93"
+ "bytes": 14783,
+ "sha256": "1806c986cab846829865605af537d264c8cd822941bc59e914ce067e1a898ddb"
},
{
"path": "third_party/ExMR/exmr/vis/__init__.py",
@@ -2136,18 +2161,18 @@
},
{
"path": "third_party/ExMR/exmr/vis/render.py",
- "bytes": 5336,
- "sha256": "956974bfb7a740a57ab6ca84f35048f93a9b856f52b7aaa67f04223e8c51690f"
+ "bytes": 7406,
+ "sha256": "80892f41655b66c66712e3e0f59666792d3b45b5e9b77a53eea23afc6efb23fc"
},
{
"path": "third_party/ExMR/exmr/vis/renderer.py",
- "bytes": 7150,
- "sha256": "474f3d9112bb247fde434786ab3d766e18a16c2c5f9bab9ccc37012d887ec7ac"
+ "bytes": 7344,
+ "sha256": "88de015551aa25c6ef2e9c953a4801e8cd1f8df0590d73d7d6551ee849561547"
},
{
"path": "third_party/ExMR/exmr/vis/video_writer.py",
- "bytes": 4303,
- "sha256": "eda0110342294642a6620d2e2aee682346817481225f941cea84d66595b2a387"
+ "bytes": 4603,
+ "sha256": "fd1f8c4c52255578cabb1f28444731dbdc823a16d9cc9110d9fbd0cb9a422754"
},
{
"path": "third_party/ExMR/licenses/HumanML3D_LICENSE.txt",
@@ -2177,12 +2202,12 @@
{
"path": "third_party/ExMR/pyproject.toml",
"bytes": 1449,
- "sha256": "1af3c3a4f1fdf3c9ac8999cf129c0f441b778d7382717f6c1b394c10a43399c5"
+ "sha256": "b6405f5845bdabcb299568dd55a865bf82fc0541476d7fdccfe8693f64fb977f"
},
{
"path": "third_party/ExMR/requirements.txt",
- "bytes": 910,
- "sha256": "37bdbcc3f0bd999ed5a24ac586a6aa1b49de3cc27838797824727292d1c4824b"
+ "bytes": 1034,
+ "sha256": "6b0e043a301eeaf9866fabeeb3a49ffd78b9ae9bd0b7e5c9c0cfc8ed917c615c"
},
{
"path": "third_party/ExMR/third_party/dinov3/.docstr.yaml",
@@ -4906,13 +4931,13 @@
},
{
"path": "third_party/ExMR/tools/demo.py",
- "bytes": 6035,
- "sha256": "0365feaa93e5223b6ea18600820760ade8cd455ac6fea6ee43219877721a0daa"
+ "bytes": 8299,
+ "sha256": "8a6c5befe6108441c95aa3b0d7555543d42bffc4d620077da1f09fb563861875"
},
{
"path": "third_party/ExMR/tools/download_models.py",
- "bytes": 18773,
- "sha256": "41ef41411ca52efd24420459d61f9ee4a107bc57d03ecabf90f34aff18bd9ba2"
+ "bytes": 19969,
+ "sha256": "59759a15093e1023c85fb5e3093935c9581deb167cec416ee50d3b69cd27c8e4"
},
{
"path": "third_party/FlowHMR/LICENSE",
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 2d60af0..a707303 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -51,7 +51,9 @@ Other runtime packages retain their included licenses. Supporting notices includ
- GVHMR: copyright 2022–2023, 3D Vision Group, Zhejiang University.
ExMR / FootMR: copyright 2025–2026, Leibniz University Hannover, with retained
GVHMR notices. Follow the upstream publication/citation instructions, including
- Wehrbein and Rosenhahn (FootMR, 3DV 2026).
+ Wehrbein and Rosenhahn (ExMR, arXiv:2610.26213; FootMR, 3DV 2026),
+ and the original GVHMR work. [Papers and BibTeX](docs/CITATIONS.md) cover
+ the five supported motion models and optional refinement models.
- Kimodo MotionCorrection: copyright 2026, NVIDIA Corporation & Affiliates.
Local changes add explicit contact targets, bounded solving and anatomical guards.
- OSNet: Kaiyang Zhou; original MIT notices and model-zoo provenance are retained.
diff --git a/docs/AGENT_GUIDE.md b/docs/AGENT_GUIDE.md
index 7d0a125..5ee7b0e 100644
--- a/docs/AGENT_GUIDE.md
+++ b/docs/AGENT_GUIDE.md
@@ -42,6 +42,21 @@ retain actual memory monitoring and deterministic producer cleanup.
## Models and model files
+ExMR's integrated v0.1.5 uses public `pipeline.hand_boxes`, `model_inputs` and
+`ExMR.from_pretrained` with direct model forward. Keep stage-scoped model reuse
+and the existing Low Memory/prefetch paths. Its upstream toe IK limits target
+displacement to 0.03 m per axis. RGB MoCap passes `normalize_world=False` through
+an explicit local option to preserve the existing world/camera frame. SimpleVO
+uses a documented frame-reader/count adapter over the canonical working video;
+do not switch it to JPEG pixels or extract duplicate frames just for camera
+enumeration. Keep the app's shared contact policy and manual timing precedence:
+upstream `foot_contacts` is not connected to correction. API/solver source hashes
+and provenance are part of stage receipts. Model Manager also downloads the
+official `models/exmr/config.json` (180 bytes) from the same pinned Hugging Face
+revision as the weights, with SHA-256 validation and a separate import row.
+It is checkpoint metadata, not app settings. Existing weight and runtime pins
+are unchanged. See [validation](VALIDATION.md#exmr-public-api-and-bounded-toe-ik-2026-10-31).
+
| Model | Practical use | Hands / options |
| --- | --- | --- |
| ExMR | Default; generally fast, good quality in the project's subjective tests. SMPL-X. | Fingers included; static/moving camera and smoothing options. |
diff --git a/docs/CITATIONS.md b/docs/CITATIONS.md
new file mode 100644
index 0000000..302fbf3
--- /dev/null
+++ b/docs/CITATIONS.md
@@ -0,0 +1,124 @@
+# Research citations
+
+RGB MoCap integrates the research projects below. Please credit the methods used
+in your work and follow their upstream citation and license requirements.
+These references do not change the separate licenses or permissions for code,
+model weights, body data or input footage. Supporting models retain their own
+upstream acknowledgements; see [third-party notices](../THIRD_PARTY_NOTICES.md).
+
+## ExMR
+
+[Paper](https://arxiv.org/abs/2610.26213) · [Official citation](https://github.com/twehrbein/ExMR/blob/main/README.md)
+
+```bibtex
+@Article{wehrbein26exmr,
+ author = {Wehrbein, Tom and Rosenhahn, Bodo},
+ title = {{ExMR}: Extremity Motion Refinement for Monocular Human Motion Capture},
+ journal = {arXiv preprint arXiv:2610.26213},
+ year = {2026},
+}
+```
+
+## FlowHMR
+
+[Paper](https://arxiv.org/abs/2610.03691) · [Official citation](https://github.com/flowhmr/flowhmr/blob/main/README.md)
+
+```bibtex
+@misc{wang2026flowhmr,
+ title={FlowHMR: Physically Plausible Motion Capture from Video},
+ author={Zhanke Wang and Chengfeng Zhao and Qing Shuai and Jingzhong Lin and Heng Li and Zeyu Ling and Yuxin Wen and Jing Li and Di Kang and Chunchao Guo and Linchao Bao},
+ year={2026},
+ eprint={2610.03691},
+ archivePrefix={arXiv},
+ primaryClass={cs.CV},
+ url={https://arxiv.org/abs/2610.03691},
+}
+```
+
+## GVHMR
+
+[Paper](https://arxiv.org/abs/2409.06662) · [Official citation](https://github.com/zju3dv/GVHMR/blob/main/README.md)
+
+```bibtex
+@inproceedings{shen2024gvhmr,
+ title={World-Grounded Human Motion Recovery via Gravity-View Coordinates},
+ author={Shen, Zehong and Pi, Huaijin and Xia, Yan and Cen, Zhi and Peng, Sida and Hu, Zechen and Bao, Hujun and Hu, Ruizhen and Zhou, Xiaowei},
+ booktitle={SIGGRAPH Asia Conference Proceedings},
+ year={2024}
+}
+```
+
+## MAMMA
+
+[Paper](https://arxiv.org/abs/2506.13040) · [Official citation](https://github.com/cuevhv/mamma/blob/main/README.md)
+
+```bibtex
+@inproceedings{cuevas2026mamma,
+ title = {{MAMMA}: {Markerless Accurate Multi-person Motion Acquisition}},
+ author = {Cuevas Velasquez, Hanz and Yiannakidis, Anastasios and Shin, Soyong and Becherini, Giorgio and H{\"o}schle, Markus and Tesch, Joachim and Obersat, Taylor and Alexiadis, Tsvetelina and Halilaj, Eni and Black, Michael J.},
+ booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)},
+ year = {2026}
+}
+```
+
+## PromptHMR
+
+[Paper](https://arxiv.org/abs/2504.06397) · [Official citation](https://github.com/yufu-wang/PromptHMR/blob/main/README.md)
+
+```bibtex
+@article{wang2025prompthmr,
+ title={PromptHMR: Promptable Human Mesh Recovery},
+ author={Wang, Yufu and Sun, Yu and Patel, Priyanka and Daniilidis, Kostas and Black, Michael J and Kocabas, Muhammed},
+ journal={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
+ year={2025}
+}
+```
+
+## FootMR
+
+[Paper](https://doi.org/10.1109/3DV69130.2026.00088) · [Official citation](https://github.com/twehrbein/FootMR/blob/main/README.md)
+
+```bibtex
+@InProceedings{wehrbein26footmr,
+ author = {Wehrbein, Tom and Rosenhahn, Bodo},
+ title = {Improving 3D Foot Motion Reconstruction in Markerless Monocular Human Motion Capture},
+ booktitle = {International Conference on 3D Vision (3DV)},
+ year = {2026},
+ pages = {871--881},
+ doi = {10.1109/3DV69130.2026.00088},
+}
+```
+
+## HTD-Refine
+
+[Paper](https://arxiv.org/abs/2605.26879) · [Official citation](https://github.com/ant-research/HTD-Refine/blob/main/README.md)
+
+```bibtex
+@inproceedings{wei2026htdrefine,
+ title = {Natural Human Motion Recovery by Aligning High-Order Temporal Dynamics from Monocular Videos},
+ author = {Wei, Dingkun and Shen, Zehong and Xia, Yan and Pavlakos, Georgios and Shen, Yujun and Zhou, Xiaowei},
+ booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)},
+ year = {2026}
+}
+```
+
+## HandFlow
+
+[Paper](https://arxiv.org/abs/2607.11221) · [Official citation](https://github.com/mxxu00/HandFlow/blob/main/README.md)
+
+```bibtex
+@misc{xu2026handflow,
+ title={HandFlow: Fully Generative 4D Hand Recovery with Flow Matching},
+ author={Mingxi Xu and Bowen Duan and Yi Gu and Zhengyang Shen and Renjing Xu and Yutao Yue},
+ year={2026},
+ eprint={2607.11221},
+ archivePrefix={arXiv},
+ primaryClass={cs.CV},
+ url={https://arxiv.org/abs/2607.11221}
+}
+```
+
+ExMR's authors also request acknowledgement of FootMR and the original GVHMR
+work. Cite optional HTD-Refine and HandFlow when using those add-ons. The
+application's use of Kimodo MotionCorrection does not imply use of the Kimodo
+text-to-motion generator.
diff --git a/docs/MAMMA.md b/docs/MAMMA.md
index 7cfd31d..389e38d 100644
--- a/docs/MAMMA.md
+++ b/docs/MAMMA.md
@@ -374,3 +374,7 @@ this installation's paths; copying that folder alone is not a supported setup
method. For development environments and detailed checks, see
[the agent installation/native-build runbook](MAMMA_AGENT_SETUP.md),
[Build from source](BUILD.md) and [Validation](VALIDATION.md).
+
+## Citation
+
+[MAMMA paper](https://arxiv.org/abs/2506.13040) · [Research citations and BibTeX](CITATIONS.md#mamma)
diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md
index d454642..7d2f195 100644
--- a/docs/VALIDATION.md
+++ b/docs/VALIDATION.md
@@ -700,3 +700,74 @@ the first 22 body/wrist joint positions were unchanged. Four original/corrected
FBXs imported into Blender with 52 bones and 30 finger bones. Local finger
rotation variation across the 32 frames was zero. Source projects/raw caches were
not changed. The runtime and AI inference calculations were not modified.
+
+
+## ExMR public API and bounded toe IK (2026-10-31)
+
+The integrated upstream source is v0.1.5, commit
+`57e4824b9c532b52ed1c8b12c44000ad41ef4c4c`, retaining the documented Windows,
+Low Memory, bounded prefetch and stage-scoped reuse adaptations. Public
+`hand_boxes`, `model_inputs`, `ExMR.from_pretrained` and direct model forward
+replace private pipeline calls. Upstream toe IK now limits its target offset to
+0.03 m per axis. Existing weights, runtime package pins and other model backends
+are unchanged.
+
+Only those numerical changes were adopted. The app keeps its existing world
+frame through an explicit local `normalize_world=False` option (generic upstream
+default remains enabled). The upstream Boolean foot-contact detector is not
+used by app correction. Shared contact code and manual timing precedence remain
+unchanged. Source/API/solver hashes invalidate outdated ExMR stage receipts;
+opening saved projects does not initiate reconstruction.
+
+- Seven cached-feature actor segments from five real scenes (997 actor frames)
+ produced tensor-exact camera/world parameters and static-confidence logits
+ against the independently verified toe-only reference. Scenes included two
+ dancers, burpees, stairs, moving-camera motion and two-person interaction.
+- Fresh 60- and 45-frame actors passed keypoint, body-feature, hand-feature and
+ motion stages in Automatic and Low Memory. Model instances were reused
+ sequentially within each phase and released on session exit. Observed stage
+ sums were 46.69 and 53.00 seconds; these single runs are not a controlled
+ speedup benchmark or universal performance promise.
+- Original/corrected meshes, paired shared cameras and shared-floor correction
+ completed. Eight actual app FBX exports imported in Blender 4.5 with 52 bones,
+ Hips root, finite bone-only keys and rest geometry distinct from animation.
+- The new SimpleVO JPEG-input path differed substantially on a moving-camera
+ sample. A small explicit frame-reader/count adapter retains the old canonical
+ video pixels without extracting another JPEG sequence. A 267-frame Unicode-path
+ test reproduced old rotations within 0.0000014 degrees; repeated calls reused
+ the cache without rewriting it. Neither estimate was scored against camera
+ ground truth.
+- Updated stale inference receipts recomputed successfully; an immediate repeat
+ hit the cache without rewriting motion. Changing the solver hash invalidated
+ the stage identity. Manual intervals remained authoritative when automatic
+ confidence was zero.
+
+The separate contact-policy comparison did not justify replacing shared contact
+detection. On the stairs segment, maximum frame-to-frame change of *added knee
+flexion* decreased from 3.553 to 1.983 degrees with the new toe IK and current
+contact policy, but rose to 4.114 degrees with the official Boolean timings used
+directly. This is not total knee jitter or error against motion ground truth.
+The body-height-only gate excluded just two frames across the tested segments;
+the existing large burpee transition remained. No blanket contact-quality claim
+is made. No clean Windows installation or second GPU was tested, and the other
+four models were not fully reinferred for this ExMR-only integration. Private
+test programs, footage, registered bodies and outputs remain outside the public
+source distribution.
+
+
+## Official ExMR checkpoint metadata (2026-10-31)
+
+Model Manager includes `ExMR configuration` (`models/exmr/config.json`, 180
+bytes), pinned to the same Hugging Face revision as the existing ExMR weights.
+Download All and the row's Auto Download use the official HTTPS endpoint and
+SHA-256 validation. Manual Download and Import use that same revision. It is
+checkpoint metadata; it does not alter model architecture or app settings.
+
+The actual download passed size/hash checks in an isolated data folder. A second
+call performed no network request or file rewrite. Invalid manual imports were
+rejected while preserving the valid file; a valid import succeeded. Offscreen
+Qt checks confirmed the row only appears for ExMR, changes to Ready after
+validation and leaves other model scopes unchanged. The development app also
+downloaded and verified its own copy. Test artifacts and model files remain
+outside the public source manifest. This metadata-only registration does not
+require a runtime reinstall or a new checkpoint.
diff --git a/docs/models/EXMR.md b/docs/models/EXMR.md
index 952fb9b..71ea44e 100644
--- a/docs/models/EXMR.md
+++ b/docs/models/EXMR.md
@@ -19,6 +19,7 @@ Select **ExMR > Model Manager** and prepare the listed files. Key assets are:
| Asset | Location under the app's `models/` folder |
| --- | --- |
| ExMR weights | `exmr/exmr.safetensors` |
+| Official ExMR checkpoint metadata | `exmr/config.json` |
| Sapiens2 pose weights | `exmr/sapiens2_1b_pose.safetensors` |
| SMPL-X v1.1 neutral body | `body_models/smplx/SMPLX_NEUTRAL.npz` |
| MANO right hand | `body_models/mano/MANO_RIGHT.pkl` |
@@ -27,6 +28,11 @@ Select **ExMR > Model Manager** and prepare the listed files. Key assets are:
Model Manager also lists shared tracking dependencies. Use its exact supported
files and import checks; do not substitute arbitrary checkpoint versions.
+**Download All** includes the small public `config.json` (180 bytes), or use
+**Auto Download** in the **ExMR configuration** row. The metadata and weights
+are pinned to the same official Hugging Face revision and verified by SHA-256.
+Manual Download and Import are also available. This is checkpoint metadata,
+not a file for changing the app's camera, smoothing or correction settings.
Registered SMPL-X/MANO and gated SAM 3D Body files may require manual download.
The shared `flowhmr` and `handflow` folder names do not mean you must run those
models or enable GVHMR's HandFlow add-on. ExMR uses these assets directly.
@@ -99,3 +105,33 @@ or free resources if necessary. Historical [processing/VRAM measurements](../USE
are individual runs, not minimum specifications. See [validation](../VALIDATION.md)
for the tested PC and scope, and [licenses](../../THIRD_PARTY_NOTICES.md) for
upstream restrictions.
+
+## Integrated upstream update
+
+The app uses ExMR v0.1.5's public input helpers and model API. Its toe IK target
+is limited to a 3 cm offset per axis from the network's target, reducing excessive
+ankle changes in the tested motions. Existing weights and the pinned ExMR runtime
+are reused. The app keeps its existing scene frame, camera sampling and shared
+contact-correction policy; the upstream Boolean foot-contact detector does not
+replace the app's automatic or manually edited lock timings.
+
+New reconstruction uses the updated solver and refreshes its result receipts.
+Opening an existing project does not automatically rerun inference or rewrite
+its saved motion. See [validation](../VALIDATION.md#exmr-public-api-and-bounded-toe-ik-2026-10-31)
+for the measured scope and limitations.
+
+## Citation
+
+[ExMR paper](https://arxiv.org/abs/2610.26213) · [Research citations and BibTeX](../CITATIONS.md#exmr)
+
+Please also credit FootMR and the original GVHMR work, as requested by the
+ExMR authors.
+
+```bibtex
+@Article{wehrbein26exmr,
+ author = {Wehrbein, Tom and Rosenhahn, Bodo},
+ title = {{ExMR}: Extremity Motion Refinement for Monocular Human Motion Capture},
+ journal = {arXiv preprint arXiv:2610.26213},
+ year = {2026},
+}
+```
diff --git a/docs/models/FLOWHMR.md b/docs/models/FLOWHMR.md
index 75c00bd..b44b7d0 100644
--- a/docs/models/FLOWHMR.md
+++ b/docs/models/FLOWHMR.md
@@ -114,3 +114,7 @@ can still exceed available memory. Historical [time/VRAM records](../USER_GUIDE.
include camera estimation and predate Fast SAM; they are not predictions or
minimum specifications. See [validation](../VALIDATION.md) and
[upstream licenses](../../THIRD_PARTY_NOTICES.md).
+
+## Citation
+
+[FlowHMR paper](https://arxiv.org/abs/2610.03691) · [Research citations and BibTeX](../CITATIONS.md#flowhmr)
diff --git a/docs/models/GVHMR.md b/docs/models/GVHMR.md
index d8851f1..9675cd1 100644
--- a/docs/models/GVHMR.md
+++ b/docs/models/GVHMR.md
@@ -99,3 +99,7 @@ to fit; no option guarantees a particular duration on every PC. Historical
include HTD, FootMR and HandFlow and are individual observations, not minimum
specifications. See [validation](../VALIDATION.md) and
[licenses](../../THIRD_PARTY_NOTICES.md).
+
+## Citation
+
+[GVHMR paper](https://arxiv.org/abs/2409.06662) · [Research citations and BibTeX](../CITATIONS.md#gvhmr)
diff --git a/docs/models/PROMPTHMR.md b/docs/models/PROMPTHMR.md
index abbacea..73eb512 100644
--- a/docs/models/PROMPTHMR.md
+++ b/docs/models/PROMPTHMR.md
@@ -225,3 +225,7 @@ restricts use to non-commercial scientific research. RGB MoCap's MIT license
does not relicense it, supporting checkpoints or registered body data. Restricted
source is downloaded into the user's private runtime; weights/body models are not
bundled. SAM2, Detectron2, ViTPose and other components retain their own terms.
+
+## Citation
+
+[PromptHMR paper](https://arxiv.org/abs/2504.06397) · [Research citations and BibTeX](../CITATIONS.md#prompthmr)
diff --git a/mocap/exmr_backend.py b/mocap/exmr_backend.py
index 114ad4f..ae78cbf 100644
--- a/mocap/exmr_backend.py
+++ b/mocap/exmr_backend.py
@@ -15,7 +15,7 @@ from .result_artifacts import file_stat
from .exmr_options import saved
STAGES=('exmr_preprocess','exmr_features','exmr')
-VERSION=1
+VERSION=2
LINKS={'exmr':'exmr/exmr.safetensors','smplx':'body_models/smplx/SMPLX_NEUTRAL.npz',
'exmr_sapiens':'sapiens2/sapiens2_1b_pose.safetensors',
'flow_sam':'sam-3d-body-dinov3/model.ckpt','flow_sam_config':'sam-3d-body-dinov3/model_config.yaml',
@@ -101,7 +101,7 @@ def camera(project,emit):
"""One rotation estimate for the whole scene, sliced for visible takes."""
import torch
root=scene_root(project);state=json.loads((root/'project.json').read_text(encoding='utf-8'))
- config=saved(root,state);context=dict(input=file_stat(root/'input.mp4'),frames=state['frames'],static=config['static_camera'],version=1)
+ config=saved(root,state);context=dict(input=file_stat(root/'input.mp4'),frames=state['frames'],static=config['static_camera'],version=3,odometry=sha256(UPSTREAM/'ExMR/exmr/preprocessing/visual_odometry.py'),reader=sha256(Path(__file__).with_name('exmr_camera.py')))
receipt=root/'exmr_camera.json';path=root/'exmr_camera.npy'
valid=False
try:valid=json.loads(receipt.read_text())['identity']==context and json.loads(receipt.read_text())['output']==file_stat(path)
@@ -113,8 +113,8 @@ def camera(project,emit):
if config['static_camera']:rotations=np.broadcast_to(np.eye(3,dtype=np.float32),(state['frames'],3,3)).copy()
else:
emit('progress',current=0,total=0,message='ExMR: estimate one scene camera rotation (SimpleVO)')
- from exmr.pipeline import _simplevo_rotations
- rotations=np.asarray(_simplevo_rotations(root/'input.mp4'),np.float32)
+ from .exmr_camera import rotations as estimate_rotations
+ rotations=np.asarray(estimate_rotations(root/'input.mp4',state['frames']),np.float32)
if rotations.shape!=(state['frames'],3,3) or not np.isfinite(rotations).all():raise ValueError('ExMR camera has incomplete frames')
temporary=root/'exmr_camera.partial.npy';np.save(temporary,rotations);os.replace(temporary,path)
atomic_json(receipt,dict(identity=context,output=file_stat(path)))
@@ -146,6 +146,9 @@ def identity(project,stage):
}[stage]},
feature_decoder={name:sha256(UPSTREAM/'ExMR/third_party/sam-3d-body/sam_3d_body/models'/name)
for name in ('decoders/promptable_decoder.py','meta_arch/sam3d_body.py')} if stage=='exmr_features' else {},
+ upstream_api=sha256(UPSTREAM/'ExMR/exmr/pipeline.py'),
+ motion_solver={name:sha256(UPSTREAM/'ExMR/exmr'/name) for name in
+ ('model/exmr.py','model/global_traj.py','model/ik.py','geometry/camera.py')} if stage=='exmr' else {},
code=code_hash(Path(__file__)),upstream=sha256(UPSTREAM/'ExMR/RGB_MOCAP_PROVENANCE.json'))
@@ -229,13 +232,11 @@ def run_stage(project,stage,result,emit,force=False,feature_phase=None):
root,weights=activate()
from .model_session import acquire,model_key,release
from exmr import pipeline as P
- from exmr.assets import Assets
with np.load(project/'tracking.npz',allow_pickle=False) as tracking:
boxes=torch.from_numpy(tracking['boxes'].copy()).float();k=torch.from_numpy(tracking['K'].copy()).float()
if boxes.shape!=(n,4) or not torch.isfinite(boxes).all():raise ValueError('ExMR actor tracking has the wrong frame count')
if k.ndim==2:k=k[None].repeat(n,1,1)
if tuple(k.shape)!=(n,3,3) or not torch.isfinite(k).all():raise ValueError('Invalid original camera intrinsics')
- from exmr.preprocessing.keypoints.mappings import COCO23,COCO63_LEFT_HAND,COCO63_RIGHT_HAND
if stage=='exmr_preprocess':
from exmr.preprocessing.keypoints.sapiens2 import Sapiens2Keypoints
emit('progress',current=0,total=n,message='ExMR: body, hand and foot keypoints (Balanced)')
@@ -280,10 +281,9 @@ def run_stage(project,stage,result,emit,force=False,feature_phase=None):
emit('complete',stage=stage,output=str(project/'exmr_body_features.pt'),cached=body_valid,elapsed=time.monotonic()-started)
return
prepare_mano(root,weights)
- from exmr.preprocessing.hand_features import HamerHandFeatures,hand_boxes_from_keypoints
- from exmr.preprocessing.keypoints import VISIBILITY_THRESHOLD
- points=load(project/'exmr_keypoints.pt');threshold=VISIBILITY_THRESHOLD['sapiens2']
- hand_boxes=torch.stack([hand_boxes_from_keypoints(points[:,COCO63_LEFT_HAND],threshold),hand_boxes_from_keypoints(points[:,COCO63_RIGHT_HAND],threshold)],1)
+ from exmr.preprocessing.hand_features import HamerHandFeatures
+ points=load(project/'exmr_keypoints.pt')
+ hand_boxes=P.hand_boxes(points,'sapiens2')
emit('progress',current=0,total=n,message='ExMR: left and right hand features')
def hand_features(low):
model=acquire(model_key('hamer',*[BY_KEY[key].path for key in ('hand_hamer','hand_mean','mano_right')],low_memory=low),
@@ -293,19 +293,23 @@ def run_stage(project,stage,result,emit,force=False,feature_phase=None):
values=memory_run('ExMR hand features',hand_features,5.5,emit)
save_tensor(values,project/'exmr_hand_features.pt')
else:
- from exmr.geometry.camera import bbx_xys_from_xyxy,cam_angvel_from_rotations
config=saved(scene_root(project));rotations=camera(project,emit)
if len(rotations)!=n:raise ValueError('ExMR take camera and motion lengths differ')
- data=dict(kp2d=load(project/'exmr_keypoints.pt')[:,COCO23].clone(),bbx_xys=bbx_xys_from_xyxy(boxes,base_enlarge=1.2).float(),
- bbx_xyxy=boxes,K_fullimg=k,cam_angvel=cam_angvel_from_rotations(rotations),
- body_feat=load(project/'exmr_body_features.pt'),hand_feat=load(project/'exmr_hand_features.pt'))
+ data=P.model_inputs(load(project/'exmr_keypoints.pt'),boxes,k,rotations,
+ load(project/'exmr_body_features.pt'),load(project/'exmr_hand_features.pt'),'sapiens2')
emit('progress',current=0,total=n,message='ExMR: reconstruct and refine full body, feet and fingers')
from exmr.model.exmr import ExMR
- assets=Assets(weights)
model=acquire(model_key('exmr',BY_KEY['exmr'].path,BY_KEY['smplx'].path),
- lambda:ExMR.from_pretrained(assets.exmr,assets.smplx))
+ lambda:ExMR.from_pretrained(BY_KEY['exmr'].path,BY_KEY['smplx'].path))
try:
- native=P._run_model(data,P.Options(static_cam=config['static_camera'],smoothing=config['smoothing'],snap_to_ground=False,render=False),state['fps'],assets,model=model)
+ with torch.inference_mode():
+ output=model(**{key:value[None].cuda() for key,value in data.items()},
+ static_cam=config['static_camera'],snap_to_ground=False,
+ smooth_incam=False,smooth_global=config['smoothing']!='none',fps=state['fps'],
+ normalize_world=False)
+ native={space:{key:value[0].cpu() for key,value in output[space].items()} for space in ('smplx_incam','smplx_global')}
+ native.update(static_conf_logits=output['static_conf_logits'][0].cpu(),K_fullimg=k,bbx_xyxy=boxes)
+ del output
finally:release(model)
del model
native['fps']=state['fps'];validate_native(native,n)
diff --git a/mocap/exmr_camera.py b/mocap/exmr_camera.py
new file mode 100644
index 0000000..08f218a
--- /dev/null
+++ b/mocap/exmr_camera.py
@@ -0,0 +1,28 @@
+"""Preserve the evaluated camera pixels while using ExMR's public SimpleVO.
+
+The input is RGB MoCap's already rotated, constant-frame-rate working video,
+not the user's original file. The estimator and its matching settings are
+unchanged. The small upstream frame_reader extension is explicit in provenance.
+"""
+import numpy as np
+
+def rotations(video_path, frame_count):
+ import imageio.v3 as iio
+ from exmr.preprocessing.visual_odometry import SimpleVO
+ def pixels(indices):
+ wanted=list(indices)
+ if not wanted:return
+ iterator=iio.imiter(video_path,plugin='pyav',thread_type='FRAME',
+ filter_sequence=[('scale','iw*0.5:ih*0.5')])
+ position=0
+ try:
+ for index,image in enumerate(iterator):
+ if index==wanted[position]:
+ yield np.ascontiguousarray(image[:,:,::-1])
+ position+=1
+ if position==len(wanted):return
+ raise ValueError('Canonical camera video has incomplete frames')
+ finally:
+ close=getattr(iterator,'close',None)
+ if close:close()
+ return SimpleVO(scale=1.,progress=False,frame_reader=pixels)(frame_count=frame_count)
diff --git a/mocap/models.py b/mocap/models.py
index 0d41e8d..de1101a 100644
--- a/mocap/models.py
+++ b/mocap/models.py
@@ -83,10 +83,14 @@ MODELS_LIST.extend([
expected_sha256='45d60aa3b27ef9107a7afd4e00808f307fd91111e1cfa35afd5c4a62de264767'),
])
SAM_MANUAL_FILES = {'flow_sam': 'model.ckpt', 'flow_sam_config': 'model_config.yaml', 'flow_mhr': 'assets/mhr_model.pt'}
+EXMR_REV = '8debd2e34262fcc63384f7e04d39ca784b0aec21'
MODELS_LIST.extend([
Model('exmr','Motion / ExMR','exmr/exmr.safetensors','https://huggingface.co/twehrbein/ExMR',minimum_bytes=235766520,
- download_url='https://huggingface.co/twehrbein/ExMR/resolve/8debd2e34262fcc63384f7e04d39ca784b0aec21/exmr.safetensors',
+ download_url=f'https://huggingface.co/twehrbein/ExMR/resolve/{EXMR_REV}/exmr.safetensors',
expected_sha256='8d3947310c30444ec59dae4662574d7a32bf83af30320eeac87146529ff2fda5'),
+ Model('exmr_config','ExMR configuration','exmr/config.json','https://huggingface.co/twehrbein/ExMR',minimum_bytes=180,
+ download_url=f'https://huggingface.co/twehrbein/ExMR/resolve/{EXMR_REV}/config.json',
+ expected_sha256='b29ad86d7916a7f54154c1a20fb07d3bc9d794da4d671c88ba0cf75a5cec8c43'),
Model('exmr_sapiens','Body / Hand / Foot Keypoints / Sapiens2 1B','exmr/sapiens2_1b_pose.safetensors','https://huggingface.co/facebook/sapiens2-pose-1b',minimum_bytes=6079194752,
download_url='https://huggingface.co/facebook/sapiens2-pose-1b/resolve/f5fed8b97b99698d5eea1d14ff0855d0b4c3f000/sapiens2_1b_pose.safetensors',
expected_sha256='2dab7014a17e99e460c18817325a71dd7a81ce48d87027f01c2ee7d7b3af969f'),
@@ -98,6 +102,7 @@ MODELS_LIST.extend(Model(**entry) for entry in PHMR_ASSETS)
BY_KEY = {model.key: model for model in MODELS_LIST}
if len(BY_KEY)!=len(MODELS_LIST):raise ValueError('Duplicate model identifiers in the model registry.')
MANUAL_INSTRUCTIONS = {
+ 'exmr_config': 'Download config.json using the Supported file link below. It is the official ExMR checkpoint metadata, pinned to the same revision as exmr.safetensors. Return to the ExMR configuration row and click Import. Import the original JSON file without editing or renaming it. Auto Download can obtain this small public file directly.',
'mano_right': '1. Open the Recommended download link below, or click Open Download Page. This opens the official download server for the exact archive. Sign in and accept the provider terms; register on the official MANO website if needed.\n2. Download mano_v1_2.zip. If browsing the MANO website instead, this is Models & Code > Models & Code.\n3. Extract the ZIP and open mano_v1_2/models.\n4. Return to Hand Model / MANO Right, click Import and select MANO_RIGHT.pkl. Keep this PKL file intact.\nHandFlow uses a right-hand canonical model for both hands, reflecting the left result back. The separate SMPL-H downloads cannot replace this hand model.',
'smplx': '1. Open the SMPL-X download page below. Register or sign in and accept the provider terms.\n2. In the "SMPL-X Model" section, choose "Download SMPL-X v1.1 (NPZ+PKL, 830 MB)". Choose the standard v1.1 download listed above.\n3. Download models_smplx_v1_1.zip and extract the outer ZIP archive.\n4. Inside the extracted folder, open models, then smplx. Choose SMPLX_NEUTRAL.npz. Leave this NPZ file intact.\n5. Return to the Body Model / SMPL-X Neutral row and click Import. Select that single NPZ file; Missing changes to Ready after validation.',
@@ -127,7 +132,8 @@ for _key, _file in SAM_MANUAL_FILES.items():
'The app does not need your account password or access token.')
MANUAL_DETAILS = {
- 'exmr':dict(selection='twehrbein/ExMR > Files and versions > exmr.safetensors',location='exmr.safetensors',avoid='FootMR standalone weights, config.json, or repository ZIPs.'),
+ 'exmr':dict(selection='twehrbein/ExMR > Files and versions > exmr.safetensors',location='exmr.safetensors',avoid='FootMR standalone weights, config.json (use the separate ExMR configuration row), or repository ZIPs.'),
+ 'exmr_config':dict(selection='twehrbein/ExMR > Files and versions > config.json',location='config.json',avoid='Edited JSON, a different revision, an HTML page, or exmr.safetensors. Use the Supported file link for the matching revision.'),
'exmr_sapiens':dict(selection='facebook/sapiens2-pose-1b > Files and versions > sapiens2_1b_pose.safetensors',location='sapiens2_1b_pose.safetensors',avoid='Sapiens v1, 0.3B models, segmentation, depth or normal checkpoints.'),
'mano_right': dict(selection='Models & Code > Models & Code (mano_v1_2.zip)',location='mano_v1_2/models/MANO_RIGHT.pkl',avoid='SMPL+H archives, MANO_LEFT.pkl, or the outer ZIP file.'),
'smplx': dict(selection='SMPL-X Model > Download SMPL-X v1.1 (NPZ+PKL, 830 MB)',
@@ -227,7 +233,7 @@ STAGE_REQUIREMENTS = {
'flow_export': ('smplh',),
'exmr_preprocess': ('exmr_sapiens',),
'exmr_features': ('flow_sam','flow_sam_config','flow_mhr','hand_hamer','hand_mean','mano_right'),
- 'exmr': ('exmr','smplx'),
+ 'exmr': ('exmr','exmr_config','smplx'),
'mamma_assets': MAMMA_KEYS,
**{stage:PHMR_KEYS for stage in ('prompthmr_assets','prompthmr_prepare','prompthmr_track','prompthmr_pose','prompthmr_world','prompthmr_publish')},
'mamma_prepare': MAMMA_KEYS,
diff --git a/third_party/ExMR/README.md b/third_party/ExMR/README.md
index d6f664e..0ed5f30 100644
--- a/third_party/ExMR/README.md
+++ b/third_party/ExMR/README.md
@@ -3,6 +3,7 @@
[![arXiv](https://img.shields.io/badge/arXiv-2610.26213-b31b1b.svg)](https://arxiv.org/abs/2610.26213)
[![Project page](https://img.shields.io/badge/Project-Page-blue)](https://twehrbein.github.io/exmr-website/)
[![Model](https://img.shields.io/badge/%F0%9F%A4%97-Model-yellow)](https://huggingface.co/twehrbein/ExMR)
+[![Demo](https://img.shields.io/badge/%F0%9F%A4%97-Demo-yellow)](https://huggingface.co/spaces/twehrbein/ExMR)
![ExMR teaser](assets/teaser.jpg)
@@ -15,6 +16,16 @@
## News
+- **[2026-10-29]** [v0.1.5](https://github.com/twehrbein/ExMR/releases/tag/v0.1.5): fixes for
+ portrait phone videos (the mesh was beside the person) and for ffmpeg crashing at the end of a run;
+ foot contacts in the results, `--export_fps` (e.g. 24 or 30 fps exports), a world-frame motion that
+ starts facing +z, the mesh's shadow in the world view and world-frame ankles closer to the network's.
+- **[2026-10-26]** Online demo on [Hugging Face Spaces](https://huggingface.co/spaces/twehrbein/ExMR):
+ try ExMR in the browser, without installing anything.
+- **[2026-10-26]** [v0.1.4](https://github.com/twehrbein/ExMR/releases/tag/v0.1.4): 3D and 2D joints
+ in the results, BVH export, FBX for Unity and Unreal (through Blender) and retargeting to humanoid
+ robots with [GMR](https://github.com/YanjieZe/GMR), see [outputs](docs/OUTPUTS.md); a demo about
+ 10 % faster.
- **[2026-10-22]** [v0.1.3](https://github.com/twehrbein/ExMR/releases/tag/v0.1.3): export for
Blender (AMASS SMPL-X file), `--snap_to_ground` and temporal smoothing.
- **[2026-10-21]** Demo code and model weights released.
@@ -37,6 +48,9 @@ first: its weights are gated and access is approved manually, which can take a w
## Quick Start
+To try ExMR without installing it, the [online demo](https://huggingface.co/spaces/twehrbein/ExMR)
+runs the default mode on up to 20 seconds of a video and returns the same outputs.
+
Reconstruct the main person in a video:
```bash
@@ -45,27 +59,32 @@ python tools/demo.py --video path/to/video.mp4 -s # static camera (better worl
```
For example, download the [dancing video](https://www.pexels.com/video/woman-doing-dancing-exercise-in-the-garden-3690649/)
-from Pexels (1906x1080, filmed with a static camera) and run
+from Pexels (1906x1080, filmed with a static camera; the ground is flat) and run
```bash
-python tools/demo.py --video 3690649-hd_1906_1080_30fps.mp4 -s
+python tools/demo.py --video 3690649-hd_1906_1080_30fps.mp4 -s --snap_to_ground
```
![Demo output on the example video: SMPL-X in the camera view (left) and in the gravity-aligned world frame (right)](assets/demo.gif)
-Results go to `outputs/<video name>/`: SMPL-X parameters in the camera and in a gravity-aligned
-world frame (`results.pt`, `results.npz`), the world-frame motion as an AMASS file that the SMPL-X
-Blender add-on imports (`<video name>_amass.npz`, see [Blender](docs/OUTPUTS.md#blender-and-amass))
-and rendered videos, see [outputs](docs/OUTPUTS.md).
+Results go to `outputs/<video name>/` (see [outputs](docs/OUTPUTS.md)):
+
+* `results.pt`, `results.npz`: SMPL-X parameters and joints in the camera and in a gravity-aligned
+ world frame
+* `<video name>_amass.npz`: the world-frame motion as an AMASS SMPL-X file, e.g. for
+ [Blender](docs/OUTPUTS.md#blender-and-amass), [Unity and Unreal](docs/OUTPUTS.md#fbx-for-unity-and-unreal)
+ (FBX through Blender) or [humanoid robots](docs/OUTPUTS.md#humanoid-robots-gmr)
+* `<video name>.bvh`: the world-frame motion as a [BVH](docs/OUTPUTS.md#bvh) skeleton animation
+* rendered videos of the SMPL-X mesh in the camera view and in the world frame
`--mode` trades speed for accuracy. Times are for the 37-second example video (1122 frames, `-s`)
on an RTX 4090, including model loading and rendering:
| `--mode` | Person detector | 2D keypoints | Camera motion (moving camera) | Time |
|---|---|---|---|---:|
-| `fast` | YOLO11m | RTMW-x | SimpleVO | 1&nbsp;min&nbsp;9&nbsp;s |
-| `balanced` (default) | YOLO11m | Sapiens2-1B 448x336 | SimpleVO | 1&nbsp;min&nbsp;23&nbsp;s |
-| `accurate` | YOLO11x | Sapiens2-1B 1024x768 | DPVO | 3&nbsp;min&nbsp;22&nbsp;s |
+| `fast` | YOLO11m | RTMW-x | SimpleVO | 1&nbsp;min&nbsp;3&nbsp;s |
+| `balanced` (default) | YOLO11m | Sapiens2-1B 448x336 | SimpleVO | 1&nbsp;min&nbsp;17&nbsp;s |
+| `accurate` | YOLO11x | Sapiens2-1B 1024x768 | DPVO | 2&nbsp;min&nbsp;58&nbsp;s |
In our evaluation, Sapiens2-1B gives nearly the same accuracy at 448x336 and 1024x768; RTMW-x is
slightly less accurate, mostly for the feet. With `-s` (static camera), no mode estimates camera
@@ -76,6 +95,13 @@ Other options:
* `--detector`, `--pose_backend`, `--sapiens2_resolution`, `--vo`: override single parts of the
mode, e.g. `--mode accurate --vo simplevo` without DPVO.
+* `--start`, `--end`: only the part of the video between these times, in seconds (`83.5`) or as
+ in a video player (`1:23.5`, `1:02:03`); either can be left out. The outputs go to
+ `outputs/<video name>_<start>-<end>s/` and cover only that part (see [outputs](docs/OUTPUTS.md)).
+* `--f_mm`: the camera's focal length in mm as for a full-frame camera (35 mm equivalent), if you
+ know it; for phones about 13 (0.5x lens), 24-26 (1x), 48 (2x) or 77 (3x). Without it, ExMR assumes
+ a 53° diagonal field of view (about 43 mm). The focal
+ length is used by the model, SAM 3D Body and the camera motion estimation.
* `--fps30`: resample the video to 30 fps first. Usually not needed; ExMR is trained on 30 fps
videos, so you may try it for videos far from 30 fps (e.g. 50 fps or more). For such videos it
also makes the demo faster, since fewer frames are processed. The results then follow the
@@ -84,12 +110,16 @@ Other options:
seems to fly or sink). If the scene has a single flat ground and nothing to stand on (no
stairs, chairs, ...), the body touches the ground at least every 0.5 s, about the hang time of
a jump; this option moves the world-frame motion vertically so that it does, as in
- [PRIMAL](https://arxiv.org/abs/2503.17544). Jumps with a longer flight are pulled down.
+ [PRIMAL](https://arxiv.org/abs/2503.17544). Jumps with a longer flight are pulled down. The
+ demo suggests this option when the feet end up far above the ground where they touch it.
+* `--export_fps`: frame rate of the exported motion (`<name>_amass.npz`, `<name>.bvh`), e.g. 24 for
+ film or 60 for games, resampled from the video's (default). The other outputs keep the video's
+ frames.
* `--smoothing {global,both,none}`: temporal smoothing of the output motion (Gaussian, ~33 ms).
By default (`global`) only the world-frame motion is smoothed; the camera-frame motion stays
raw, best aligned with the image. `both` also smooths the camera-frame motion (smoother, but
fast foot motion is followed slightly less closely in the image); `none` keeps the raw output.
-* `--no_render`: only save the results.
+* `--no_render`: no videos, only the results (needs no nvdiffrast).
Intermediate results are cached in `outputs/<video name>/cache/`, so rerunning the demo (e.g.
with `--no_render` removed, or another option) only recomputes what changed.
@@ -122,8 +152,11 @@ results = run_video("video.mp4", "outputs/video", Options(static_cam=True, rende
body_pose = results["smplx_global"]["body_pose"] # (L, 63), see docs/OUTPUTS.md
```
-`Options` has the same settings as the demo's command-line options (default: `balanced` mode). The
-model files are read from `checkpoints/` (or `$EXMR_CHECKPOINT_DIR`).
+`Options` has the same settings as the demo's command-line options (default: `balanced` mode;
+`start` and `end` in seconds). The model files are read from `checkpoints/` (or
+`$EXMR_CHECKPOINT_DIR`). `exmr.pipeline` also exposes the pieces `run_video` is built from, e.g.
+for a pipeline with preloaded models: `hand_boxes`, `model_inputs`, `compute_joints`,
+`save_results` and `render`.
## How it works
@@ -140,7 +173,7 @@ model files are read from `checkpoints/` (or `$EXMR_CHECKPOINT_DIR`).
| ExMR: initial whole-body estimate, then FootMR and HandMR | `exmr/model/exmr.py`, with `body_net.py` and `refiners.py` |
| World-frame trajectory and post-processing (static joints, camera drift, ground contact, IK) | `exmr/model/global_traj.py` |
| Temporal smoothing | `exmr/model/exmr.py`, `exmr/geometry/smoothing.py` |
-| Export for Blender (AMASS SMPL-X file) | `exmr/export.py` |
+| Export for Blender and robot retargeting (AMASS SMPL-X file) and BVH | `exmr/export.py` |
| Rendered videos | `exmr/vis/` |
## Citation
diff --git a/third_party/ExMR/RGB_MOCAP_PROVENANCE.json b/third_party/ExMR/RGB_MOCAP_PROVENANCE.json
index 3fd8e43..693ba0b 100644
--- a/third_party/ExMR/RGB_MOCAP_PROVENANCE.json
+++ b/third_party/ExMR/RGB_MOCAP_PROVENANCE.json
@@ -1,7 +1,7 @@
{
"repository": "https://github.com/twehrbein/ExMR",
- "commit": "f031badd0488bf5d50b8eba2e722c5a55f323e3f",
+ "commit": "57e4824b9c532b52ed1c8b12c44000ad41ef4c4c",
"runtime": "Native Windows Python 3.12 / Torch 2.8.0+cu128",
"weights_bundled": false,
- "compatibility": "Bounded sequential loaders, optional CPU-first body/hand loading and pre-transfer Sapiens FP16 conversion, local DINOv3 source, Unicode-safe OpenCV JPEG IO; explicit optional model injection and removable feature-token hooks for stage-scoped sequential actor reuse; network and native precision unchanged; bounded CPU batch prefetch; unused final body-pose readouts omitted only after collected decoder features, retaining intermediate feedback and the generic SAM path"
+ "compatibility": "Native Windows pinned RGB MoCap runtime; bounded sequential loaders, CPU-first Low Memory body/hand loading, pre-transfer Sapiens FP16, local DINOv3 and Unicode-safe image IO retained. Public hand_boxes/model_inputs/ExMR.from_pretrained and direct model forward replace private pipeline calls. Stage-scoped model reuse, removable hooks, bounded CPU prefetch and unused final body readout omission retained. Upstream v0.1.5 axis-wise 0.03 m toe IK bound enabled. Local normalize_world switch defaults to upstream behavior; app disables it to retain its scene/camera frame. Explicit SimpleVO frame_reader callback preserves canonical-video pixels. App shared contact detection and correction are unchanged; upstream foot_contacts is not used. Runtime package pins and model weights unchanged."
}
diff --git a/third_party/ExMR/constraints.txt b/third_party/ExMR/constraints.txt
new file mode 100644
index 0000000..a678e4f
--- /dev/null
+++ b/third_party/ExMR/constraints.txt
@@ -0,0 +1,88 @@
+# Exact versions of all packages, indirect dependencies included, that the release was validated
+# with: pip install -r requirements.txt -c constraints.txt (see docs/INSTALL.md). Not listed: torch,
+# torchvision and their CUDA libraries (pinned by their own install command), pip, setuptools, wheel
+# and packaging (installed with conda's Python), and the packages installed from pinned URLs.
+accelerate==1.15.0
+aiohappyeyeballs==2.7.1
+aiohttp==3.14.5
+aiosignal==1.4.0
+anyio==4.15.1
+attrs==26.1.0
+av==13.0.0
+braceexpand==0.1.7
+certifi==2026.10.23
+charset-normalizer==3.5.2
+click==8.5.0
+contourpy==1.4.0
+cycler==0.12.1
+einops==0.8.1
+filelock==3.32.3
+flatbuffers==25.12.19
+fonttools==4.67.0
+freetype-py==2.5.1
+frozenlist==1.8.0
+fsspec==2026.7.0
+h11==0.16.0
+hf-xet==1.7.0
+httpcore2==2.16.0
+httpx2==2.16.0
+huggingface_hub==2.3.0
+idna==3.20
+imageio==2.34.1
+iopath==0.1.10
+Jinja2==3.1.6
+kiwisolver==1.5.1
+lap==0.5.13
+lightning-utilities==0.15.3
+markdown-it-py==4.2.0
+MarkupSafe==3.0.3
+matplotlib==3.11.2
+mdurl==0.1.2
+mpmath==1.3.0
+multidict==7.1.0
+networkx==3.6.1
+numpy==2.3.5
+nvidia-ml-py==13.615.71
+omegaconf==2.4.0
+onnxruntime-gpu==1.24.4
+opencv-python==4.11.0.86
+pillow==12.3.0
+polars-runtime-32==2.0.0
+polars==2.0.0
+portalocker==4.4.1
+prettytable==3.18.0
+propcache==0.5.4
+protobuf==7.36.2
+psutil==7.2.2
+pycolmap==3.11.1
+pyglet==2.1.19
+Pygments==2.21.0
+PyOpenGL==3.1.0
+pyparsing==3.3.3
+pyrender==0.1.45
+python-dateutil==3.0.0
+pytorch-lightning==2.6.6
+PyTurboJPEG==2.5.0
+PyYAML==6.0.3
+requests==2.34.2
+rich==15.0.0
+roma==1.5.6
+safetensors==0.7.0
+scipy==1.15.2
+six==1.17.0
+smplx==0.1.28
+sympy==1.14.0
+termcolor==3.3.0
+timm==0.9.12
+torchmetrics==1.9.0
+tqdm==4.70.1
+trimesh==4.6.5
+truststore==0.10.5
+typing_extensions==4.16.0
+tzdata==2026.5
+ultralytics-thop==2.2.3
+ultralytics==8.4.83
+urllib3==2.8.0
+wcwidth==0.9.3
+yacs==0.1.8
+yarl==1.25.1
diff --git a/third_party/ExMR/docs/INSTALL.md b/third_party/ExMR/docs/INSTALL.md
new file mode 100644
index 0000000..d782e77
--- /dev/null
+++ b/third_party/ExMR/docs/INSTALL.md
@@ -0,0 +1,150 @@
+# Installation
+
+Tested on Linux with an NVIDIA RTX 4090, CUDA 12.8 (driver >= 570), Python 3.12. The demo needs
+about 8 GB of GPU memory (7.4 GB peak measured on a 1080x1920 video).
+
+**Windows:** not tested. Use [WSL2](https://learn.microsoft.com/windows/wsl/install) (Ubuntu, with
+the NVIDIA driver >= 570 installed in Windows) and follow these instructions inside it. Native
+Windows is not supported.
+
+> [!IMPORTANT]
+> Request access to [SAM 3D Body](https://huggingface.co/facebook/sam-3d-body-dinov3) on Hugging Face
+> before you start: its weights are gated and access is approved manually, which can take a while.
+> SMPL-X and MANO need a (free) registration too, see [model files](#3-model-files).
+
+## 1. Code
+
+```bash
+git clone --recursive https://github.com/twehrbein/ExMR.git
+cd ExMR
+```
+
+`third_party/` holds pinned git submodules: SAM 3D Body (required) and DPVO (optional).
+
+## 2. Environment
+
+```bash
+conda create -y -n exmr python=3.12
+conda activate exmr
+# ignore packages in ~/.local, which would otherwise shadow the environment's (set once, kept
+# for every activation of this environment)
+conda env config vars set PYTHONNOUSERSITE=1
+conda activate exmr
+
+pip install torch==2.8.0 torchvision==0.23.0 --index-url https://download.pytorch.org/whl/cu128
+conda install -y -c conda-forge ffmpeg=9.0.2 libjpeg-turbo
+# constraints.txt pins the indirect dependencies too, to the validated versions
+pip install -r requirements.txt -c constraints.txt
+# HaMeR and Sapiens2 at the evaluated versions, without their (training) dependencies
+# (`pip check` lists those as missing; they are not needed)
+pip install --no-deps \
+ "git+https://github.com/geopavlakos/hamer.git@3a01849f4148352e9260b69bf28b65d1671a4905" \
+ "git+https://github.com/facebookresearch/sapiens2.git@7e5bae88456ac418ff0e58e74106c9fe192055d4"
+# nvdiffrast renders the result videos: a prebuilt wheel for exactly this torch version
+pip install "https://huggingface.co/twehrbein/ExMR/resolve/03e36730ba7466ef09fcd98523fec6d9c2da8a0a/wheels/nvdiffrast-0.4.0%2Bpt2.8.0cu128-cp312-cp312-linux_x86_64.whl#sha256=ca26d44f4f198e8fb460f86f355c5fdaeaac6319e15a5551ea31397719c0d563"
+pip install -e .
+```
+
+The wheel is [nvdiffrast](https://github.com/NVlabs/nvdiffrast) v0.4.0, built by us for this torch
+version and hosted with the ExMR weights (see the
+[model card](https://huggingface.co/twehrbein/ExMR)); the hash pins the tested file. With another
+torch version, [build nvdiffrast](#optional-build-nvdiffrast-from-source) instead. The demo tries
+nvdiffrast before it starts; without it, everything but the videos works (`--no_render`).
+
+### Optional: build nvdiffrast from source
+
+nvdiffrast is compiled against the installed torch, with nvcc 12.x and gcc <= 14. Install both
+into the environment, so that the build does not depend on the system's CUDA toolkit (DPVO below
+needs the same):
+
+```bash
+conda install -y -c conda-forge cuda-version=12.8 cuda-nvcc cuda-cudart-dev cuda-cccl \
+ libcublas-dev libcusparse-dev libcusolver-dev ninja
+# re-activate: the compiler packages just installed point CC/CXX to the environment's gcc 14
+# only on activation (a newer system gcc, e.g. 15, is rejected by nvcc 12.8)
+conda activate exmr
+# build for the GPUs that the torch build above supports (the compiler packages set a longer
+# list, with older GPUs that DPVO cannot be built for); fewer build faster, see the table below
+export TORCH_CUDA_ARCH_LIST="7.0;7.5;8.0;8.6;9.0;10.0;12.0"
+CUDA_HOME=$CONDA_PREFIX pip install --no-build-isolation \
+ "git+https://github.com/NVlabs/[email protected]"
+```
+
+`TORCH_CUDA_ARCH_LIST` takes the compute capabilities of the GPUs to build for, separated by
+semicolons (e.g. `"8.6;8.9"`); `nvidia-smi --query-gpu=name,compute_cap --format=csv` prints them.
+The list above covers all GPUs that the torch build supports (RTX 40 series GPUs run the code
+built for `8.6`):
+
+| GPU | `TORCH_CUDA_ARCH_LIST` |
+|---|---|
+| V100 | `7.0` |
+| RTX 20 series, T4 | `7.5` |
+| A100 | `8.0` |
+| RTX 30 series, A40, RTX A6000 | `8.6` |
+| RTX 40 series, L4, L40, RTX 6000 Ada | `8.9` |
+| H100, H200 | `9.0` |
+| B200 | `10.0` |
+| RTX 50 series, RTX PRO 6000 Blackwell | `12.0` |
+
+### Optional: DPVO
+
+DPVO, a learned visual odometry method, is an alternative to the default SimpleVO for estimating
+the motion of a moving camera (`--vo dpvo`); `--mode accurate` uses it. See
+[camera motion](../README.md#camera-motion) for the differences. It is compiled with the
+compiler from [build nvdiffrast](#optional-build-nvdiffrast-from-source) (its `conda install` and
+re-activation).
+
+```bash
+export TORCH_CUDA_ARCH_LIST="7.0;7.5;8.0;8.6;9.0;10.0;12.0" # as for nvdiffrast, see above
+git -C third_party/DPVO apply ../patches/DPVO-torch2.7.patch # build fix for torch >= 2.7
+wget https://gitlab.com/libeigen/eigen/-/archive/3.4.0/eigen-3.4.0.zip
+unzip eigen-3.4.0.zip -d third_party/DPVO/thirdparty && rm eigen-3.4.0.zip
+pip install torch-scatter==2.1.2 -f https://data.pyg.org/whl/torch-2.8.0+cu128.html \
+ numba==0.68.0 pypose==0.7.2 -c constraints.txt
+CUDA_HOME=$CONDA_PREFIX pip install --no-build-isolation --no-deps -e third_party/DPVO
+```
+
+## 3. Model files
+
+Three models need a (free) registration or access request first:
+
+* **SMPL-X**: register at [smpl-x.is.tue.mpg.de](https://smpl-x.is.tue.mpg.de) and download
+ `models_smplx_v1_1.zip` ("SMPL-X v1.1 (NPZ+PKL)").
+* **MANO**: register at [mano.is.tue.mpg.de](https://mano.is.tue.mpg.de) and download
+ `mano_v1_2.zip` ("Models & Code").
+* **SAM 3D Body** is gated on Hugging Face: request access at
+ [facebook/sam-3d-body-dinov3](https://huggingface.co/facebook/sam-3d-body-dinov3) and, once
+ approved, log in with `hf auth login`.
+
+Then download everything else and unpack the two zips (~12 GB, about 10 minutes):
+
+```bash
+python tools/download_models.py --smplx_zip models_smplx_v1_1.zip --mano_zip mano_v1_2.zip
+# optional DPVO weights: add --dpvo
+```
+
+The script checks every file against the version ExMR was tested with, skips files that are already
+present (rerun it after an interrupted download) and prints each model's license; downloading a
+model means accepting its license. It also stores the DINOv3 code that SAM 3D Body loads through
+`torch.hub`, so that the demo runs offline afterwards.
+
+All model files go into one directory, `checkpoints/` by default (or set `EXMR_CHECKPOINT_DIR`, or
+pass `--checkpoint_dir` to both scripts):
+
+```
+checkpoints/
+├── exmr/exmr.safetensors ExMR
+├── body_models/smplx/SMPLX_NEUTRAL.npz SMPL-X (register at smpl-x.is.tue.mpg.de)
+├── yolo/yolo11x.pt, yolo11m.pt person detector (Ultralytics)
+├── sapiens2/sapiens2_1b_pose.safetensors 2D keypoints (default)
+├── rtmw/rtmw-x_384x288_fp16.onnx 2D keypoints (--mode fast)
+├── sam-3d-body-dinov3/ body features: model.ckpt, model_config.yaml,
+│ assets/mhr_model.pt
+├── hamer/ hand features (HaMeR's hamer_demo_data):
+│ ├── hamer_ckpts/ checkpoints/hamer.ckpt, model_config.yaml
+│ └── data/ mano_mean_params.npz,
+│ mano/MANO_RIGHT.pkl (register at mano.is.tue.mpg.de)
+└── dpvo/dpvo.pth optional, for --mode accurate / --vo dpvo
+```
+
+The demo checks for all files it needs before it starts and lists the missing ones.
diff --git a/third_party/ExMR/docs/OUTPUTS.md b/third_party/ExMR/docs/OUTPUTS.md
new file mode 100644
index 0000000..7da8db4
--- /dev/null
+++ b/third_party/ExMR/docs/OUTPUTS.md
@@ -0,0 +1,220 @@
+# Demo outputs
+
+`python tools/demo.py --video <video>` writes to `--output_dir` (default `outputs/<video name>`, with
+`--start`/`--end` `outputs/<video name>_<start>-<end>s`):
+
+| File | Content |
+|---|---|
+| `results.pt` | reconstruction: SMPL-X parameters and 3D/2D joints (PyTorch, see below) |
+| `results.npz` | the same as NumPy arrays, with flattened keys (`smplx_incam_body_pose`, ...) |
+| `<name>_amass.npz` | the world-frame motion as an AMASS SMPL-X file, e.g. for [Blender](#blender-and-amass), [Unity and Unreal](#fbx-for-unity-and-unreal) or [humanoid robots](#humanoid-robots-gmr) |
+| `<name>.bvh` | the world-frame motion as a [BVH](#bvh) skeleton animation (centimeters), e.g. for animation software |
+| `<name>_incam.mp4` | SMPL-X mesh rendered over the input video |
+| `<name>_global.mp4` | SMPL-X mesh in the world frame, with a ground plane and the mesh's shadow straight down on it (a gap between a foot and its shadow: the foot is above the ground), seen by a static camera |
+| `<name>_incam_global.mp4` | both side by side (scaled down to at most 4096 pixels wide) |
+| `cache/` | cached preprocessing results (reused when the demo is run again with the same settings) |
+| `run.json` | the video and options of the run (e.g. `smoothing`, `start`, `end`) |
+
+With `--start`/`--end`, all outputs cover only that part of the video: their first frame is the
+first frame at or after `--start`. Tracking, camera motion, the model and the ground see only that
+part, so the results differ slightly from the same frames of a run on the whole video.
+
+Which output for what:
+
+| To ... | use |
+|---|---|
+| analyze the motion, e.g. joint positions in Python | `results.npz` or `results.pt`: SMPL-X parameters and joints ([results.pt](#resultspt)) |
+| see the SMPL-X body in Blender | `<name>_amass.npz` with the SMPL-X Blender add-on ([Blender and AMASS](#blender-and-amass)) |
+| use the body in Unity or Unreal | an FBX exported from Blender ([FBX](#fbx-for-unity-and-unreal)) |
+| animate your own character, e.g. in Blender, Maya or MotionBuilder | `<name>.bvh`, retargeted to the character's rig ([BVH](#bvh)) |
+| drive a humanoid robot | `<name>_amass.npz` with GMR ([humanoid robots](#humanoid-robots-gmr)) |
+
+## results.pt
+
+```python
+results = torch.load("results.pt")
+```
+
+For a video with `L` frames:
+
+| Key | Shape | Description |
+|---|---|---|
+| `smplx_incam` | dict | SMPL-X parameters in the camera frame (x right, y down, z forward); not smoothed over time unless `--smoothing both` |
+| `smplx_global` | dict | SMPL-X parameters in a gravity-aligned world frame (y up); the motion starts at the origin (x, z) facing +z and stands on the ground y=0: the lowest mesh vertex over all frames is at y=0 (with `--snap_to_ground`: the lowest vertex within every 0.5 s); smoothed over time unless `--smoothing none` |
+| `joints_incam`, `joints_global` | <code>(L,&nbsp;76,&nbsp;3)</code> | 3D joints of `smplx_incam` and `smplx_global` in meters, see [joints](#joints) |
+| `joints_2d` | <code>(L,&nbsp;76,&nbsp;2)</code> | `joints_incam` projected into the image with `K_fullimg`, in pixels |
+| `joint_names` | 76 | names of the joints, e.g. `left_heel` |
+| `static_conf_logits` | `(L, 6)` | logits of [left ankle, left foot, right ankle, right foot, left wrist, right wrist] being static (not moving in the world frame: usually, but not necessarily, in contact with the ground or an object) |
+| `foot_contact` | `(L, 2)` | whether the [left, right] foot touches the ground: its ankle or foot is static (`static_conf_logits` above 0.8 in probability) and it is the lowest part of the body (within 5 cm), e.g. to lock the feet when retargeting the motion to another character |
+| `K_fullimg` | <code>(L,&nbsp;3,&nbsp;3)</code> | camera intrinsics used (from `--f_mm`, else estimated from the image size) |
+| `bbx_xyxy` | `(L, 4)` | tracked bounding box of the person, `[x1, y1, x2, y2]` in pixels |
+| `fps` | float | frame rate of the processed video |
+
+Both SMPL-X parameter dicts contain, per frame, axis-angle rotations:
+
+| Key | Shape | Description |
+|---|---|---|
+| `global_orient` | `(L, 3)` | root rotation |
+| `body_pose` | `(L, 63)` | 21 body joints, relative to their parent |
+| `left_hand_pose`, `right_hand_pose` | `(L, 45)` | 15 finger joints per hand (full axis-angle, no PCA, flat hand mean) |
+| `betas` | `(L, 10)` | body shape (the same for all frames) |
+| `transl` | `(L, 3)` | root translation in meters |
+
+Face parameters (jaw, eyes, expression) are not estimated; use zeros.
+
+To get the mesh with the [smplx](https://github.com/vchoutas/smplx) package:
+
+```python
+import smplx
+
+params = results["smplx_incam"] # or results["smplx_global"]
+L = len(params["body_pose"])
+model = smplx.SMPLX(
+ "SMPLX_NEUTRAL.npz", use_pca=False, flat_hand_mean=True, num_betas=10, batch_size=L
+) # batch_size: the face parameters, which ExMR does not estimate, default to zeros of that size
+output = model(**params)
+vertices = output.vertices # (L, 10475, 3)
+joints = output.joints[:, :76] # (L, 76, 3): joints_incam or joints_global of results.pt
+```
+
+`exmr.body_models.smplx_model.SmplxModel` gives the same vertices and joints.
+
+### Joints
+
+The 76 joints are the 55 joints of the SMPL-X skeleton followed by 21 points on the mesh surface,
+in the order of the [smplx](https://github.com/vchoutas/smplx) package's output (`joint_names`):
+
+| Index | Joints |
+|---|---|
+| 0-21 | pelvis and 21 body joints (the same as SMPL's first 22, e.g. for comparisons with SMPL-based methods) |
+| 22-24 | jaw, left and right eye (the face is not estimated: they follow the head) |
+| 25-54 | 15 finger joints per hand, left hand first |
+| 55-59 | nose, right and left eye, right and left ear (surface points) |
+| 60-65 | big toe, small toe and heel, left foot first (surface points) |
+| 66-75 | fingertips, thumb to pinky, left hand first (surface points) |
+
+The skeleton joints are rotation centers inside the body, the surface points lie on the skin, like
+the foot and fingertip keypoints of 2D detectors such as OpenPose.
+
+`exmr.pipeline.compute_joints` computes the joint keys (`joints_incam`, `joints_global`,
+`joints_2d`, `joint_names`) from the SMPL-X parameters, e.g. for results of ExMR versions before
+0.1.4, which have none:
+
+```python
+from exmr.body_models.smplx_model import SmplxModel
+from exmr.pipeline import compute_joints
+
+results |= compute_joints(results, SmplxModel("SMPLX_NEUTRAL.npz"))
+```
+
+## Blender and AMASS
+
+`<name>_amass.npz` holds the world-frame motion (`smplx_global`) in the layout of the SMPL-X files
+of [AMASS](https://amass.is.tue.mpg.de), which the SMPL-X Blender add-on imports:
+
+1. Download "SMPL-X for Blender" from the [SMPL-X website](https://smpl-x.is.tue.mpg.de)
+ (registration, Blender 4.5 or newer) and install the zip in Blender (Edit > Preferences > Get
+ Extensions > Install from Disk).
+2. In the 3D viewport's sidebar (View > Sidebar), tab "SMPL Models", click "Add Animation" and
+ select the file. The default settings fit (Format: AMASS, Hand pose reference: Flat).
+3. Set "Target framerate" to the file's frame rate (`mocap_frame_rate`) or a divisor of it, e.g. 25
+ for a 25 fps video: the add-on rejects targets above the frame rate and otherwise keeps every
+ (frame rate / target)-th frame, rounded down. Its default of 30 suits 30 and 60 fps videos,
+ and files exported with `--export_fps 30`.
+4. For the exact SMPL-X mesh, enable "Use keyframed corrective pose weights" (slower import and
+ playback). Without it, the skeleton moves the same, but the mesh lacks SMPL-X's pose-dependent
+ shape corrections.
+
+The add-on's default body model is SMPL-X "locked head" (without the head bun of SMPL-X v1.1,
+which ExMR uses). The joints and the body agree within about a millimeter; only the head differs.
+
+As in AMASS, the world frame is z-up with the ground at z=0: the motion is `smplx_global` rotated
+by 90 degrees about the x-axis, i.e. the point (x, y, z) of `smplx_global` is at (x, -z, y). The
+hand poses are relative to the flat hand, as in `results.pt`.
+
+| Key | Shape | Description |
+|---|---|---|
+| `poses` | `(L, 165)` | axis-angle rotations of the 55 SMPL-X joints: root, 21 body joints, jaw, 2 eyes, 15 + 15 finger joints (jaw and eyes are zero) |
+| `root_orient`, `pose_body`, `pose_jaw`, `pose_eye`, `pose_hand` | `(L, 3)`, `(L, 63)`, `(L, 3)`, `(L, 6)`, `(L, 90)` | the same, split into parts |
+| `trans` | `(L, 3)` | root translation in meters |
+| `betas` | `(16,)` | body shape: ExMR's 10 betas, padded with zeros to the 16 of AMASS (`num_betas`: 16) |
+| `gender`, `surface_model_type` | | `neutral`, `smplx` |
+| `mocap_frame_rate` | | frame rate, rounded to an integer (the Blender add-on reads it as one); the exact rate is `fps` in `results.pt` |
+
+`exmr.export.save_amass` writes the file from `results.pt`, e.g. for results of an earlier ExMR
+version:
+
+```python
+from exmr.body_models.smplx_model import SmplxModel
+from exmr.export import save_amass
+
+smplx = SmplxModel("SMPLX_NEUTRAL.npz")
+save_amass(results["smplx_global"], results["fps"], "motion_amass.npz", smplx)
+```
+
+### FBX for Unity and Unreal
+
+The add-on also exports the animated SMPL-X body as FBX: after importing the AMASS file, select
+the body's mesh, click "Export FBX" (tab "SMPL Models", panel "Export") and choose the Format
+(Unity or Unreal) and "Blend Shapes: None: Apply shape space". The default blend shapes, SMPL-X's
+shape and pose corrective shapes, are not animated by the import and make the file much larger
+(150 MB instead of 5 MB for the example video).
+
+## BVH
+
+`<name>.bvh` holds the world-frame motion (`smplx_global`) as a skeleton animation, e.g. to put
+the motion on another character in Blender, Maya or MotionBuilder:
+
+- the 55 joints of the SMPL-X skeleton, fingers included, named as in `joint_names` (`pelvis`,
+ `left_hip`, ...), with end sites at the big toes, the fingertips, the chin and the eyes
+- the skeleton in the SMPL-X rest pose (a T-pose) of the person's body shape, in centimeters, y up
+- one frame per video frame (`Frame Time`: 1 / frame rate); in every frame, the joints are at
+ `joints_global` of `results.pt` (in meters there). With `--export_fps`, the frames are resampled
+ to that rate instead (also in `<name>_amass.npz`), e.g. 24 fps for film: the rotations are
+ interpolated on the sphere (slerp), the root position linearly
+- the root (`pelvis`) with absolute positions; the rotation order of the pelvis, shoulders, elbows
+ and ankles differs from the others' XYZ, which keeps them away from gimbal lock, and the angles
+ do not jump by 360 degrees between frames
+- the jaw and the eyes do not move (the face is not estimated)
+
+In Blender: File > Import > Motion Capture (.bvh) with Scale 0.01 (centimeters to meters), and
+"Update Scene FPS" and "Update Scene Duration" checked. The BVH has no mesh; for the SMPL-X body,
+import the AMASS file (above).
+
+`exmr.export.save_bvh` writes the file from `results.pt`:
+
+```python
+from exmr.body_models.smplx_model import SmplxModel
+from exmr.export import save_bvh
+
+smplx = SmplxModel("SMPLX_NEUTRAL.npz")
+save_bvh(results["smplx_global"], results["fps"], "motion.bvh", smplx)
+```
+
+## Humanoid robots (GMR)
+
+[GMR](https://github.com/YanjieZe/GMR) (General Motion Retargeting) retargets AMASS SMPL-X files
+to humanoid robots, e.g. the Unitree G1 and H1, Booster T1 or Fourier N1 (see its list).
+
+![The example video (left) and its ExMR motion (with --snap_to_ground) retargeted to a Unitree G1 by GMR (right)](../assets/robot_g1.gif)
+
+Install GMR as described in its README, put ExMR's `checkpoints/body_models/smplx/SMPLX_NEUTRAL.npz`
+into GMR's `assets/body_models/smplx/` and run, in the GMR repository:
+
+```bash
+python scripts/smplx_to_robot.py --smplx_file <name>_amass.npz --robot unitree_g1 \
+ --save_path <name>_unitree_g1.pkl --rate_limit
+```
+
+- The robot keeps the height of the motion above the ground, so run ExMR with `--snap_to_ground`
+ if the scene allows it (see the [README](../README.md)): otherwise vertical drift of the
+ world-frame motion lets the robot float or sink.
+- GMR treats motions below 30 fps as 30 fps motions without resampling them, so e.g. a 25 fps
+ motion plays too fast. For videos below 30 fps, run ExMR with `--export_fps 30`.
+- GMR retargets the body only and ignores the finger motion, also for robots with hands. For robot
+ hands, the [joints](#joints) contain per hand the wrist, the three finger joints and the
+ fingertip of every finger: the 21 hand keypoints (in another order) that hand retargeting tools
+ such as [dex-retargeting](https://github.com/dexsuite/dex-retargeting) take.
+- Sudden robot arm motions that the SMPL-X mesh does not show come from the retargeting: GMR
+ solves every frame on its own and can switch the robot's arm between joint configurations that
+ reach the same pose. The same happens with ground-truth motion.
diff --git a/third_party/ExMR/exmr/__init__.py b/third_party/ExMR/exmr/__init__.py
index aa5609d..77bf3ee 100644
--- a/third_party/ExMR/exmr/__init__.py
+++ b/third_party/ExMR/exmr/__init__.py
@@ -1,3 +1,3 @@
"""ExMR: Extremity Motion Refinement for Monocular Human Motion Capture."""
-__version__ = "0.1.3"
+__version__ = "0.1.5"
diff --git a/third_party/ExMR/exmr/body_models/smplx_model.py b/third_party/ExMR/exmr/body_models/smplx_model.py
index ed26b00..096bbfd 100644
--- a/third_party/ExMR/exmr/body_models/smplx_model.py
+++ b/third_party/ExMR/exmr/body_models/smplx_model.py
@@ -5,9 +5,13 @@ from pathlib import Path
import torch
import torch.nn as nn
+# the joints of the smplx package's output that ExMR reports: the 55 SMPL-X joints, then 21 mesh
+# vertices (nose, eyes, ears, toes, heels, fingertips)
+NUM_JOINTS = 76
+
class SmplxModel(nn.Module):
- """Vertices (10475) and joints of SMPL-X for ExMR's output parameters.
+ """Vertices (10475) and joints (76) of SMPL-X for ExMR's output parameters.
Args:
smplx_npz: the official SMPLX_NEUTRAL.npz (not distributed with ExMR, see docs/INSTALL.md)
@@ -49,14 +53,37 @@ class SmplxModel(nn.Module):
for name, buffer in list(module.named_buffers(recurse=False)):
module.register_buffer(name, buffer, persistent=False)
self.faces = torch.from_numpy(self.model.faces.astype("int64")) # (20908, 3)
+ # the vertices of each foot: those that follow its ankle or toe joint the most
+ bone = self.model.lbs_weights.argmax(dim=-1) # (10475,)
+ for side, joints in (("left", [7, 10]), ("right", [8, 11])):
+ ids = torch.isin(bone, torch.tensor(joints)).nonzero()[:, 0]
+ self.register_buffer(f"{side}_foot_vertices", ids, persistent=False)
@property
def J_regressor(self):
"""(55, 10475) joint regressor; the first 22 joints match SMPL's."""
return self.model.J_regressor
+ @property
+ def joint_names(self):
+ """Names of the joints (76), e.g. "left_heel"."""
+ from smplx.joint_names import JOINT_NAMES
+
+ return JOINT_NAMES[:NUM_JOINTS]
+
def forward(self, body_pose, betas, global_orient, transl, left_hand_pose, right_hand_pose):
"""SMPL-X parameters, each (L, D) -> vertices (L, 10475, 3)"""
+ return self._output(
+ body_pose, betas, global_orient, transl, left_hand_pose, right_hand_pose
+ ).vertices
+
+ def joints(self, body_pose, betas, global_orient, transl, left_hand_pose, right_hand_pose):
+ """SMPL-X parameters, each (L, D) -> joints (L, 76, 3), see joint_names"""
+ return self._output(
+ body_pose, betas, global_orient, transl, left_hand_pose, right_hand_pose
+ ).joints[:, :NUM_JOINTS]
+
+ def _output(self, body_pose, betas, global_orient, transl, left_hand_pose, right_hand_pose):
L = body_pose.shape[0]
zeros = body_pose.new_zeros((L, 3))
return self.model(
@@ -70,4 +97,4 @@ class SmplxModel(nn.Module):
leye_pose=zeros,
reye_pose=zeros,
expression=body_pose.new_zeros((L, self.model.num_expression_coeffs)),
- ).vertices
+ )
diff --git a/third_party/ExMR/exmr/export.py b/third_party/ExMR/exmr/export.py
index 48d7013..3e660bf 100644
--- a/third_party/ExMR/exmr/export.py
+++ b/third_party/ExMR/exmr/export.py
@@ -1,23 +1,79 @@
-"""Export of the world-frame motion as an AMASS SMPL-X file, e.g. for the SMPL-X Blender add-on
-(see docs/OUTPUTS.md)."""
+"""Export of the world-frame motion as an AMASS SMPL-X file, e.g. for the SMPL-X Blender add-on or
+for retargeting to humanoid robots with GMR, and as a BVH skeleton animation (see
+docs/OUTPUTS.md)."""
import numpy as np
import torch
+from scipy.spatial.transform import Rotation, Slerp
-from exmr.body_models.smplx_skeleton import SmplxSkeleton
from exmr.geometry.rotation_conversions import axis_angle_to_matrix, matrix_to_axis_angle
# ExMR's world frame is y-up, AMASS's z-up: +90 degrees about x
Y_UP_TO_Z_UP = torch.tensor([[1, 0, 0], [0, 0, -1], [0, 1, 0]], dtype=torch.float64)
+# AMASS SMPL-X files have 16 betas, and loaders such as GMR's build the body model with as many:
+# ExMR's 10 betas are padded with zeros (the same body shape)
+AMASS_NUM_BETAS = 16
+# BVH: the rotation order of each joint (intrinsic, as its channels list them; XYZ if not listed),
+# chosen so that the middle angle stays away from +-90 degrees (gimbal lock) in typical motion
+BVH_ROTATION_ORDERS = {
+ "pelvis": "YZX", # turns freely about the vertical
+ "left_shoulder": "ZXY", "right_shoulder": "ZXY",
+ "left_elbow": "YXZ", "right_elbow": "YXZ", # bend about the vertical in the rest pose
+ "left_ankle": "XZY", "right_ankle": "XZY",
+} # fmt: skip
+# BVH: the end site of each leaf joint, a point of SmplxModel.joints or the chin
+BVH_END_SITES = {
+ "jaw": "chin",
+ "left_eye_smplhf": "left_eye",
+ "right_eye_smplhf": "right_eye",
+ **{f"{side}_foot": f"{side}_big_toe" for side in ("left", "right")},
+ **{
+ f"{side}_{finger}3": f"{side}_{finger}"
+ for side in ("left", "right")
+ for finger in ("thumb", "index", "middle", "ring", "pinky")
+ },
+}
+CHIN_VERTEX = 8750 # a vertex of the SMPL-X mesh, on the chin's midline
-def save_amass(smplx_params, fps, path, smplx_npz):
+
+def resample_motion(smplx_params, fps, out_fps):
+ """The motion (SMPL-X parameters, each (L, D)) at another frame rate, over the same time:
+ frames every 1/out_fps seconds from the first one, rotations interpolated on the sphere
+ (slerp), the translation linearly."""
+ L = len(smplx_params["transl"])
+ t_in = np.arange(L) / fps
+ n = int(np.floor((L - 1) / fps * out_fps + 1e-6)) + 1
+ t_out = np.minimum(np.arange(n) / out_fps, t_in[-1])
+ out = {}
+ for key, value in smplx_params.items():
+ v = value.detach().cpu().double().numpy()
+ if key == "betas": # the same in all frames
+ res = np.repeat(v[:1], n, axis=0)
+ elif key == "transl":
+ res = np.stack([np.interp(t_out, t_in, v[:, d]) for d in range(v.shape[1])], -1)
+ elif L == 1:
+ res = np.repeat(v, n, axis=0)
+ else: # axis-angle rotations (L, 3 * J)
+ rotvecs = v.reshape(L, -1, 3)
+ res = np.stack(
+ [
+ Slerp(t_in, Rotation.from_rotvec(r))(t_out).as_rotvec()
+ for r in rotvecs.swapaxes(0, 1)
+ ],
+ axis=1,
+ ).reshape(n, -1)
+ out[key] = torch.from_numpy(res).to(value.dtype)
+ return out
+
+
+def save_amass(smplx_params, fps, path, smplx):
"""Save world-frame SMPL-X parameters (results["smplx_global"], each (L, D), y up) to path as
an AMASS SMPL-X .npz (z up, float64).
Args:
fps: frame rate of the motion; stored rounded to an integer
- smplx_npz: the SMPLX_NEUTRAL.npz of the parameters, for the rest-pose pelvis position
+ smplx: a SmplxModel of the parameters, for the rest-pose pelvis position
"""
params = {k: v.detach().cpu().double() for k, v in smplx_params.items()}
R = Y_UP_TO_Z_UP
@@ -25,7 +81,8 @@ def save_amass(smplx_params, fps, path, smplx_npz):
# SMPL-X rotates the body about its rest-pose pelvis J0, not about the origin: the rotated
# world moves the pelvis from J0 + transl to R (J0 + transl)
betas = params["betas"][0] # the same in all frames
- pelvis = SmplxSkeleton(smplx_npz)(betas.float())[0].double()
+ with torch.no_grad():
+ pelvis = smplx.joints(**_rest_pose(params))[0, 0].double()
trans = (pelvis + params["transl"]) @ R.T - pelvis
zeros = torch.zeros(len(trans), 3, dtype=torch.float64)
@@ -41,11 +98,103 @@ def save_amass(smplx_params, fps, path, smplx_npz):
poses=torch.cat(list(parts.values()), dim=-1).numpy(), # (L, 165): the 55 SMPL-X joints
**{k: v.numpy() for k, v in parts.items()},
trans=trans.numpy(),
- betas=betas.numpy(),
- num_betas=len(betas),
+ betas=np.pad(betas.numpy(), (0, AMASS_NUM_BETAS - len(betas))),
+ num_betas=AMASS_NUM_BETAS,
gender="neutral",
surface_model_type="smplx",
# rounded: the SMPL-X Blender add-on cuts the rate to an integer (29.97 -> 29) and rejects
# rates below its target framerate (default 30)
mocap_frame_rate=float(round(fps)),
)
+
+
+def save_bvh(smplx_params, fps, path, smplx):
+ """Save world-frame SMPL-X parameters (results["smplx_global"], each (L, D), y up) to path as
+ a BVH animation of the 55 SMPL-X joints, in centimeters: the skeleton is the SMPL-X rest pose
+ of the person's shape, and the joints are at SmplxModel.joints(...)[:, :55] in every frame.
+
+ Args:
+ fps: frame rate of the motion
+ smplx: a SmplxModel of the parameters
+ """
+ params = {k: v.detach().cpu().float() for k, v in smplx_params.items()}
+ L = len(params["transl"])
+ names, parents = smplx.joint_names, smplx.model.parents.tolist()
+ rest_params = _rest_pose(params)
+ with torch.no_grad():
+ rest = smplx.joints(**rest_params)[0].double().numpy() * 100 # (76, 3)
+ chin = smplx(**rest_params)[0, CHIN_VERTEX].double().numpy() * 100
+ points = dict(zip(names, rest)) | {"chin": chin}
+
+ children = [[c for c in range(55) if parents[c] == j] for j in range(55)]
+ lines, joint_order = ["HIERARCHY"], []
+
+ def add_joint(j, depth):
+ tab = "\t" * depth
+ rotation = " ".join(f"{axis}rotation" for axis in BVH_ROTATION_ORDERS.get(names[j], "XYZ"))
+ if j == 0: # the root's channels give its position, not an offset to it
+ offset, channels = np.zeros(3), f"CHANNELS 6 Xposition Yposition Zposition {rotation}"
+ else:
+ offset, channels = rest[j] - rest[parents[j]], f"CHANNELS 3 {rotation}"
+ lines.append(f"{tab}{'JOINT' if j else 'ROOT'} {names[j]}")
+ lines.extend([tab + "{", f"{tab}\tOFFSET {_xyz(offset)}", f"{tab}\t{channels}"])
+ joint_order.append(j)
+ for c in children[j]:
+ add_joint(c, depth + 1)
+ if not children[j]:
+ end = points[BVH_END_SITES[names[j]]] - rest[j]
+ lines.extend([f"{tab}\tEnd Site", tab + "\t{", f"{tab}\t\tOFFSET {_xyz(end)}"])
+ lines.append(tab + "\t}")
+ lines.append(tab + "}")
+
+ add_joint(0, 0)
+
+ zeros = torch.zeros(L, 3)
+ rotvecs = torch.cat(
+ [params["global_orient"], params["body_pose"], zeros, zeros, zeros] # jaw, eyes: zero
+ + [params["left_hand_pose"], params["right_hand_pose"]],
+ dim=-1,
+ ).reshape(L, 55, 3)
+ euler = np.stack(
+ [
+ Rotation.from_rotvec(rotvecs[:, j].double().numpy()).as_euler(
+ BVH_ROTATION_ORDERS.get(names[j], "XYZ"), degrees=True
+ )
+ for j in range(55)
+ ],
+ axis=1,
+ ) # (L, 55, 3)
+ # SMPL-X rotates the body about the rest-pose pelvis: the pelvis is at J0 + transl
+ pelvis = rest[0] + 100 * params["transl"].double().numpy()
+ motion = np.concatenate([pelvis, _continuous_euler(euler)[:, joint_order].reshape(L, -1)], 1)
+ with open(path, "w") as f:
+ f.write("\n".join(lines) + f"\nMOTION\nFrames: {L}\nFrame Time: {1 / fps:.8f}\n")
+ np.savetxt(f, motion, fmt="%.4f")
+
+
+def _rest_pose(params):
+ """The shape of params in the zero pose at the origin: float32 SMPL-X parameters, each (1, D)"""
+ rest = {k: torch.zeros_like(v[:1], dtype=torch.float32) for k, v in params.items()}
+ rest["betas"] = params["betas"][:1].float() # the same in all frames
+ return rest
+
+
+def _continuous_euler(euler):
+ """Euler angles (L, J, 3) in degrees -> the same rotations with each frame's angles as close
+ as possible to the previous frame's: of the two angle triples of a rotation, (a, b, c) and
+ (a + 180, 180 - b, c + 180), the closer one, and each angle shifted by a multiple of 360. So
+ the angles do not jump, e.g. from 179 to -179, and software that interpolates between frames
+ turns the joints the short way."""
+ out = euler.copy()
+ joints = np.arange(euler.shape[1])
+ for t in range(1, len(euler)):
+ a, b, c = np.moveaxis(euler[t], -1, 0)
+ candidates = np.stack([euler[t], np.stack([a + 180, 180 - b, c + 180], axis=-1)])
+ candidates += 360 * np.round((out[t - 1] - candidates) / 360)
+ best = np.abs(candidates - out[t - 1]).sum(axis=-1).argmin(axis=0) # (J,)
+ out[t] = candidates[best, joints]
+ return out
+
+
+def _xyz(v):
+ return " ".join(f"{x:.4f}" for x in v)
diff --git a/third_party/ExMR/exmr/geometry/camera.py b/third_party/ExMR/exmr/geometry/camera.py
index d47d09a..fcac9df 100644
--- a/third_party/ExMR/exmr/geometry/camera.py
+++ b/third_party/ExMR/exmr/geometry/camera.py
@@ -5,10 +5,13 @@ import torch
from exmr.geometry.rotation_conversions import matrix_to_rotation_6d
-def estimate_K(img_w, img_h):
- """Default intrinsics for an unknown camera: principal point at the image center, focal
- length = image diagonal (53 degrees diagonal field of view)."""
+def estimate_K(img_w, img_h, f_mm=None):
+ """Intrinsics with the principal point at the image center. The focal length is f_mm, that of
+ a full-frame (36x24 mm) camera in mm, scaled from the full-frame diagonal to the image's; for
+ an unknown camera (f_mm None) the image diagonal (53 degrees diagonal field of view, ~43 mm)."""
focal_length = (img_w**2 + img_h**2) ** 0.5
+ if f_mm is not None:
+ focal_length = focal_length / (24**2 + 36**2) ** 0.5 * f_mm
K = torch.eye(3).float()
K[0, 0] = focal_length
K[1, 1] = focal_length
diff --git a/third_party/ExMR/exmr/model/exmr.py b/third_party/ExMR/exmr/model/exmr.py
index 7dd4e15..896fbeb 100644
--- a/third_party/ExMR/exmr/model/exmr.py
+++ b/third_party/ExMR/exmr/model/exmr.py
@@ -86,6 +86,7 @@ class ExMR(nn.Module):
smooth_incam=False,
smooth_global=True,
fps=30.0,
+ normalize_world=True,
):
"""
Args:
@@ -108,14 +109,18 @@ class ExMR(nn.Module):
smoother, but follows fast motion, e.g. of the feet, slightly less closely in
the image
smooth_global: smooth the world-frame motion over time (Gaussian, SMOOTHING_SIGMA)
+ normalize_world: normalize the first world pose to face +z at x=z=0.
+ RGB MoCap disables this to preserve its existing scene/camera frame.
fps: frame rate of the video, for the time windows of snap_to_ground, of the
static-camera drift correction and of the smoothing
Returns:
dict with
smplx_incam: SMPL-X parameters in the camera frame (each (B, L, D))
smplx_global: SMPL-X parameters in the gravity-aligned world frame (y up, ground
- at y=0 with postprocess or snap_to_ground)
- static_conf_logits: (B, L, 6) static-contact logits of
+ at y=0 with postprocess or snap_to_ground; with postprocess and normalize_world,
+ the motion starts
+ at x=z=0 facing +z)
+ static_conf_logits: (B, L, 6) logits of being static (not moving) for
[L_ankle, L_foot, R_ankle, R_foot, L_wrist, R_wrist]
"""
B, L = kp2d.shape[:2]
@@ -219,6 +224,11 @@ class ExMR(nn.Module):
if postprocess and not snap_to_ground:
# one shift for all frames, so last: puts the final mesh on the ground
smplx_global["transl"] = global_traj.put_on_ground(smplx_global, self.body_model)
+ if postprocess and normalize_world:
+ # facing +z in the first frame, as BVH, Blender and Unity expect a character to start
+ smplx_global["global_orient"], smplx_global["transl"] = global_traj.face_forward(
+ smplx_global, self.decoder
+ )
return {
"smplx_incam": smplx_incam,
diff --git a/third_party/ExMR/exmr/model/global_traj.py b/third_party/ExMR/exmr/model/global_traj.py
index c22d8b5..85a9603 100644
--- a/third_party/ExMR/exmr/model/global_traj.py
+++ b/third_party/ExMR/exmr/model/global_traj.py
@@ -1,5 +1,6 @@
"""World-frame trajectory: gravity-view rollout and static-joint post-processing (from GVHMR),
-and putting the motion on the ground, optionally snapped to a flat ground (as in PRIMAL)."""
+putting the motion on the ground, optionally snapped to a flat ground (as in PRIMAL), facing +z,
+and the feet's contacts with the ground."""
import torch
import torch.nn.functional as F
@@ -13,11 +14,18 @@ from exmr.geometry.rotation_conversions import (
from exmr.geometry.smoothing import gaussian_smooth, moving_average_smooth
from exmr.model.ik import CCDIK
-# joints with a static-contact prediction: [L_ankle, L_foot, R_ankle, R_foot, L_wrist, R_wrist]
+# joints with a static (not moving) prediction: [L_ankle, L_foot, R_ankle, R_foot, L_wrist, R_wrist]
STATIC_JOINT_IDS = [7, 10, 8, 11, 20, 21]
# snap_to_ground: some body part touches the ground at least this often (seconds), about the hang
# time of a jump (as in PRIMAL, Zhang et al., arXiv 2503.17544)
CONTACT_INTERVAL = 0.5
+# static_joint_ik: a toe's IK target stays this close (m, per axis) to the network's toe
+TOE_TARGET_MAX_OFFSET = 0.03
+# foot_contacts: a foot touches the ground where its ankle or toe is predicted static (not
+# moving) with at least STATIC_CONF and it is at most FOOT_CONTACT_HEIGHT (m) above the lowest
+# point of the body
+STATIC_CONF = 0.8
+FOOT_CONTACT_HEIGHT = 0.05
# static_cam_transl: the world root may deviate this far (m) from the camera-frame root before
# the slow part of the deviation (Gaussian smoothing, sigma in seconds) is removed
CAMERA_DEAD_BAND = 0.25
@@ -148,17 +156,26 @@ def static_cam_transl(smplx_incam, smplx_global, static_conf_logits, decoder, fp
return transl - drift
-def lowest_vertex_height(smplx_global, body_model, chunk_size=256):
- """Height (y) of the lowest SMPL-X mesh vertex in every frame, (B, L).
+def lowest_vertex_height(smplx_global, body_model, vertex_sets=None, chunk_size=256):
+ """Height (y) of the lowest SMPL-X mesh vertex in every frame, (B, L); with vertex_sets (a
+ list of S vertex id tensors, e.g. the feet, or slice(None) for all vertices), of the lowest
+ vertex of each set, (B, L, S).
The mesh is computed in chunks of frames: all of a long video's would take gigabytes.
"""
+
+ def lowest(height): # (N, V) -> (N) or (N, S)
+ if vertex_sets is None:
+ return height.amin(dim=-1)
+ return torch.stack([height[:, ids].amin(dim=-1) for ids in vertex_sets], dim=-1)
+
params = {k: v.flatten(0, 1) for k, v in smplx_global.items()} # (B * L, D)
- lowest = [
- body_model(**{k: v[i : i + chunk_size] for k, v in params.items()})[..., 1].amin(dim=-1)
+ heights = [
+ lowest(body_model(**{k: v[i : i + chunk_size] for k, v in params.items()})[..., 1])
for i in range(0, len(params["transl"]), chunk_size)
]
- return torch.cat(lowest).view(smplx_global["transl"].shape[:2])
+ heights = torch.cat(heights)
+ return heights.view(*smplx_global["transl"].shape[:2], *heights.shape[1:])
def put_on_ground(smplx_global, body_model):
@@ -191,6 +208,44 @@ def snap_to_ground(smplx_global, body_model, fps, interval=CONTACT_INTERVAL):
return transl
+def face_forward(smplx_global, decoder):
+ """Rotate the motion about the vertical axis through the first frame's root so that the body
+ faces +z in the first frame (from its hips and shoulders), and move that root to x=z=0.
+ Returns the (B, L, 3) global orientation and translation."""
+ joints = decoder.fk(**{k: v[:, :1] for k, v in smplx_global.items()})[:, 0] # (B, 22, 3)
+ left = joints[:, 1] - joints[:, 2] + joints[:, 16] - joints[:, 17] # (B, 3) hips, shoulders
+ # the rotation about y that turns the left direction to +x (then the body faces +z)
+ yaw = torch.atan2(left[:, 2], left[:, 0])
+ yaw = torch.where(left[:, [0, 2]].norm(dim=-1) > 1e-4, yaw, torch.zeros_like(yaw))
+ zeros = torch.zeros_like(yaw)
+ R = axis_angle_to_matrix(torch.stack([zeros, yaw, zeros], dim=-1)) # (B, 3, 3)
+ global_orient = matrix_to_axis_angle(
+ R[:, None] @ axis_angle_to_matrix(smplx_global["global_orient"])
+ )
+ # SMPL-X rotates the body about its rest-pose pelvis J0: the root is at J0 + transl
+ J0 = decoder.skeleton(smplx_global["betas"])[..., 0, :] # (B, L, 3)
+ root = smplx_global["transl"] + J0
+ start = root[:, :1] * root.new_tensor([1.0, 0.0, 1.0]) # the first root on the ground plane
+ transl = torch.einsum("bij,blj->bli", R, root - start) - J0
+ return global_orient, transl
+
+
+def foot_contacts(smplx_global, static_conf_logits, body_model):
+ """Where the feet touch the ground, (B, L, 2) bool [left, right], and the height of each
+ foot's lowest mesh vertex, (B, L, 2).
+
+ A foot touches the ground where its ankle or toe is predicted static (STATIC_CONF) and it is
+ the lowest part of the body (within FOOT_CONTACT_HEIGHT): not where a foot is held still in
+ the air, e.g. lying on the back with the legs up.
+ """
+ feet = [body_model.left_foot_vertices, body_model.right_foot_vertices]
+ heights = lowest_vertex_height(smplx_global, body_model, [*feet, slice(None)]) # (B, L, 3)
+ conf = static_conf_logits.sigmoid() # (B, L, 6): [L_ankle, L_foot, R_ankle, R_foot, ...]
+ static = torch.stack([conf[..., :2].amax(dim=-1), conf[..., 2:4].amax(dim=-1)], dim=-1)
+ lowest = heights[..., 2:] + FOOT_CONTACT_HEIGHT
+ return (static > STATIC_CONF) & (heights[..., :2] <= lowest), heights[..., :2]
+
+
def static_joint_ik(smplx_global, static_conf_logits, decoder):
"""Inverse kinematics so that ankles, feet and wrists predicted static stay put.
@@ -213,6 +268,13 @@ def static_joint_ik(smplx_global, static_conf_logits, decoder):
a = torch.cat([a[:, :offset], a[:, offset:] * a[:, :-offset]], dim=1)
offset *= 2
post_target_j3d[:, :, STATIC_JOINT_IDS] = b
+ # a toe predicted static can lie far from where it was when its contact began; pulling it all
+ # the way back turns the ankle a lot (tens of degrees), against the network's ankle. Bounded
+ # per axis like FlowHMR's ankle targets (github.com/flowhmr/flowhmr, runtime_v2m_postprocess)
+ toes = [10, 11]
+ offset = post_target_j3d[:, :, toes] - post_w_j3d[:, :, toes]
+ offset = offset.clamp(-TOE_TARGET_MAX_OFFSET, TOE_TARGET_MAX_OFFSET)
+ post_target_j3d[:, :, toes] = post_w_j3d[:, :, toes] + offset
parents = decoder.parents
chains = [ # (chain, targets: joint ids, their indices within the chain)
diff --git a/third_party/ExMR/exmr/pipeline.py b/third_party/ExMR/exmr/pipeline.py
index 0961536..1d3c099 100644
--- a/third_party/ExMR/exmr/pipeline.py
+++ b/third_party/ExMR/exmr/pipeline.py
@@ -12,7 +12,7 @@ import logging
import multiprocessing
import os
import shutil
-from concurrent.futures import ProcessPoolExecutor
+from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from dataclasses import asdict, dataclass
from pathlib import Path
@@ -21,7 +21,8 @@ import torch
from exmr import __version__
from exmr.assets import RTMW_SHA256, Assets
-from exmr.export import save_amass
+from exmr.body_models.smplx_model import SmplxModel
+from exmr.export import resample_motion, save_amass, save_bvh
from exmr.geometry.camera import bbx_xys_from_xyxy, cam_angvel_from_rotations, estimate_K
from exmr.preprocessing import video as V
from exmr.preprocessing.keypoints import VISIBILITY_THRESHOLD, detect_keypoints
@@ -29,6 +30,10 @@ from exmr.preprocessing.keypoints.mappings import COCO23, COCO63_LEFT_HAND, COCO
log = logging.getLogger("exmr")
+# without snap_to_ground, a hint is logged when the feet are higher above the ground (m, median)
+# where they touch it, usually vertical drift of the world-frame motion in long videos
+FLOATING_FEET_HINT = 0.05
+
@dataclass
class Options:
@@ -37,8 +42,12 @@ class Options:
detector: str = "yolo11m" # person detector: "yolo11m" or "yolo11x" (slower)
static_cam: bool = False # the camera is known to be static: no visual odometry
vo: str = "simplevo" # camera motion if not static_cam: "simplevo" or "dpvo" (optional)
+ start: float | None = None # only the part of the video from this time on (seconds)
+ end: float | None = None # ... up to this time (seconds; None: to its end)
+ f_mm: float | None = None # the camera's focal length (mm, full-frame equivalent), if known
fps30: bool = False # resample to 30 fps first (usually not needed; faster for e.g. 60 fps)
snap_to_ground: bool = False # flat ground, nothing to stand on: no vertical drift
+ export_fps: float | None = None # frame rate of the AMASS and BVH files (None: the video's)
smoothing: str = "global" # smooth the motion over time: "global" (world frame), "both", "none"
render: bool = True
keep_frames: bool = False # keep the extracted JPEG frames
@@ -53,6 +62,14 @@ class Options:
]:
if getattr(self, name) not in choices:
raise ValueError(f"Options.{name} must be one of {choices}")
+ if self.start is not None and self.start < 0:
+ raise ValueError("Options.start must be >= 0")
+ if self.end is not None and self.end <= (self.start or 0):
+ raise ValueError("Options.end must be after Options.start")
+ if self.f_mm is not None and self.f_mm <= 0:
+ raise ValueError("Options.f_mm must be > 0")
+ if self.export_fps is not None and self.export_fps <= 0:
+ raise ValueError("Options.export_fps must be > 0")
def run_video(video_path, output_dir, options=None, assets=None):
@@ -67,26 +84,42 @@ def run_video(video_path, output_dir, options=None, assets=None):
"DPVO is not installed: see the optional DPVO section of docs/INSTALL.md, or use "
"SimpleVO (--vo simplevo)"
)
+ from exmr.preprocessing.body_features import SAM_3D_BODY_ROOT
+
+ submodule = (SAM_3D_BODY_ROOT / "sam_3d_body").is_dir()
+ if not submodule and importlib.util.find_spec("sam_3d_body") is None:
+ raise RuntimeError(
+ "SAM 3D Body's code (the git submodule third_party/sam-3d-body) is missing, as the "
+ "repository was cloned without --recursive: run git submodule update --init"
+ )
+ if options.render:
+ _check_renderer()
+ # GeForce tensor cores run FP16 matmuls with FP32 accumulation at half rate: accumulating in
+ # FP16 makes the FP16 stages (Sapiens2, SAM 3D Body, HaMeR) 10-20% faster, with unchanged
+ # accuracy (keypoints/tokens change at the 1e-3 level). Other GPUs
+ # accumulate at full rate and gain nothing, so they keep the default.
+ torch.backends.cuda.matmul.allow_fp16_accumulation = _is_geforce()
video_path, output_dir = Path(video_path), Path(output_dir)
+ if options.start is not None:
+ duration = V.video_lwh(video_path)[0] / V.video_fps(video_path)
+ if options.start >= duration:
+ raise ValueError(f"start {options.start:g} s is past the video's end ({duration:.2f}s)")
name = video_path.stem
cache = output_dir / "cache"
cache.mkdir(parents=True, exist_ok=True)
run_info = {"video": str(video_path), "options": asdict(options), "exmr": __version__}
(output_dir / "run.json").write_text(json.dumps(run_info, indent=2) + "\n")
- if options.fps30:
+ cut_path = None
+ if options.start is not None or options.end is not None:
+ video_path = cut_path = _cut(video_path, output_dir, options)
+ elif options.fps30:
video_path = _resample_to_30fps(video_path, output_dir)
frame_dir = output_dir / "frames"
+ # every stage reads these frames, so all see the same images (ffmpeg applies the video's
+ # rotation and other display metadata) and the same frame count (also of variable frame rate
+ # videos)
num_frames = _extract_frames(video_path, frame_dir)
- if V.video_lwh(video_path)[0] != num_frames:
- # the container's frame count disagrees with the decoded frames (variable frame rate or
- # damaged container): rebuild a constant-frame-rate video from the frames, so that every
- # reader sees the same frames
- log.warning("Frame count mismatch, rebuilding a constant-frame-rate video")
- cfr_path = output_dir / f"{name}_cfr.mp4"
- if not cfr_path.exists():
- V.encode_frames(frame_dir, cfr_path, fps=V.video_fps(video_path))
- video_path = cfr_path
width, height = V.frame_size(frame_dir)
fps = V.video_fps(video_path)
log.info(f"{video_path}: {num_frames} frames, {width}x{height}, {fps:.2f} fps")
@@ -96,45 +129,96 @@ def run_video(video_path, output_dir, options=None, assets=None):
log.info("Running ExMR")
results = _run_model(data, options, fps, assets)
results["fps"] = fps
- _save_results(results, output_dir)
- save_amass(results["smplx_global"], fps, output_dir / f"{name}_amass.npz", assets.smplx)
+ smplx = SmplxModel(assets.smplx)
+ results |= compute_joints(results, smplx)
+ save_results(results, output_dir)
+ motion, export_fps = results["smplx_global"], fps
+ if options.export_fps:
+ motion = resample_motion(motion, fps, options.export_fps)
+ export_fps = options.export_fps
+ save_amass(motion, export_fps, output_dir / f"{name}_amass.npz", smplx)
+ save_bvh(motion, export_fps, output_dir / f"{name}.bvh", smplx)
if options.render:
log.info("Rendering")
- _render(results, frame_dir, output_dir, name, fps, assets)
+ render(results, frame_dir, output_dir, name, fps, smplx.cuda())
if not options.keep_frames:
shutil.rmtree(frame_dir)
+ if cut_path is not None:
+ cut_path.unlink() # lossless, so large; cut again in ~1 s if needed
return results
+def range_label(start, end):
+ """The part start..end (seconds; None: the video's beginning / end) for file names, e.g.
+ "5-15.5s" or "5s-end"."""
+ return f"{start or 0:g}-{end:g}s" if end is not None else f"{start or 0:g}s-end"
+
+
+def compute_joints(results, smplx):
+ """The joints of results["smplx_incam"] and results["smplx_global"] (each (L, D)) and their
+ projection into the image with results["K_fullimg"]: the keys joints_incam, joints_global,
+ joints_2d and joint_names of results.pt (see docs/OUTPUTS.md). About a second for 1000
+ frames on the CPU.
+
+ Args:
+ smplx: a SmplxModel of the parameters (on the CPU, like the results)
+ """
+ with torch.no_grad():
+ incam, world = (smplx.joints(**results[key]) for key in ("smplx_incam", "smplx_global"))
+ uvz = torch.einsum("lij,lkj->lki", results["K_fullimg"], incam)
+ return {
+ "joints_incam": incam,
+ "joints_global": world,
+ "joints_2d": uvz[..., :2] / uvz[..., 2:],
+ "joint_names": smplx.joint_names,
+ }
+
+
def _preprocess(video_path, frame_dir, L, width, height, options, assets, cache):
detector = assets.yolo(options.detector).name
- tracker_settings = {"video": str(video_path), "frames": L, "detector": detector}
+ # the ExMR version in every stage's settings: a new version recomputes the cached stages, whose
+ # code may have changed (e.g. 0.1.4's tracker and VO read rotated videos sideways)
+ tracker_settings = {
+ "video": str(video_path),
+ "frames": L,
+ "detector": detector,
+ "exmr": __version__,
+ }
backend = options.pose_backend
kp_settings = {**tracker_settings, "pose_backend": backend}
if backend == "sapiens2":
kp_settings["resolution"] = options.sapiens2_resolution
vo_cache = cache / "camera_rotations.pt"
- vo_settings = {"video": str(video_path), "frames": L, "odometry": options.vo}
+ vo_settings = {
+ "video": str(video_path),
+ "frames": L,
+ "odometry": options.vo,
+ "f_mm": options.f_mm,
+ "exmr": __version__,
+ }
- # SimpleVO needs only the video and the CPU: it runs in a separate process while the GPU
+ # SimpleVO needs only the frames and the CPU: it runs in a separate process while the GPU
# stages below run
simplevo = None
use_simplevo = options.vo == "simplevo" and not options.static_cam
if use_simplevo and not _is_cached(vo_cache, vo_settings):
log.info("Starting visual odometry in the background")
- simplevo = _in_background(_simplevo_rotations, video_path)
+ simplevo = _in_background(_simplevo_rotations, frame_dir, options.f_mm)
+
+ # RTMW's session build and warm-up run in a thread while
+ # the tracker runs, which hides about half of it
+ rtmw = None
+ if backend == "rtmw" and not _is_cached(cache / "keypoints.pt", kp_settings):
+ rtmw = _in_thread(_warm_rtmw, assets.rtmw)
def track():
from exmr.preprocessing.tracker import Tracker
- return Tracker(assets.yolo(options.detector)).get_main_track(video_path).float()
+ return Tracker(assets.yolo(options.detector)).get_main_track(frame_dir).float()
bbx_xyxy = _cached(cache / "tracks.pt", tracker_settings, track) # (L, 4)
- bbx_xys = bbx_xys_from_xyxy(bbx_xyxy, base_enlarge=1.2).float() # (L, 3)
- K = estimate_K(width, height)[None].repeat(L, 1, 1) # (L, 3, 3)
-
- threshold = VISIBILITY_THRESHOLD[backend]
+ K = estimate_K(width, height, options.f_mm)[None].repeat(L, 1, 1) # (L, 3, 3)
def keypoints():
if backend == "sapiens2":
@@ -142,28 +226,24 @@ def _preprocess(video_path, frame_dir, L, width, height, options, assets, cache)
backend, assets.sapiens2, frame_dir, bbx_xyxy,
resolution=options.sapiens2_resolution,
) # fmt: skip
- return detect_keypoints(backend, assets.rtmw, frame_dir, bbx_xyxy, sha256=RTMW_SHA256)
+ return rtmw.result()(frame_dir, bbx_xyxy)
kp2d = _cached(cache / "keypoints.pt", kp_settings, keypoints) # (L, 63, 3)
def body_features():
from exmr.preprocessing.body_features import SamBodyFeatures
- return SamBodyFeatures(assets.sam_3d_body)(frame_dir, bbx_xyxy, K)
+ # the backbone profits from FP16 accumulation only in float16 (see run_video)
+ fp16 = torch.backends.cuda.matmul.allow_fp16_accumulation
+ return SamBodyFeatures(assets.sam_3d_body, fp16=fp16)(frame_dir, bbx_xyxy, K)
- body_feat = _cached(cache / "body_features.pt", tracker_settings, body_features)
+ body_settings = {**tracker_settings, "f_mm": options.f_mm}
+ body_feat = _cached(cache / "body_features.pt", body_settings, body_features)
def hand_features():
- from exmr.preprocessing.hand_features import HamerHandFeatures, hand_boxes_from_keypoints
+ from exmr.preprocessing.hand_features import HamerHandFeatures
- boxes = torch.stack(
- [
- hand_boxes_from_keypoints(kp2d[:, COCO63_LEFT_HAND], threshold),
- hand_boxes_from_keypoints(kp2d[:, COCO63_RIGHT_HAND], threshold),
- ],
- dim=1,
- ) # (L, 2, 4)
- return HamerHandFeatures(assets.hamer)(frame_dir, boxes)
+ return HamerHandFeatures(assets.hamer)(frame_dir, hand_boxes(kp2d, backend))
hand_feat = _cached(cache / "hand_features.pt", kp_settings, hand_features)
@@ -175,38 +255,63 @@ def _preprocess(video_path, frame_dir, L, width, height, options, assets, cache)
from exmr.preprocessing.visual_odometry import DPVOOdometry
if options.vo == "dpvo":
- return DPVOOdometry(assets.dpvo)(video_path, K[0])
+ return DPVOOdometry(assets.dpvo)(frame_dir, K[0])
return torch.from_numpy(simplevo.result()) # waits for SimpleVO to finish
R_w2c = _cached(vo_cache, vo_settings, camera_rotations)
+ inputs = model_inputs(kp2d, bbx_xyxy, K, R_w2c, body_feat, hand_feat, backend)
+ return {**inputs, "bbx_xyxy": bbx_xyxy}
+
+
+def hand_boxes(kp2d, backend):
+ """(L, 2, 4) boxes [left, right] of the hands for HaMeR, from the (L, 63, 3) keypoints of the
+ pose backend ("sapiens2" or "rtmw")."""
+ from exmr.preprocessing.hand_features import hand_boxes_from_keypoints
+
+ threshold = VISIBILITY_THRESHOLD[backend]
+ return torch.stack(
+ [
+ hand_boxes_from_keypoints(kp2d[:, COCO63_LEFT_HAND], threshold),
+ hand_boxes_from_keypoints(kp2d[:, COCO63_RIGHT_HAND], threshold),
+ ],
+ dim=1,
+ )
+
+
+def model_inputs(kp2d, bbx_xyxy, K_fullimg, R_w2c, body_feat, hand_feat, backend):
+ """ExMR's inputs (see ExMR.forward, without the batch dimension) from the preprocessing
+ stages' outputs of one video: (L, 63, 3) keypoints of the pose backend ("sapiens2" or
+ "rtmw"), (L, 4) person boxes, (L, 3, 3) intrinsics, (L, 3, 3) world-to-camera rotations,
+ (L, 1024) SAM 3D Body and (L, 2, 1024) HaMeR features."""
# body + foot keypoints; RTMW's raw scores become a binary visibility for the network
kp23 = kp2d[:, COCO23].clone()
if backend == "rtmw":
- kp23[..., 2] = (kp23[..., 2] > threshold).to(kp23.dtype)
+ kp23[..., 2] = (kp23[..., 2] > VISIBILITY_THRESHOLD[backend]).to(kp23.dtype)
return {
"kp2d": kp23,
- "bbx_xys": bbx_xys,
- "bbx_xyxy": bbx_xyxy,
- "K_fullimg": K,
+ "bbx_xys": bbx_xys_from_xyxy(bbx_xyxy, base_enlarge=1.2).float(),
+ "K_fullimg": K_fullimg,
"cam_angvel": cam_angvel_from_rotations(R_w2c),
"body_feat": body_feat,
"hand_feat": hand_feat,
}
-def _simplevo_rotations(video_path):
+def _simplevo_rotations(frame_dir, f_mm=None):
"""SimpleVO's (L, 3, 3) camera rotations, as a numpy array: torch tensors would be returned
- from the separate process through shared memory."""
+ from the separate process through shared memory. f_mm: the focal length (SimpleVO's default
+ if None)."""
from exmr.preprocessing.visual_odometry import SimpleVO
- return SimpleVO(progress=False)(video_path).numpy()
+ vo = SimpleVO(progress=False) if f_mm is None else SimpleVO(f_mm=f_mm, progress=False)
+ return vo(frame_dir).numpy()
-def _run_model(data, options, fps, assets, model=None):
+def _run_model(data, options, fps, assets):
from exmr.model.exmr import ExMR
- if model is None:model = ExMR.from_pretrained(assets.exmr, assets.smplx)
+ model = ExMR.from_pretrained(assets.exmr, assets.smplx)
inputs = {
k: data[k][None].cuda()
for k in ("kp2d", "bbx_xys", "K_fullimg", "cam_angvel", "body_feat", "hand_feat")
@@ -219,18 +324,39 @@ def _run_model(data, options, fps, assets, model=None):
smooth_global=options.smoothing != "none",
fps=fps,
)
+ from exmr.model.global_traj import foot_contacts
+
+ contact, foot_height = foot_contacts(
+ out["smplx_global"], out["static_conf_logits"], model.body_model
+ )
+ if not options.snap_to_ground:
+ _hint_floating_feet(foot_height[contact])
del model
_free_gpu_memory()
return {
"smplx_incam": {k: v[0].cpu() for k, v in out["smplx_incam"].items()},
"smplx_global": {k: v[0].cpu() for k, v in out["smplx_global"].items()},
"static_conf_logits": out["static_conf_logits"][0].cpu(),
+ "foot_contact": contact[0].cpu(),
"K_fullimg": data["K_fullimg"],
"bbx_xyxy": data["bbx_xyxy"],
}
-def _save_results(results, output_dir):
+def _hint_floating_feet(height):
+ """height: of the feet where they touch the ground (all frames, both feet)"""
+ if len(height) and height.median() > FLOATING_FEET_HINT:
+ log.warning(
+ f"In the world frame, the feet are {height.median() * 100:.0f} cm above the ground "
+ "(median) where they touch it, probably vertical drift. If the scene has a single "
+ "flat ground and nothing to stand on, snap_to_ground (demo: --snap_to_ground) keeps "
+ "the body on it"
+ )
+
+
+def save_results(results, output_dir):
+ """Save the results of run_video as <output_dir>/results.pt and results.npz (the same values
+ with flattened keys, e.g. smplx_global_transl), see docs/OUTPUTS.md."""
_atomic_save(results, output_dir / "results.pt")
flat = {}
for key, value in results.items():
@@ -241,21 +367,62 @@ def _save_results(results, output_dir):
np.savez(output_dir / "results.npz", **flat)
-def _render(results, frame_dir, output_dir, name, fps, assets):
- from exmr.body_models.smplx_model import SmplxModel
+def _is_geforce():
+ return torch.cuda.is_available() and "GeForce" in torch.cuda.get_device_name()
+
+
+def _check_renderer():
+ """Render a triangle with nvdiffrast, so that a missing or broken install (e.g. built for
+ another torch version or GPU) stops the run now rather than after the reconstruction."""
+ try:
+ import nvdiffrast.torch as dr
+
+ triangle = torch.tensor([[[-1.0, -1, 0, 1], [1, -1, 0, 1], [0, 1, 0, 1]]], device="cuda")
+ faces = torch.tensor([[0, 1, 2]], dtype=torch.int32, device="cuda")
+ dr.rasterize(dr.RasterizeCudaContext(), triangle, faces, (8, 8))
+ except Exception as e:
+ raise RuntimeError(
+ f"nvdiffrast, which renders the videos, does not work: {e}\nInstall it as in "
+ "docs/INSTALL.md, or skip the videos (--no_render); the other outputs need no "
+ "nvdiffrast"
+ ) from e
+
+
+def render(
+ results, frame_dir, output_dir, name, fps, smplx, videos=("incam", "global", "incam_global")
+):
+ """Render the results of run_video over the frames (frame_dir/%06d.jpg) and in the world
+ frame: <output_dir>/<name>_<video>.mp4 for the videos "incam" (camera view), "global" (world
+ view) and "incam_global" (both side by side); only the views needed are rendered. smplx: a
+ SmplxModel on the GPU."""
from exmr.vis.render import render_videos
- smplx = SmplxModel(assets.smplx).cuda()
with torch.no_grad():
verts_incam = smplx(**{k: v.cuda() for k, v in results["smplx_incam"].items()})
verts_global = smplx(**{k: v.cuda() for k, v in results["smplx_global"].items()})
render_videos(
frame_dir, verts_incam, verts_global, smplx.faces, smplx.J_regressor.cuda(),
results["K_fullimg"][0], fps,
- [output_dir / f"{name}_{view}.mp4" for view in ("incam", "global", "incam_global")],
+ {view: output_dir / f"{name}_{view}.mp4" for view in videos},
) # fmt: skip
+def _warm_rtmw(checkpoint):
+ from exmr.preprocessing.keypoints.rtmw import RTMWKeypoints
+
+ model = RTMWKeypoints(checkpoint, sha256=RTMW_SHA256)
+ model.warm_up()
+ return model
+
+
+def _in_thread(fn, *args):
+ """The future result of fn(*args), computed in a new thread."""
+ executor = ThreadPoolExecutor(1)
+ future = executor.submit(fn, *args)
+ executor.shutdown(wait=False)
+ return future
+
+
def _in_background(fn, *args):
"""The future result of fn(*args), computed in a new process. The process is started with
"spawn": a forked process would inherit this process's state (e.g. CUDA, OpenCV's threads)."""
@@ -303,6 +470,20 @@ def _extract_frames(video_path, frame_dir):
return num_frames
+def _cut(video_path, output_dir, options):
+ """The part of the video from options.start to options.end, in output_dir; with options.fps30
+ also resampled to 30 fps (unless it has ~30 fps already, as _resample_to_30fps)."""
+ resample = options.fps30 and abs(V.video_fps(video_path) - 30) >= 0.5
+ label = range_label(options.start, options.end)
+ out = output_dir / f"{video_path.stem}_{label}{'_30fps' if resample else ''}.mp4"
+ if not out.exists():
+ log.info(f"Cutting {label}" + (", resampled to 30 fps" if resample else ""))
+ tmp = out.with_name(out.stem + ".tmp.mp4") # no complete-looking file if interrupted
+ V.cut(video_path, tmp, options.start, options.end, fps=30 if resample else None)
+ os.replace(tmp, out)
+ return out
+
+
def _resample_to_30fps(video_path, output_dir):
fps = V.video_fps(video_path)
if abs(fps - 30) < 0.5:
diff --git a/third_party/ExMR/exmr/preprocessing/body_features.py b/third_party/ExMR/exmr/preprocessing/body_features.py
index 4f4c82f..0df2e69 100644
--- a/third_party/ExMR/exmr/preprocessing/body_features.py
+++ b/third_party/ExMR/exmr/preprocessing/body_features.py
@@ -88,11 +88,14 @@ class SamBodyFeatures:
Args:
checkpoint_dir: directory with model.ckpt, model_config.yaml and assets/mhr_model.pt of
facebook/sam-3d-body-dinov3
+ fp16: run the backbone in float16 instead of the checkpoint's bfloat16 (SAM 3D Body's own
+ FP16_TYPE option). Faster only with FP16 accumulation
+ (torch.backends.cuda.matmul.allow_fp16_accumulation); tokens change at the 1e-3 level
"""
TOKEN_DIM = 1024
- def __init__(self, checkpoint_dir, batch_size=32, num_workers=8, device="cuda", low_memory=False):
+ def __init__(self, checkpoint_dir, fp16=False, batch_size=32, num_workers=8, device="cuda", low_memory=False):
sam_3d_body, self._transforms, self._load_image, self._prepare_batch, self._to = (
_import_sam_3d_body()
)
@@ -107,6 +110,11 @@ class SamBodyFeatures:
mhr_path=str(checkpoint_dir / "assets" / "mhr_model.pt"),
)
assert model.cfg.MODEL.DECODER.DO_HAND_DETECT_TOKENS
+ if fp16:
+ for t in [*model.backbone.parameters(), *model.backbone.buffers()]:
+ if t.dtype == torch.bfloat16:
+ t.data = t.data.half()
+ model.backbone_dtype = torch.float16
self.model = model.eval().to(device)
self.input_size = model_cfg.MODEL.IMAGE_SIZE
self.batch_size, self.num_workers, self.device = batch_size, num_workers, device
@@ -158,6 +166,11 @@ class SamBodyFeatures:
tokens[i : i + bs] = self._tokens[:, 0].cpu()
i += bs
pbar.update(bs)
+ if not torch.isfinite(tokens).all():
+ raise RuntimeError(
+ "Non-finite SAM 3D Body features, probably a float16 overflow: disable FP16 "
+ "accumulation in run_video (exmr/pipeline.py) and please report this"
+ )
return tokens
diff --git a/third_party/ExMR/exmr/preprocessing/hand_features.py b/third_party/ExMR/exmr/preprocessing/hand_features.py
index 79a5a38..387ad0c 100644
--- a/third_party/ExMR/exmr/preprocessing/hand_features.py
+++ b/third_party/ExMR/exmr/preprocessing/hand_features.py
@@ -120,6 +120,11 @@ class HamerHandFeatures:
)
i += bs
pbar.update(bs)
+ if not torch.isfinite(tokens).all():
+ raise RuntimeError(
+ "Non-finite HaMeR hand features, probably a float16 overflow: disable FP16 "
+ "accumulation in run_video (exmr/pipeline.py) and please report this"
+ )
return tokens
def _forward(self, crops):
diff --git a/third_party/ExMR/exmr/preprocessing/keypoints/rtmw.py b/third_party/ExMR/exmr/preprocessing/keypoints/rtmw.py
index da97e16..9f6015e 100644
--- a/third_party/ExMR/exmr/preprocessing/keypoints/rtmw.py
+++ b/third_party/ExMR/exmr/preprocessing/keypoints/rtmw.py
@@ -43,6 +43,13 @@ class RTMWKeypoints:
if self.session.get_providers()[0] != "CUDAExecutionProvider":
raise RuntimeError("ONNX Runtime CUDA provider unavailable for RTMW")
+ def warm_up(self):
+ """Run one batch of zeros: ONNX Runtime and cuDNN set the network up for the batch shape
+ on its first use (~7 s), which can thereby happen while e.g. the tracker runs."""
+ inp = self.session.get_inputs()[0]
+ w, h = INPUT_SIZE
+ self.session.run(None, {inp.name: np.zeros((self.batch_size, 3, h, w), dtype=np.float32)})
+
def __call__(self, frame_dir, bbx_xyxy):
"""frame_dir with %06d.jpg frames, bbx_xyxy (L, 4) -> (L, 63, 3) [x, y, raw score]"""
boxes = bbx_xyxy.cpu().numpy()
diff --git a/third_party/ExMR/exmr/preprocessing/tracker.py b/third_party/ExMR/exmr/preprocessing/tracker.py
index 0a61424..a21f866 100644
--- a/third_party/ExMR/exmr/preprocessing/tracker.py
+++ b/third_party/ExMR/exmr/preprocessing/tracker.py
@@ -1,5 +1,6 @@
"""Person detection and tracking (YOLO11 + ByteTrack); keeps the most prominent person."""
+import math
import queue
import threading
from collections import defaultdict
@@ -10,11 +11,12 @@ from tqdm import tqdm
from ultralytics import YOLO
from exmr.geometry.smoothing import moving_average_smooth
-from exmr.preprocessing.video import video_lwh
+from exmr.preprocessing.video import frame_paths, frame_size, read_frames
class Tracker:
- """Tracks all people in a video and returns the boxes of the most prominent one.
+ """Tracks all people in a video's extracted frames and returns the boxes of the most
+ prominent one.
Args:
checkpoint: YOLO11 detection weights (yolo11m.pt is fast, yolo11x.pt more accurate)
@@ -22,14 +24,17 @@ class Tracker:
def __init__(self, checkpoint):
self.yolo = YOLO(checkpoint)
- # decode the video in a background thread while the detector runs
- self.yolo.add_callback("on_predict_start", _start_video_prefetch)
- self.yolo.add_callback("on_predict_end", _close_video_prefetch)
-
- def track(self, video_path):
- """Per frame, a list of {"id": track id, "bbx_xyxy": (4,) array} detections."""
+ self._frame_dir = None
+ # decode the frames in background threads while the detector runs
+ self.yolo.add_callback("on_predict_start", self._start_prefetch)
+ self.yolo.add_callback("on_predict_end", _close_prefetch)
+
+ def track(self, frame_dir):
+ """frame_dir with %06d.jpg frames -> per frame, a list of {"id": track id,
+ "bbx_xyxy": (4,) array} detections."""
+ self._frame_dir = frame_dir
results = self.yolo.track(
- video_path,
+ str(frame_dir),
device="cuda",
conf=0.5,
classes=0, # person
@@ -42,12 +47,12 @@ class Tracker:
# on the CPU and dominates this stage, while we only need the main person's boxes
tracker="bytetrack.yaml",
)
- # skip Ultralytics' warm-up: its 640x640 dummy image has a shape that the video's frames
+ # skip Ultralytics' warm-up: its 640x640 dummy image has a shape that the frames
# never have, and cuDNN 9 spends ~1 s setting up each new input shape
self.yolo.predictor.done_warmup = True
track_history = []
try:
- for result in tqdm(results, total=video_lwh(video_path)[0], desc="Tracking"):
+ for result in tqdm(results, total=len(frame_paths(frame_dir)), desc="Tracking"):
frame = []
if result.boxes.id is not None:
track_ids = result.boxes.id.int().cpu().tolist()
@@ -58,21 +63,26 @@ class Tracker:
try:
results.close()
finally:
- _close_video_prefetch(self.yolo.predictor)
+ _close_prefetch(self.yolo.predictor)
return track_history
- def get_main_track(self, video_path):
+ def _start_prefetch(self, predictor):
+ if predictor.dataset.mode != "image":
+ raise ValueError("Tracker prefetch expects a directory of frames")
+ predictor.dataset = _PrefetchFrames(predictor.dataset, self._frame_dir)
+
+ def get_main_track(self, frame_dir):
"""(L, 4) bounding boxes [x1, y1, x2, y2] of the most prominent person, i.e. the track
with the largest summed box area; frames where it is missing are interpolated."""
- L, w, h = video_lwh(video_path)
+ L, (w, h) = len(frame_paths(frame_dir)), frame_size(frame_dir)
id_to_frame_ids = defaultdict(list)
id_to_bbx_xyxys = defaultdict(list)
- for frame_id, frame in enumerate(self.track(video_path)):
+ for frame_id, frame in enumerate(self.track(frame_dir)):
for det in frame:
id_to_frame_ids[det["id"]].append(frame_id)
id_to_bbx_xyxys[det["id"]].append(det["bbx_xyxy"])
if not id_to_frame_ids:
- raise RuntimeError(f"No person detected in {video_path}")
+ raise RuntimeError(f"No person detected in {frame_dir}")
def area_sum(track_id):
boxes = np.array(id_to_bbx_xyxys[track_id])
@@ -120,12 +130,14 @@ def _runs_of_true(mask):
return [torch.arange(s, e) for s, e in zip(starts, ends)]
-class _PrefetchVideo:
- """Wraps ultralytics' video loader to decode in a background thread (at most two batches
- ahead). Only the worker thread touches the OpenCV capture; batches are consumed in order."""
+class _PrefetchFrames:
+ """Replaces ultralytics' image loader: decodes the frames of frame_dir in background threads
+ (at most two batches ahead); batches are consumed in order. Every frame gets frame_dir as its
+ path, like the frames of a video: ultralytics resets the tracker whenever the path changes."""
- def __init__(self, loader):
- self.loader = loader
+ def __init__(self, loader, frame_dir):
+ self.loader, self.frame_dir = loader, str(frame_dir)
+ self._paths = frame_paths(frame_dir)
self._pending = queue.Queue(maxsize=2)
self._stop = threading.Event()
self._thread = None
@@ -134,7 +146,7 @@ class _PrefetchVideo:
return getattr(self.loader, name)
def __len__(self):
- return len(self.loader)
+ return math.ceil(len(self._paths) / self.loader.bs) # number of batches
def _put(self, item):
while not self._stop.is_set():
@@ -146,18 +158,24 @@ class _PrefetchVideo:
def _decode(self):
try:
- for batch in self.loader:
+ imgs = []
+ for img in read_frames(self._paths):
if self._stop.is_set():
break
- self._put((True, batch))
+ imgs.append(img)
+ if len(imgs) == self.loader.bs:
+ self._put_batch(imgs)
+ imgs = []
+ if imgs and not self._stop.is_set():
+ self._put_batch(imgs)
except Exception as error:
self._put((False, error))
finally:
- try:
- if self.loader.cap is not None:
- self.loader.cap.release()
- finally:
- self._put((True, None))
+ self._put((True, None))
+
+ def _put_batch(self, imgs):
+ """(paths, BGR images, info strings), like ultralytics' loaders"""
+ self._put((True, ([self.frame_dir] * len(imgs), imgs, [""] * len(imgs))))
def __iter__(self):
if self._thread is None and not self._stop.is_set():
@@ -184,9 +202,7 @@ class _PrefetchVideo:
if self._thread is not None:
self._thread.join(timeout=5)
if self._thread.is_alive():
- raise RuntimeError("Video decoder did not stop within five seconds")
- elif self.loader.cap is not None:
- self.loader.cap.release()
+ raise RuntimeError("Frame decoder did not stop within five seconds")
while True: # release queued frames even if inference exited early
try:
self._pending.get_nowait()
@@ -194,13 +210,6 @@ class _PrefetchVideo:
break
-def _start_video_prefetch(predictor):
- loader = predictor.dataset
- if loader.nf != 1 or loader.mode != "video":
- raise ValueError("Tracker decode prefetch expects exactly one video file")
- predictor.dataset = _PrefetchVideo(loader)
-
-
-def _close_video_prefetch(predictor):
- if isinstance(getattr(predictor, "dataset", None), _PrefetchVideo):
+def _close_prefetch(predictor):
+ if isinstance(getattr(predictor, "dataset", None), _PrefetchFrames):
predictor.dataset.close()
diff --git a/third_party/ExMR/exmr/preprocessing/video.py b/third_party/ExMR/exmr/preprocessing/video.py
index 7332418..f881b5c 100644
--- a/third_party/ExMR/exmr/preprocessing/video.py
+++ b/third_party/ExMR/exmr/preprocessing/video.py
@@ -1,10 +1,12 @@
"""Video probing, frame extraction and re-encoding (ffmpeg / PyAV / TurboJPEG)."""
+import collections
import functools
+import math
import re
import shutil
import subprocess
-from fractions import Fraction
+from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import av
@@ -36,7 +38,34 @@ def extract_frames(video_path, output_dir, quality=2):
["-i", video_path, "-fps_mode", "passthrough", "-q:v", quality, "-start_number", 0,
output_dir / "%06d.jpg"]
) # fmt: skip
- return sum(1 for p in output_dir.glob("*.jpg") if re.fullmatch(r"\d{6}", p.stem))
+ return len(frame_paths(output_dir))
+
+
+def frame_paths(frame_dir):
+ """The extracted frames' files frame_dir/%06d.jpg, in order."""
+ return sorted(p for p in Path(frame_dir).glob("*.jpg") if re.fullmatch(r"\d{6}", p.stem))
+
+
+def read_frames(paths, threads=8):
+ """Yields the (H, W, 3) BGR uint8 images of the JPEG files paths, in order, decoded by a pool
+ of threads (OpenCV releases the GIL) at most 2 * threads frames ahead. One thread decodes
+ 1080p JPEGs at ~200 frames/s, a fifth of OpenCV's video decoding; 8 decode them as fast, 4K
+ ones twice as fast."""
+ with ThreadPoolExecutor(threads) as pool:
+ pending = collections.deque()
+ for path in paths:
+ pending.append(pool.submit(_imread, path))
+ if len(pending) > 2 * threads:
+ yield pending.popleft().result()
+ while pending:
+ yield pending.popleft().result()
+
+
+def _imread(path):
+ img = read_bgr_frame(path)
+ if img is None:
+ raise RuntimeError(f"Could not read {path}")
+ return img
def frame_size(frame_dir):
@@ -120,21 +149,52 @@ def h264_args(crf):
return [*codec, "-pix_fmt", "yuv420p"]
-def encode_frames(frame_dir, out_path, fps, crf=17):
- """frame_dir/%06d.jpg -> constant-frame-rate H.264 video with exactly that many frames.
+def resample_fps(in_path, out_path, fps=30, crf=17):
+ """Re-encode a video to a constant frame rate (drops/duplicates frames)."""
+ _run_ffmpeg(["-i", in_path, "-vf", f"fps={fps}", "-an", *h264_args(crf), out_path])
+ return out_path
+
- Used to rebuild variable-frame-rate or damaged videos, whose container frame count disagrees
- with the frames ffmpeg decodes, so that every reader sees the same frames.
- """
- fps = Fraction(fps).limit_denominator(1000)
+def cut(in_path, out_path, start=None, end=None, fps=None, crf=17):
+ """The frames of a video with timestamps in [start, end) (seconds; None: from its beginning /
+ to its end), encoded losslessly: they are exactly the input's frames. With fps, resampled to
+ that frame rate instead (re-encoded as in resample_fps)."""
+ # -ss before -i: seek in the input, frame-accurate (decoded frames before start are dropped);
+ # the frames' timestamps then count from start. The end is a trim filter (keeps timestamps
+ # < end, then ends the stream): -t / -to would count from the first frame after start instead
+ # (one frame too many if start falls between frames). In videos whose time base is the frame
+ # interval (e.g. 1/25 s), a start between two frames is rounded, which can shift the end by a
+ # frame
+ filters = [f"trim=end={end - (start or 0):.6f}"] if end is not None else []
+ if fps is None:
+ codec = ["-fps_mode", "passthrough", "-c:v", "libx264", "-preset", "ultrafast", "-qp", 0]
+ else:
+ filters.append(f"fps={fps}")
+ codec = h264_args(crf)
_run_ffmpeg(
- ["-framerate", fps, "-start_number", 0, "-i", Path(frame_dir) / "%06d.jpg",
- *h264_args(crf), out_path]
+ ["-ss", f"{start or 0:.6f}", "-i", in_path, "-an",
+ *(["-vf", ",".join(filters)] if filters else []), *codec, out_path]
) # fmt: skip
+ with av.open(str(out_path)) as c:
+ if not c.streams.video or not c.streams.video[0].frames:
+ raise ValueError(f"no frames between start={start} and end={end} (seconds)")
return out_path
-def resample_fps(in_path, out_path, fps=30, crf=17):
- """Re-encode a video to a constant frame rate (drops/duplicates frames)."""
- _run_ffmpeg(["-i", in_path, "-vf", f"fps={fps}", "-an", *h264_args(crf), out_path])
- return out_path
+def parse_time(text):
+ """Seconds from a time "83.5", "1:23.5" or "0:01:23.5" ([[hh:]mm:]ss)."""
+ error = ValueError(f"not a time: {text!r} (use seconds or [hh:]mm:ss)")
+ parts = text.strip().split(":")
+ if not 1 <= len(parts) <= 3:
+ raise error
+ seconds = 0.0
+ for i, part in enumerate(parts):
+ try:
+ value = float(part)
+ except ValueError:
+ raise error from None
+ # minutes and seconds after a colon are below 60
+ if not math.isfinite(value) or value < 0 or (i > 0 and value >= 60):
+ raise error
+ seconds = seconds * 60 + value
+ return seconds
diff --git a/third_party/ExMR/exmr/preprocessing/visual_odometry.py b/third_party/ExMR/exmr/preprocessing/visual_odometry.py
index 802afcd..63e97ea 100644
--- a/third_party/ExMR/exmr/preprocessing/visual_odometry.py
+++ b/third_party/ExMR/exmr/preprocessing/visual_odometry.py
@@ -12,14 +12,13 @@ import threading
from pathlib import Path
import cv2
-import imageio.v3 as iio
import numpy as np
import pycolmap
import torch
from tqdm import tqdm
from exmr.geometry.rotation_conversions import quaternion_to_matrix
-from exmr.preprocessing.video import video_lwh
+from exmr.preprocessing.video import frame_paths, frame_size, read_frames
DPVO_ROOT = Path(__file__).resolve().parents[2] / "third_party" / "DPVO"
@@ -33,34 +32,49 @@ class SimpleVO:
step: frame stride between matched frames
f_mm: assumed focal length in mm of a full-frame (36x24 mm) camera
progress: show a progress bar
+ frame_reader: optional image iterator. Receives file paths normally,
+ or sampled integer indices when the caller supplies frame_count.
"""
- def __init__(self, scale=0.5, step=8, f_mm=24, progress=True):
+ def __init__(self, scale=0.5, step=8, f_mm=24, progress=True, frame_reader=None):
self.scale, self.step, self.f_mm, self.progress = scale, step, f_mm, progress
self.sift = cv2.SIFT_create()
+ # RGB MoCap: optional explicit pixel reader preserves the validated
+ # canonical-video sampling without changing pose estimation.
+ self.frame_reader = frame_reader
- def __call__(self, video_path):
- """(L, 3, 3) world-to-camera rotations (float64), the first one identity."""
+ def __call__(self, frame_dir=None, *, frame_count=None):
+ """JPEG frame_dir, or frame_reader plus frame_count, -> (L, 3, 3) rotations.
+
+ World-to-camera, float64, first one identity. The callback/count route
+ can read a canonical video without extracting duplicate JPEG files.
+ """
with _opencv_multithreading():
- return torch.from_numpy(self.poses(video_path)[:, :3, :3])
+ return torch.from_numpy(self.poses(frame_dir, frame_count=frame_count)[:, :3, :3])
- def poses(self, video_path):
+ def poses(self, frame_dir=None, *, frame_count=None):
"""(L, 4, 4) world-to-camera transforms (float64), the first one identity."""
_reset_random_state()
- # keep only the frames that are matched, every step-th and the last one: all frames of a
- # long video would not fit into memory
- frames = {} # frame index -> (H, W, 3) RGB
- reader = iio.imiter(
- video_path,
- plugin="pyav",
- thread_type="FRAME",
- filter_sequence=[("scale", f"iw*{self.scale}:ih*{self.scale}")],
- )
- for i, frame in enumerate(reader):
- if i % self.step == 0:
- frames[i] = frame
- frames[i] = frame # the last frame
- sample_idxs, frames = list(frames), list(frames.values())
+ # only the frames that are matched are read: every step-th and the last one
+ # RGB MoCap's canonical-video reader accepts frame indices directly;
+ # no duplicate JPEG extraction is needed solely to enumerate frames.
+ if frame_count is None:
+ paths = frame_paths(frame_dir)
+ count = len(paths)
+ else:
+ if self.frame_reader is None or type(frame_count) is not int or frame_count < 1:
+ raise ValueError("frame_count requires a frame_reader and a positive integer")
+ paths = None
+ count = frame_count
+ sample_idxs = sorted({*range(0, count, self.step), count - 1})
+ sources = [paths[i] for i in sample_idxs] if paths is not None else sample_idxs
+ frames = [ # (H, W, 3) RGB
+ cv2.cvtColor(
+ cv2.resize(img, None, fx=self.scale, fy=self.scale, interpolation=cv2.INTER_AREA),
+ cv2.COLOR_BGR2RGB,
+ )
+ for img in (self.frame_reader or read_frames)(sources)
+ ]
H, W = frames[0].shape[:2]
# pinhole camera with the principal point at the center
@@ -144,33 +158,41 @@ class DPVOOdometry:
Args:
checkpoint: DPVO weights (dpvo.pth)
- resize: frames are downscaled by this factor
+ resize: frames are downscaled by this factor, and further if their longer side would
+ still exceed max_side pixels (4K videos: to 960 px, like 1080p ones; DPVO's time grows
+ with the pixels, its rotations do not get better)
+ max_side: see resize
buffer: DPVO frame buffer size
"""
- def __init__(self, checkpoint, resize=0.5, buffer=4000):
- self.checkpoint, self.resize, self.buffer = checkpoint, resize, buffer
+ def __init__(self, checkpoint, resize=0.5, max_side=960, buffer=4000):
+ self.checkpoint, self.resize, self.max_side, self.buffer = (
+ checkpoint, resize, max_side, buffer
+ ) # fmt: skip
- def __call__(self, video_path, K):
- """video and its (3, 3) intrinsics -> (L, 3, 3) world-to-camera rotations (float32)"""
+ def __call__(self, frame_dir, K):
+ """frame_dir with %06d.jpg frames and their (3, 3) intrinsics -> (L, 3, 3) world-to-camera
+ rotations (float32)"""
from dpvo.config import cfg
from dpvo.dpvo import DPVO
intrinsics = torch.stack([K[0, 0], K[1, 1], K[0, 2], K[1, 2]]).float() # fx, fy, cx, cy
- # frames are decoded in a background thread (OpenCV releases the GIL), overlapping with
+ paths = frame_paths(frame_dir)
+ resize = min(self.resize, self.max_side / max(frame_size(frame_dir)))
+ # frames are decoded in background threads (OpenCV releases the GIL), overlapping with
# DPVO on the GPU. A thread rather than a process: importing dpvo switches the
# multiprocessing start method to "spawn" for the whole interpreter.
frames = queue.Queue(maxsize=8)
stop = threading.Event()
reader = threading.Thread(
- target=_dpvo_video_stream,
- args=(frames, stop, str(video_path), intrinsics, self.resize),
+ target=_dpvo_frame_stream,
+ args=(frames, stop, paths, intrinsics, resize),
daemon=True,
)
reader.start()
slam = None
- pbar = tqdm(total=video_lwh(video_path)[0], desc="DPVO")
+ pbar = tqdm(total=len(paths), desc="DPVO")
# no_grad is essential: DPVO writes network outputs into persistent buffers, which
# would otherwise keep every frame's autograd graph alive (memory grows ~0.25 GB/frame)
try:
@@ -228,7 +250,7 @@ def _dpvo_terminate(slam):
return lietorch.stack(poses, dim=0).inv().data.cpu().numpy()
-def _dpvo_video_stream(frames, stop, video_path, intrinsics, resize):
+def _dpvo_frame_stream(frames, stop, paths, intrinsics, resize):
"""Puts (frame index, downscaled BGR frame cropped to multiples of 16, intrinsics) into the
frames queue, then None at the end (or the exception, if reading fails)."""
@@ -240,22 +262,16 @@ def _dpvo_video_stream(frames, stop, video_path, intrinsics, resize):
except queue.Full:
pass
- cap = cv2.VideoCapture(video_path)
try:
- t = 0
- while not stop.is_set():
- ret, frame = cap.read()
- if not ret:
+ for t, frame in enumerate(read_frames(paths)):
+ if stop.is_set():
break
image = cv2.resize(frame, None, fx=resize, fy=resize, interpolation=cv2.INTER_AREA)
h, w, _ = image.shape
put((t, image[: h - h % 16, : w - w % 16], intrinsics * resize))
- t += 1
put(None)
except Exception as error:
put(error)
- finally:
- cap.release()
def _interpolate_poses(T_w2c, sample_idxs):
diff --git a/third_party/ExMR/exmr/vis/render.py b/third_party/ExMR/exmr/vis/render.py
index c859882..786c384 100644
--- a/third_party/ExMR/exmr/vis/render.py
+++ b/third_party/ExMR/exmr/vis/render.py
@@ -1,9 +1,10 @@
"""Result videos: the SMPL-X mesh over the input video (camera view), in the world frame with a
-ground plane (world view), and both side by side."""
+ground plane (world view), and/or both side by side."""
import os
from collections import deque
from concurrent.futures import ThreadPoolExecutor
+from contextlib import ExitStack
from pathlib import Path
import torch
@@ -16,58 +17,100 @@ from exmr.vis.renderer import Renderer, ground_params_from_points, world_view_ca
from exmr.vis.video_writer import VideoWriter
MESH_COLOR = [86.0 / 255.0, 180.0 / 255.0, 233.0 / 255.0] # light blue
+# world view: the mesh's shadow straight down on the ground, which shows its height above it; the
+# ground's brightness in the shadow
+SHADOW_BRIGHTNESS = 0.6
+# the videos: camera view, world view, both side by side
+VIEWS = ("incam", "global", "incam_global")
@torch.no_grad()
def render_videos(frame_dir, verts_incam, verts_global, faces, J_regressor, K, fps, out_paths):
- """Render the camera view, the world view and both side by side in one pass.
+ """Render the camera view, the world view and/or both side by side in one pass.
Args:
frame_dir: the video's frames %06d.jpg
verts_incam: (L, V, 3) mesh vertices in the camera frame, with intrinsics K (3, 3)
verts_global: (L, V, 3) mesh vertices in the world frame
- out_paths: the three videos [camera view, world view, side by side]
+ out_paths: {view: video path} for the views "incam" (camera view), "global" (world view)
+ and "incam_global" (both side by side); only the views needed are rendered
"""
+ if unknown := set(out_paths) - set(VIEWS):
+ raise ValueError(f"unknown views {sorted(unknown)}, expected some of {VIEWS}")
frame_dir = Path(frame_dir)
first = read_frame(frame_dir / "000000.jpg")
# even sizes, for the videos' YUV 4:2:0 format (which stores colors per 2x2 pixels): an odd
# last row or column is left out
height, width = (s // 2 * 2 for s in first.shape[:2])
- incam_renderer = Renderer(width, height, K=K, faces=faces)
- world_renderer, ground, verts_world = _world_view(
- verts_global, faces, J_regressor, width, height
- )
+ incam_renderer = world_renderer = None
+ if out_paths.keys() & {"incam", "incam_global"}:
+ incam_renderer = Renderer(width, height, K=K, faces=faces)
+ frame_paths = [frame_dir / f"{i:06d}.jpg" for i in range(len(verts_incam))]
+ frames = _decoded_frames(frame_paths, height, width)
+ if out_paths.keys() & {"global", "incam_global"}:
+ world_renderer, ground, verts_world, R, T = _world_view(
+ verts_global, faces, J_regressor, width, height
+ )
# write to temporary names, so that an interrupted run leaves no complete-looking videos
- tmp_paths = [Path(p).with_name(Path(p).name + ".tmp.mp4") for p in out_paths]
- # the side-by-side frame is written as is and cropped into the two views
- crops = [(0, 0, width, height), (width, 0, width, height), None]
- writer = VideoWriter(dict(zip(tmp_paths, crops)), fps=fps)
- frame_paths = [frame_dir / f"{i:06d}.jpg" for i in range(len(verts_incam))]
- # decode the JPEGs in background threads, up to 8 frames ahead of rendering
- with ThreadPoolExecutor(4) as pool:
- decoded = deque(pool.submit(read_frame, p) for p in frame_paths[:8])
- for i in tqdm(range(len(frame_paths)), desc="Rendering"):
- frame = torch.from_numpy(decoded.popleft().result()[:height, :width]).cuda()
- if i + 8 < len(frame_paths):
- decoded.append(pool.submit(read_frame, frame_paths[i + 8]))
- incam = incam_renderer.render_mesh(verts_incam[i], frame, MESH_COLOR)
- world = world_renderer.render_mesh(
- verts_world[i], ground, MESH_COLOR, specular_color=(1.0, 1.0, 1.0)
+ tmp_paths = {
+ view: Path(p).with_name(Path(p).name + ".tmp.mp4") for view, p in out_paths.items()
+ }
+ with ExitStack() as stack: # closes every writer, also on errors
+ writers = {
+ view: stack.enter_context(
+ VideoWriter(path, 2 * width if view == "incam_global" else width, height, fps=fps)
)
- writer.write_frame(torch.cat([incam, world], dim=1))
- writer.close()
- for tmp, path in zip(tmp_paths, out_paths):
- os.replace(tmp, path)
+ for view, path in tmp_paths.items()
+ }
+ images = {}
+ for i in tqdm(range(len(verts_incam)), desc="Rendering"):
+ if incam_renderer is not None:
+ images["incam"] = incam_renderer.render_mesh(
+ verts_incam[i], next(frames), MESH_COLOR
+ )
+ if world_renderer is not None:
+ shadow = verts_world[i].clone()
+ shadow[:, 1] = 0.002 # just above the ground
+ # unlit: the flattened mesh's normals point anywhere
+ covered = world_renderer.coverage(shadow @ R.mT + T)
+ background = torch.where(
+ covered, (ground * SHADOW_BRIGHTNESS).to(torch.uint8), ground
+ )
+ images["global"] = world_renderer.render_mesh(
+ verts_world[i] @ R.mT + T,
+ background,
+ MESH_COLOR,
+ specular_color=(1.0, 1.0, 1.0),
+ )
+ if "incam_global" in writers:
+ images["incam_global"] = torch.cat([images["incam"], images["global"]], dim=1)
+ for view, writer in writers.items():
+ writer.write_frame(images[view])
+ for view, path in out_paths.items():
+ os.replace(tmp_paths[view], path)
+
+
+def _decoded_frames(frame_paths, height, width, ahead=8):
+ """The frames, cropped to height x width, on the GPU; decoded in background threads, up to
+ `ahead` frames ahead of their use."""
+ with ThreadPoolExecutor(4) as pool:
+ decoded = deque(pool.submit(read_frame, p) for p in frame_paths[:ahead])
+ for i in range(len(frame_paths)):
+ frame = decoded.popleft().result()[:height, :width]
+ if i + ahead < len(frame_paths):
+ decoded.append(pool.submit(read_frame, frame_paths[i + ahead]))
+ yield torch.from_numpy(frame).cuda()
def _world_view(vertices, faces, J_regressor, width, height):
"""The world view of the world-frame vertices (L, V, 3): a static camera looks from the side
- at the motion, which starts at the origin, facing +z. Returns its renderer, the ground image
- and the vertices in its camera frame.
+ at the motion, which starts at the origin, facing +z. Returns its renderer, the ground image,
+ the vertices moved there and the camera's world-to-camera rotation R and translation T.
As the camera is static, the ground is rendered only once, and each frame renders only the
- mesh over it. The ground never hides the mesh, as the camera and all vertices are above it.
+ mesh's shadow and the mesh over it. The ground never hides the mesh, as the camera is above
+ it and the mesh is drawn over it (also a part dipping below it).
"""
vertices = _move_to_start_point_face_z(vertices, J_regressor)
joints = torch.einsum("jv,lvc->ljc", J_regressor, vertices) # (L, J, 3)
@@ -80,15 +123,16 @@ def _world_view(vertices, faces, J_regressor, width, height):
# the light is at the camera
renderer = Renderer(width, height, K=K, faces=faces, light_location=(0.0, 0.0, 0.0))
ground = renderer.render_ground(R, T, scale * 1.5, cx, cz)
- return renderer, ground, vertices @ R.mT + T
+ return renderer, ground, vertices, R, T
def _move_to_start_point_face_z(verts, J_regressor):
- """Translate verts (L, V, 3) so that the first frame's root is at the origin (xz) and the
- lowest vertex on the ground (y=0), then rotate about y so that the first frame faces +z."""
+ """Translate verts (L, V, 3) so that the first frame's root is at the origin (xz), then
+ rotate about y so that the first frame faces +z. The height stays: the ground (y=0) is the
+ results' (ExMR's world-frame results already start like this)."""
verts = verts.clone()
offset = (J_regressor @ verts[0])[0] # first-frame root joint
- offset[1] = verts[:, :, 1].min()
+ offset[1] = 0
verts = verts - offset
joints = (J_regressor @ verts[0])[None] # (1, J, 3)
diff --git a/third_party/ExMR/exmr/vis/renderer.py b/third_party/ExMR/exmr/vis/renderer.py
index 48f4146..0f41997 100644
--- a/third_party/ExMR/exmr/vis/renderer.py
+++ b/third_party/ExMR/exmr/vis/renderer.py
@@ -46,6 +46,10 @@ class Renderer:
rgb = (AMBIENT + DIFFUSE * cos.clamp(min=0)) * color + SPECULAR * specular
return torch.where(rast[0, ..., 3:] > 0, (rgb * 255).to(torch.uint8), background)
+ def coverage(self, vertices):
+ """Where the mesh (V, 3) in the camera frame covers the image: (H, W, 1) bool."""
+ return self._rasterize(vertices, self.faces)[0, ..., 3:] > 0
+
def render_ground(self, R, T, length, center_x, center_z):
"""A checkerboard ground (side length, center in the xz-plane of the world frame) seen
with the world-to-camera rotation R (3, 3) and translation T (3,), white where there is
diff --git a/third_party/ExMR/exmr/vis/video_writer.py b/third_party/ExMR/exmr/vis/video_writer.py
index 4efab4e..06d4b5f 100644
--- a/third_party/ExMR/exmr/vis/video_writer.py
+++ b/third_party/ExMR/exmr/vis/video_writer.py
@@ -2,16 +2,16 @@
import queue
import subprocess
+import tempfile
import threading
from fractions import Fraction
-import numpy as np
import torch
import torch.nn.functional as F
from exmr.preprocessing.video import h264_args
-# NVENC's H.264 encoder rejects frames wider or taller than this
+# frames wider or taller than this are scaled down: H.264 levels and players top out around 4K
MAX_SIZE = 4096
# RGB -> YUV, BT.601 limited range (ffmpeg's default for yuv420p)
RGB_TO_YUV = torch.tensor(
@@ -24,62 +24,74 @@ RGB_TO_YUV = torch.tensor(
class VideoWriter:
- """Encodes RGB uint8 (H, W, 3) frames (torch tensors, H and W even) into one or more videos,
- each the whole frame or a crop of it, with a single ffmpeg subprocess. A background thread
- feeds it, so write_frame returns immediately and encoding overlaps with rendering. Call
- close() at the end.
+ """Encodes RGB uint8 (H, W, 3) frames (torch tensors) into a video with an ffmpeg subprocess.
+ A background thread feeds it, so write_frame returns immediately and encoding overlaps with
+ rendering. Call close() at the end, or use it as a context manager.
+
+ One video per writer (ffmpeg process) also keeps NVENC to one session per process: several
+ NVENC sessions in one ffmpeg process crash intermittently when they are destroyed at exit
+ (driver-side, seen with driver 610).
Args:
- outputs: {output path: crop (x, y, w, h) of the frame, or None for the whole frame}
+ width, height: the frame size, both even (the video's YUV 4:2:0 format needs it)
"""
- def __init__(self, outputs, fps=30, crf=23, queue_size=8):
- self.outputs, self.fps, self.crf = {str(p): c for p, c in outputs.items()}, fps, crf
- self._proc = None # started with the first frame, which gives the frame size
+ def __init__(self, path, width, height, fps=30, crf=23, queue_size=8):
+ self.path, self.width, self.height = str(path), width, height
+ self._stderr = tempfile.TemporaryFile() # ffmpeg's messages, shown if it fails
+ self._proc = subprocess.Popen(
+ self._command(fps, crf), stdin=subprocess.PIPE, stderr=self._stderr, bufsize=0
+ )
self._queue = queue.Queue(maxsize=queue_size)
self._thread = threading.Thread(target=self._run, daemon=True)
self._thread.start()
def _run(self):
- while (frame := self._queue.get()) is not None:
- if self._proc is None:
- h, w = frame.shape
- self._proc = subprocess.Popen(
- self._command(h * 2 // 3, w), stdin=subprocess.PIPE, bufsize=0
- )
- # write the array's buffer directly: .tobytes() would copy every frame
- self._proc.stdin.write(np.ascontiguousarray(frame, dtype=np.uint8))
- if self._proc is not None:
- self._proc.stdin.close()
- self._proc.wait()
-
- def _command(self, h, w):
- """ffmpeg command: raw h x w YUV 4:2:0 frames from stdin, split into the outputs"""
- n = len(self.outputs)
- graph = [f"[0:v]split={n}" + "".join(f"[in{i}]" for i in range(n))]
- output_args = []
- for i, (path, crop) in enumerate(self.outputs.items()):
- x, y, cw, ch = crop or (0, 0, w, h)
- filters = ([f"crop={cw}:{ch}:{x}:{y}"] if crop else []) + _scale_filter(cw, ch)
- graph.append(f"[in{i}]{','.join(filters) or 'null'}[out{i}]")
- output_args += ["-map", f"[out{i}]", *map(str, h264_args(self.crf)), path]
+ try:
+ while (frame := self._queue.get()) is not None:
+ self._proc.stdin.write(frame) # the array's buffer, without a copy
+ except OSError: # ffmpeg exited (broken pipe): close() reports its error
+ while self._queue.get() is not None: # keep taking frames, so write_frame never blocks
+ pass
+ self._proc.stdin.close()
+ self._proc.wait()
+
+ def _command(self, fps, crf):
+ """ffmpeg command: raw YUV 4:2:0 frames from stdin -> H.264 video"""
+ scale = _scale_filter(self.width, self.height)
return [
"ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
- "-f", "rawvideo", "-pix_fmt", "yuv420p", "-s", f"{w}x{h}",
- "-r", str(Fraction(self.fps).limit_denominator(1000)), "-i", "pipe:0",
- "-filter_complex", ";".join(graph), *output_args,
+ "-f", "rawvideo", "-pix_fmt", "yuv420p", "-s", f"{self.width}x{self.height}",
+ "-r", str(Fraction(fps).limit_denominator(1000)), "-i", "pipe:0",
+ *(["-vf", *scale] if scale else []), *map(str, h264_args(crf)), self.path,
] # fmt: skip
def write_frame(self, frame):
- # converted to YUV 4:2:0 (the videos' format) on the frame's device, e.g. the GPU: this
+ if frame.shape[:2] != (self.height, self.width):
+ raise ValueError(f"frame {tuple(frame.shape)}, expected {self.height}x{self.width}")
+ # converted to YUV 4:2:0 (the video's format) on the frame's device, e.g. the GPU: this
# halves the bytes copied to the CPU and piped to ffmpeg, which limit 4K videos
self._queue.put(_rgb_to_yuv420(frame).cpu().numpy())
def close(self):
self._queue.put(None)
self._thread.join()
- if self._proc is not None and self._proc.returncode != 0:
- raise RuntimeError(f"ffmpeg failed to write {', '.join(self.outputs)}")
+ self._stderr.seek(0)
+ messages = self._stderr.read().decode(errors="replace").strip()
+ self._stderr.close()
+ if self._proc.returncode != 0:
+ raise RuntimeError(
+ f"ffmpeg failed (exit code {self._proc.returncode}) to write {self.path}:\n"
+ f"{messages}"
+ )
+ if messages:
+ print(messages)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ self.close()
def _rgb_to_yuv420(rgb):
diff --git a/third_party/ExMR/pyproject.toml b/third_party/ExMR/pyproject.toml
index 254ea9a..bfc19e7 100644
--- a/third_party/ExMR/pyproject.toml
+++ b/third_party/ExMR/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "exmr"
-version = "0.1.3"
+version = "0.1.5"
description = "ExMR: Extremity Motion Refinement for Monocular Human Motion Capture"
readme = "README.md"
license = { file = "LICENSE" }
diff --git a/third_party/ExMR/requirements.txt b/third_party/ExMR/requirements.txt
index 6679507..508423d 100644
--- a/third_party/ExMR/requirements.txt
+++ b/third_party/ExMR/requirements.txt
@@ -1,5 +1,6 @@
# ExMR, on top of torch 2.8.0 / torchvision 0.23.0 (CUDA 12.8), see docs/INSTALL.md.
-# Versions are those the release was validated with; packages that affect numerics are pinned.
+# All packages are pinned to the versions the release was validated with; constraints.txt pins
+# their dependencies too.
# numerics, video and image IO
numpy==2.3.5
@@ -7,17 +8,17 @@ scipy==1.15.2
opencv-python==4.11.0.86
av==13.0.0
imageio==2.34.1
-PyTurboJPEG
+PyTurboJPEG==2.5.0
safetensors==0.7.0
einops==0.8.1
-tqdm
+tqdm==4.70.1
# SMPL-X
smplx==0.1.28
# person tracking
ultralytics==8.4.83
-lap
+lap==0.5.13
# visual odometry (SimpleVO)
pycolmap==3.11.1
@@ -26,15 +27,15 @@ pycolmap==3.11.1
onnxruntime-gpu==1.24.4
# Sapiens2 keypoints
-pillow
-prettytable
-accelerate
-rich
-termcolor
+pillow==12.3.0
+prettytable==3.18.0
+accelerate==1.15.0
+rich==15.0.0
+termcolor==3.3.0
# HaMeR hand features (installed with --no-deps, see docs/INSTALL.md)
-pytorch-lightning
-omegaconf
+pytorch-lightning==2.6.6
+omegaconf==2.4.0
timm==0.9.12
yacs==0.1.8
pyrender==0.1.45
@@ -43,6 +44,6 @@ trimesh==4.6.5
# SAM 3D Body body features (git submodule)
roma==1.5.6
iopath==0.1.10
-braceexpand
-huggingface_hub
-matplotlib
+braceexpand==0.1.7
+huggingface_hub==2.3.0
+matplotlib==3.11.2
diff --git a/third_party/ExMR/tools/demo.py b/third_party/ExMR/tools/demo.py
index 655020d..e5d6f3b 100644
--- a/third_party/ExMR/tools/demo.py
+++ b/third_party/ExMR/tools/demo.py
@@ -4,6 +4,7 @@
python tools/demo.py --video path/to/video.mp4 -s # static camera
python tools/demo.py --video path/to/video.mp4 --mode fast # fastest
python tools/demo.py --video path/to/video.mp4 --mode accurate # slowest, needs DPVO
+ python tools/demo.py --video path/to/video.mp4 --start 1:05 --end 1:30 # only this part
Modes: person detector, 2D keypoints, camera motion (moving camera)
fast YOLO11m, RTMW-x, SimpleVO
@@ -11,9 +12,10 @@ Modes: person detector, 2D keypoints, camera motion (moving camera)
accurate YOLO11x, Sapiens2-1B 1024x768, DPVO
--detector, --pose_backend, --sapiens2_resolution and --vo override single parts.
-Writes results.pt / results.npz (SMPL-X parameters, see docs/OUTPUTS.md), <video name>_amass.npz
-(the world-frame motion for Blender) and rendered videos to --output_dir (default:
-outputs/<video name>).
+Writes results.pt / results.npz (SMPL-X parameters and joints, see docs/OUTPUTS.md),
+<video name>_amass.npz (the world-frame motion, e.g. for Blender or GMR), <video name>.bvh (the
+same as a BVH skeleton animation) and rendered videos to --output_dir (default:
+outputs/<video name>, with --start/--end outputs/<video name>_<start>-<end>s).
"""
import argparse
@@ -21,7 +23,8 @@ import logging
from pathlib import Path
from exmr.assets import DEFAULT_CHECKPOINT_DIR, Assets
-from exmr.pipeline import Options, run_video
+from exmr.pipeline import Options, range_label, run_video
+from exmr.preprocessing.video import parse_time
PRESETS = {
"fast": dict(detector="yolo11m", pose_backend="rtmw", sapiens2_resolution="448x336",
@@ -48,6 +51,12 @@ def main():
parser.add_argument(
"-s", "--static_cam", action="store_true", help="the camera does not move (skips VO)"
)
+ parser.add_argument(
+ "--start",
+ type=_time,
+ help="only the part of the video from this time on: seconds (83.5) or [hh:]mm:ss (1:23.5)",
+ )
+ parser.add_argument("--end", type=_time, help="... up to this time (default: the video's end)")
parser.add_argument(
"--mode", choices=list(PRESETS), default="balanced", help="speed/accuracy preset"
)
@@ -63,6 +72,13 @@ def main():
choices=["simplevo", "dpvo"],
help="camera motion estimation for a moving camera (DPVO is an optional install)",
)
+ parser.add_argument(
+ "--f_mm",
+ type=float,
+ help="the camera's focal length in mm as for a full-frame camera (35 mm equivalent), if "
+ "known; e.g. phones: about 13 (0.5x lens), 24-26 (1x), 48 (2x), 77 (3x). Default: a 53 "
+ "degree field of view (about 43 mm)",
+ )
parser.add_argument(
"--fps30",
action="store_true",
@@ -77,7 +93,15 @@ def main():
help="assume a single flat ground and nothing to stand on (no stairs, chairs, ...): the "
"body touches the ground at least every 0.5 s, so the world-frame motion is moved "
"vertically to stay on the ground. Removes vertical drift (the person seems to fly or "
- "sink) in long videos; jumps with a longer flight are pulled down.",
+ "sink) in long videos; jumps with a longer flight are pulled down. The demo suggests it "
+ "when the feet end up far above the ground.",
+ )
+ parser.add_argument(
+ "--export_fps",
+ type=float,
+ help="frame rate of the exported motion (<video name>_amass.npz and .bvh), e.g. 24 for "
+ "film or 60 for games: resampled from the video's (rotations interpolated on the "
+ "sphere). Default: the video's frame rate. The other outputs keep the video's frames.",
)
parser.add_argument(
"--smoothing",
@@ -89,8 +113,14 @@ def main():
"_incam video), smoother but following fast foot motion slightly less closely in the "
"image. none: the raw network output.",
)
- parser.add_argument("--no_render", action="store_true", help="only save the results")
- parser.add_argument("--keep_frames", action="store_true", help="keep the extracted frames")
+ parser.add_argument(
+ "--no_render", action="store_true", help="no videos, only the results (needs no nvdiffrast)"
+ )
+ parser.add_argument(
+ "--keep_frames",
+ action="store_true",
+ help="keep the extracted frames (and with --start/--end the cut video)",
+ )
args = parser.parse_args()
# ExMR's progress at INFO; third-party libraries only warnings
@@ -101,6 +131,12 @@ def main():
log.setLevel(logging.INFO)
if not args.video.exists():
parser.error(f"video not found: {args.video}")
+ if args.end is not None and args.end <= (args.start or 0):
+ parser.error("--end must be after --start")
+ if args.f_mm is not None and args.f_mm <= 0:
+ parser.error("--f_mm must be > 0")
+ if args.export_fps is not None and args.export_fps <= 0:
+ parser.error("--export_fps must be > 0")
# the preset, with the explicitly given parts replaced
settings = {k: getattr(args, k) or v for k, v in PRESETS[args.mode].items()}
keypoints = (
@@ -113,22 +149,38 @@ def main():
vo = "static camera"
detector = settings["detector"].replace("yolo", "YOLO")
log.info(f"Mode {args.mode}: {detector}, {keypoints}, {vo}; smoothing: {args.smoothing}")
+ if args.f_mm is not None:
+ log.info(f"Focal length {args.f_mm:g} mm (full-frame equivalent)")
options = Options(
pose_backend=settings["pose_backend"],
sapiens2_resolution=settings["sapiens2_resolution"],
detector=settings["detector"],
static_cam=args.static_cam,
vo=settings["vo"],
+ start=args.start,
+ end=args.end,
+ f_mm=args.f_mm,
fps30=args.fps30,
snap_to_ground=args.snap_to_ground,
+ export_fps=args.export_fps,
smoothing=args.smoothing,
render=not args.no_render,
keep_frames=args.keep_frames,
)
- output_dir = args.output_dir or Path("outputs") / args.video.stem
+ name = args.video.stem
+ if args.start is not None or args.end is not None:
+ name += "_" + range_label(args.start, args.end) # not over the outputs of the whole video
+ output_dir = args.output_dir or Path("outputs") / name
run_video(args.video, output_dir, options, Assets(args.checkpoint_dir))
log.info(f"Done: {output_dir}")
+def _time(text):
+ try:
+ return parse_time(text)
+ except ValueError as e:
+ raise argparse.ArgumentTypeError(str(e)) from None
+
+
if __name__ == "__main__":
main()
diff --git a/third_party/ExMR/tools/download_models.py b/third_party/ExMR/tools/download_models.py
index d1f1aec..24a8610 100644
--- a/third_party/ExMR/tools/download_models.py
+++ b/third_party/ExMR/tools/download_models.py
@@ -48,6 +48,9 @@ DINOV3_COMMIT = "6876159a11b4df116f30f667f8c9888617df0751"
DINOV3_TREE_SHA256 = "0389aafef4614add2090f2907f210698df48f16d3f2b845b6002c4ebb6aea0f8"
YOLO_URL = "https://github.com/ultralytics/assets/releases/download/v8.3.0/{}"
HAMER_URL = "https://www.cs.utexas.edu/~pavlakos/hamer/data/hamer_demo_data.tar.gz"
+# the archive's files that ExMR needs are also in the HaMeR authors' demo Space, which is tried
+# first: 2.7 GB instead of the archive's 6 GB
+HAMER_SPACE, HAMER_SPACE_REVISION = "geopavlakos/HaMeR", "aabc78ee4fd1f1ccf1a55fdd4225bf84df0e680a"
DPVO_URL = (
"https://www.dropbox.com/scl/fo/2g6e134ruh1acmaye5bmy/AK0DY9WLZ25elq-7N7sJcB0/models.zip"
"?rlkey=4j336vcc4h324j4p4ji3ppl0t&dl=1"
@@ -77,8 +80,10 @@ SHA256 = {
"hamer/hamer_ckpts/checkpoints/hamer.ckpt": (
"e5cc06f294d88a92dee24e603480aab04de532b49f0e08200804ee7d90e16f53"
),
+ # the archive's file or the Space's, which differ only in MANO's paths (ExMR sets them itself)
"hamer/hamer_ckpts/model_config.yaml": (
- "0e5eeb82752e47dfd01db8e13ccc4c5eba9bf83f53da8285523b8d3e87247aa3"
+ "0e5eeb82752e47dfd01db8e13ccc4c5eba9bf83f53da8285523b8d3e87247aa3",
+ "2217f6bcf27ae4c074e2a33a3409d822bbfd02931373deedb9f71287adeabe16",
),
"hamer/hamer_ckpts/dataset_config.yaml": (
"392d10aece296152769328f14bb1c0137d6ea2f50f7e69f716ee00e9ad6ac343"
@@ -115,8 +120,11 @@ def sha256_file(path):
def check_sha256(path, expected):
+ """expected: the SHA256, or a tuple of the accepted ones."""
actual = sha256_file(path)
- if actual != expected:
+ accepted = expected if isinstance(expected, tuple) else (expected,)
+ if actual not in accepted:
+ expected = " or ".join(accepted)
raise RuntimeError(
f"Checksum mismatch for {path}:\n expected {expected}\n got {actual}"
)
@@ -155,7 +163,7 @@ class Downloader:
_copy(response, f, total=response.length, desc=rel)
self.place(tmp, rel)
- def hf(self, repo, revision, filename, rel):
+ def hf(self, repo, revision, filename, rel, repo_type="model"):
"""A file of a Hugging Face repo (uses the token of `hf auth login` for gated repos)."""
if not self.todo(rel):
return
@@ -164,7 +172,9 @@ class Downloader:
with tempfile.TemporaryDirectory(dir=self.root) as tmp:
try:
- path = hf_hub_download(repo, filename, revision=revision, local_dir=tmp)
+ path = hf_hub_download(
+ repo, filename, repo_type=repo_type, revision=revision, local_dir=tmp
+ )
except GatedRepoError:
raise RuntimeError(
f"{repo} is gated: request access at https://huggingface.co/{repo}, wait for "
@@ -251,15 +261,23 @@ def _tree_sha256(root):
def fetch_hamer(d, args):
- """HaMeR's demo data: streamed, only the HaMeR checkpoint and MANO mean parameters are kept
- (the archive's 3.8 GB of ViTPose weights are not needed)."""
- members = {
- f"_DATA/{rel.removeprefix('hamer/')}": rel
- for rel in SHA256
- if rel.startswith("hamer/") and d.todo(rel)
- }
- if not members:
- return
+ """The HaMeR checkpoint and MANO mean parameters of HaMeR's demo data: from the HaMeR authors'
+ demo Space, else from the archive."""
+ rels = [rel for rel in SHA256 if rel.startswith("hamer/") and d.todo(rel)]
+ try:
+ for rel in rels:
+ name = f"_DATA/{rel.removeprefix('hamer/')}"
+ d.hf(HAMER_SPACE, HAMER_SPACE_REVISION, name, rel, repo_type="space")
+ except Exception as e:
+ reason = str(e).split("\n", 1)[0] or type(e).__name__
+ print(f" {HAMER_SPACE} failed ({reason}), trying {HAMER_URL}")
+ _fetch_hamer_archive(d, [rel for rel in rels if not (d.root / rel).exists()])
+
+
+def _fetch_hamer_archive(d, rels):
+ """Streamed: only the needed files are kept (the archive's 3.8 GB of ViTPose weights are
+ not needed)."""
+ members = {f"_DATA/{rel.removeprefix('hamer/')}": rel for rel in rels}
with tempfile.TemporaryDirectory(dir=d.root) as tmp, _open(HAMER_URL) as response:
with tqdm(total=response.length, unit="B", unit_scale=True, unit_divisor=1024,
desc="hamer_demo_data.tar.gz", leave=False) as bar: # fmt: skip