diff --git a/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam2.html b/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam2.html new file mode 100644 index 0000000000000000000000000000000000000000..5af1fc3076b476333d0577fd345486772eec8715 --- /dev/null +++ b/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam2.html @@ -0,0 +1,4182 @@ +subject4_h1_7_cam2

subject4_h1_7_cam2

直接读取 v1.1 bundle;预览只作人工核查。手/物体点来自源 3D 标注,仅为显示投影到 RGB;未生成新 UV、分割或接触标注。

帧 0 / 584

原生 RGB(仅预览缩放)
RGB + 原生 3D 关键点投影(仅预览:keypoints_xyz #00e6ff, points_cocoa #ff48a4)
深度 Z,黑=无效,白≥3 m;不改源深度
原深度逐像素 valid:白=有效,黑=无效,不是深度值
原帧号、全部数值标注及有效性
{
+  "frame": {
+    "source_frame_id": 0,
+    "sync_id": "subject4/h1/7:0",
+    "source_locator": {
+      "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+      "member": "subject4/h1/7/cam2/rgb/000000.png",
+      "sha256": "b1cc98bf66c15b1fd672cb9519c7991a2a3ce490e40db8a52b15d8a29b80bd72"
+    },
+    "component_sources": {
+      "hand_pose_mano": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/hand_pose_mano/000000.txt",
+        "sha256": "e5d3c40a8fb81221ae92822aa6c3e73c493825d8a8b320e7dd180c95a6e95710"
+      },
+      "hand_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/hand_pose/000000.txt",
+        "sha256": "ab26f8422dc3642469f67a36f06eaa9e17be289927cb7a252246ef194551a540"
+      },
+      "depth": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/depth/000000.png",
+        "sha256": "cebfef5d05ec2afbe8eab6603760596856bc0be765a417ff68577cd0ea9d546d"
+      },
+      "cam_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/cam_pose/000000.txt",
+        "sha256": "2467e62760c08c6646247552bb3c3aa4c7afeea53184bfc38e728ad7289807bb"
+      },
+      "obj_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/obj_pose/000000.txt",
+        "sha256": "dcd894e4b32fde7d9ab7ec9727f2712ad294319fedc5bbd92ccd8a1925064026"
+      },
+      "obj_pose_rt": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/obj_pose_rt/000000.txt",
+        "sha256": "25e793974b940adadf081d5fb17cd4a86ceb65a42f60b29bcfb574955ea572e6"
+      },
+      "rgb": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/rgb/000000.png",
+        "sha256": "b1cc98bf66c15b1fd672cb9519c7991a2a3ce490e40db8a52b15d8a29b80bd72"
+      }
+    },
+    "annotation_matches": {
+      "hand_pose_mano": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "hand_pose": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "depth": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "cam_pose": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose_rt": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      }
+    },
+    "frame_index": 0,
+    "timestamp_ns": null,
+    "clock_domain": null
+  },
+  "rgb_valid": true,
+  "intrinsic": {
+    "value": [
+      [
+        632.29296875,
+        0.0,
+        640.5956420898438
+      ],
+      [
+        0.0,
+        631.815673828125,
+        367.3528747558594
+      ],
+      [
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "extrinsic": {
+    "value": [
+      [
+        -0.9906443953514099,
+        0.06802894920110703,
+        0.11830098181962967,
+        -0.061109621077775955
+      ],
+      [
+        0.11820145696401596,
+        -0.00550162885338068,
+        0.9929746985435486,
+        -0.2933327853679657
+      ],
+      [
+        0.06820183992385864,
+        0.9976677894592285,
+        -0.0025910395197570324,
+        0.6673370599746704
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "mano": {
+    "value": [
+      [
+        1.4362382888793945,
+        0.9369861483573914,
+        -1.746880292892456,
+        0.004794743377715349,
+        0.1707584261894226,
+        -0.6018233895301819,
+        0.1699988692998886,
+        -0.00020761990163009614,
+        -0.7155240774154663,
+        -0.047670040279626846,
+        0.010327726602554321,
+        -0.1493668556213379,
+        -0.08601675927639008,
+        -0.03311705216765404,
+        -0.8589394092559814,
+        -0.21975138783454895,
+        0.030946308746933937,
+        -0.5646840333938599,
+        -0.005143176298588514,
+        -0.0020604562014341354,
+        -0.3331383466720581,
+        -0.4338557720184326,
+        -0.37572646141052246,
+        -0.5886749625205994,
+        -0.31636539101600647,
+        0.008779612369835377,
+        -0.4466293454170227,
+        -0.07524889707565308,
+        -0.0031842770986258984,
+        -0.23183982074260712,
+        -0.1047976166009903,
+        -0.18011412024497986,
+        -0.6970809698104858,
+        -0.30140432715415955,
+        -0.03360113874077797,
+        -0.5651438236236572,
+        -0.043166544288396835,
+        -0.045574817806482315,
+        -0.4815016984939575,
+        0.8711068034172058,
+        0.3190931975841522,
+        -0.1111631914973259,
+        -0.2661822438240051,
+        0.06150209903717041,
+        0.015476319938898087,
+        0.08050798624753952,
+        -0.06933743506669998,
+        -0.38123515248298645,
+        -0.2806254029273987,
+        1.476506233215332,
+        -0.6854744553565979,
+        0.16803301870822906,
+        -0.18744522333145142,
+        -0.5487542748451233,
+        -2.63431978225708,
+        -0.5607357025146484,
+        -2.1435391902923584,
+        -0.6932340264320374,
+        0.2751154899597168,
+        0.11924334615468979,
+        0.8427309989929199
+      ],
+      [
+        1.35846745967865,
+        -0.7478873133659363,
+        1.5062075853347778,
+        0.039051394909620285,
+        -0.37876221537590027,
+        0.19084596633911133,
+        0.15678124129772186,
+        -0.08973533660173416,
+        0.6323488354682922,
+        -0.03988899290561676,
+        -0.02587687410414219,
+        0.3320583999156952,
+        -0.059423819184303284,
+        -0.21750974655151367,
+        0.7102867364883423,
+        -0.19489334523677826,
+        -0.012446731328964233,
+        0.47452813386917114,
+        0.0021097674034535885,
+        -0.028252437710762024,
+        0.11033516377210617,
+        -0.17313151061534882,
+        0.36597415804862976,
+        0.37573477625846863,
+        -0.3820681869983673,
+        0.00449522165581584,
+        0.591370165348053,
+        -0.055342692881822586,
+        0.03855744004249573,
+        0.3542528748512268,
+        -0.03029007650911808,
+        0.04169467091560364,
+        0.5991495847702026,
+        -0.3130511939525604,
+        0.007519695907831192,
+        0.6511586308479309,
+        -0.008511385880410671,
+        0.030142562463879585,
+        0.3059384822845459,
+        0.6466566324234009,
+        0.019822046160697937,
+        0.19402238726615906,
+        -0.09911049902439117,
+        0.16130289435386658,
+        0.20247028768062592,
+        0.055118627846241,
+        -0.013596867211163044,
+        0.24345824122428894,
+        -0.4555988311767578,
+        0.13637742400169373,
+        0.8111323714256287,
+        -2.9508821964263916,
+        0.06259849667549133,
+        -1.952202320098877,
+        -3.399379253387451,
+        0.6082465648651123,
+        -1.1187307834625244,
+        -0.8084438443183899,
+        -0.3260643184185028,
+        0.09749910235404968,
+        0.7252326607704163
+      ]
+    ],
+    "valid": [
+      true,
+      true
+    ]
+  },
+  "keypoints_xyz": {
+    "value": [
+      [
+        [
+          0.1807723492383957,
+          0.1261885017156601,
+          0.8486074209213257
+        ],
+        [
+          0.1486014425754547,
+          0.11095565557479858,
+          0.8315427303314209
+        ],
+        [
+          0.12442933768033981,
+          0.11028110235929489,
+          0.8115865588188171
+        ],
+        [
+          0.11083708703517914,
+          0.11433202773332596,
+          0.7893268465995789
+        ],
+        [
+          0.08889321982860565,
+          0.12656648457050323,
+          0.769697368144989
+        ],
+        [
+          0.1512289047241211,
+          0.10385231673717499,
+          0.7669911980628967
+        ],
+        [
+          0.1362164169549942,
+          0.11267568171024323,
+          0.7392643094062805
+        ],
+        [
+          0.11971625685691833,
+          0.1269652396440506,
+          0.7370709776878357
+        ],
+        [
+          0.10002540051937103,
+          0.1388963907957077,
+          0.7366706728935242
+        ],
+        [
+          0.1659216731786728,
+          0.1228778064250946,
+          0.7563812136650085
+        ],
+        [
+          0.14584635198116302,
+          0.1374080777168274,
+          0.7359626293182373
+        ],
+        [
+          0.12635886669158936,
+          0.15060856938362122,
+          0.7372148633003235
+        ],
+        [
+          0.10521768778562546,
+          0.1631188839673996,
+          0.7408250570297241
+        ],
+        [
+          0.17655690014362335,
+          0.1460157036781311,
+          0.7657535076141357
+        ],
+        [
+          0.15834712982177734,
+          0.15447653830051422,
+          0.7435747981071472
+        ],
+        [
+          0.1372479349374771,
+          0.16783449053764343,
+          0.7430437803268433
+        ],
+        [
+          0.11537343263626099,
+          0.17886407673358917,
+          0.7463194727897644
+        ],
+        [
+          0.18122713267803192,
+          0.1645311713218689,
+          0.7775169610977173
+        ],
+        [
+          0.16835619509220123,
+          0.17288409173488617,
+          0.7627807259559631
+        ],
+        [
+          0.15109141170978546,
+          0.18092352151870728,
+          0.7592751979827881
+        ],
+        [
+          0.1343732327222824,
+          0.18881119787693024,
+          0.7573028802871704
+        ]
+      ],
+      [
+        [
+          -0.22954224050045013,
+          0.1042974591255188,
+          0.7315999269485474
+        ],
+        [
+          -0.2049480825662613,
+          0.08055157959461212,
+          0.7103165984153748
+        ],
+        [
+          -0.1820819079875946,
+          0.06488832086324692,
+          0.6937956213951111
+        ],
+        [
+          -0.16022926568984985,
+          0.060520801693201065,
+          0.677078902721405
+        ],
+        [
+          -0.12986299395561218,
+          0.06193399056792259,
+          0.6595754623413086
+        ],
+        [
+          -0.22086451947689056,
+          0.06488265842199326,
+          0.6520053148269653
+        ],
+        [
+          -0.22447504103183746,
+          0.06666605919599533,
+          0.6198859810829163
+        ],
+        [
+          -0.21413852274417877,
+          0.07864103466272354,
+          0.6044198870658875
+        ],
+        [
+          -0.19729703664779663,
+          0.08930538594722748,
+          0.5925713181495667
+        ],
+        [
+          -0.23467667400836945,
+          0.0835074707865715,
+          0.6400612592697144
+        ],
+        [
+          -0.22338391840457916,
+          0.09544379264116287,
+          0.610769510269165
+        ],
+        [
+          -0.20475706458091736,
+          0.10727602988481522,
+          0.6005802750587463
+        ],
+        [
+          -0.1829758733510971,
+          0.12152411043643951,
+          0.591772198677063
+        ],
+        [
+          -0.24129237234592438,
+          0.10996384918689728,
+          0.6461287140846252
+        ],
+        [
+          -0.23168018460273743,
+          0.11394853889942169,
+          0.6179399490356445
+        ],
+        [
+          -0.20971587300300598,
+          0.12671013176441193,
+          0.6098947525024414
+        ],
+        [
+          -0.1891503781080246,
+          0.13743409514427185,
+          0.6028714179992676
+        ],
+        [
+          -0.24074123799800873,
+          0.13173824548721313,
+          0.6534515619277954
+        ],
+        [
+          -0.23607446253299713,
+          0.13616076111793518,
+          0.6316583156585693
+        ],
+        [
+          -0.2200271636247635,
+          0.14308780431747437,
+          0.6212643384933472
+        ],
+        [
+          -0.20332062244415283,
+          0.1497931331396103,
+          0.615313708782196
+        ]
+      ]
+    ],
+    "valid": [
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ],
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ]
+    ]
+  },
+  "pose_cocoa": {
+    "value": [
+      [
+        -0.5107280015945435,
+        0.8541058301925659,
+        -0.09828584641218185,
+        -0.14798320829868317
+      ],
+      [
+        0.2798040509223938,
+        0.05703110992908478,
+        -0.9583619236946106,
+        0.1468261480331421
+      ],
+      [
+        -0.8129368424415588,
+        -0.5169629454612732,
+        -0.2681100368499756,
+        0.6410136222839355
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "points_cocoa": {
+    "value": [
+      [
+        -0.14798320829868317,
+        0.1468261480331421,
+        0.6410136222839355
+      ],
+      [
+        -0.13608518242835999,
+        0.09067847579717636,
+        0.5642457604408264
+      ],
+      [
+        -0.09459318965673447,
+        0.06794694811105728,
+        0.6302894353866577
+      ],
+      [
+        -0.0801997035741806,
+        0.20829437673091888,
+        0.6695528626441956
+      ],
+      [
+        -0.12169169634580612,
+        0.23102588951587677,
+        0.6035091280937195
+      ],
+      [
+        -0.21576669812202454,
+        0.0853579118847847,
+        0.6124743819236755
+      ],
+      [
+        -0.17427471280097961,
+        0.06262638419866562,
+        0.6785181164741516
+      ],
+      [
+        -0.15988121926784515,
+        0.20297379791736603,
+        0.7177814841270447
+      ],
+      [
+        -0.20137321949005127,
+        0.2257053256034851,
+        0.6517378091812134
+      ],
+      [
+        -0.11533918231725693,
+        0.07931271195411682,
+        0.5972675681114197
+      ],
+      [
+        -0.19502070546150208,
+        0.07399214804172516,
+        0.6454962491989136
+      ],
+      [
+        -0.1806272268295288,
+        0.21433956921100616,
+        0.6847596764564514
+      ],
+      [
+        -0.10094570368528366,
+        0.21966013312339783,
+        0.6365309953689575
+      ],
+      [
+        -0.17592594027519226,
+        0.08801819384098053,
+        0.588360071182251
+      ],
+      [
+        -0.13443394005298615,
+        0.06528666615486145,
+        0.6544037461280823
+      ],
+      [
+        -0.12004046142101288,
+        0.20563408732414246,
+        0.6936671733856201
+      ],
+      [
+        -0.161532461643219,
+        0.22836561501026154,
+        0.6276234984397888
+      ],
+      [
+        -0.12888844311237335,
+        0.16085219383239746,
+        0.583877444267273
+      ],
+      [
+        -0.08739644289016724,
+        0.13812066614627838,
+        0.6499211192131042
+      ],
+      [
+        -0.1670779585838318,
+        0.13280010223388672,
+        0.6981498003005981
+      ],
+      [
+        -0.2085699588060379,
+        0.1555316299200058,
+        0.6321061253547668
+      ]
+    ],
+    "valid": [
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true
+    ]
+  }
+}

帧 146 / 584

原生 RGB(仅预览缩放)
RGB + 原生 3D 关键点投影(仅预览:keypoints_xyz #00e6ff, points_cocoa #ff48a4)
深度 Z,黑=无效,白≥3 m;不改源深度
原深度逐像素 valid:白=有效,黑=无效,不是深度值
原帧号、全部数值标注及有效性
{
+  "frame": {
+    "source_frame_id": 146,
+    "sync_id": "subject4/h1/7:146",
+    "source_locator": {
+      "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+      "member": "subject4/h1/7/cam2/rgb/000146.png",
+      "sha256": "a05baf34eae5db6ea7c0ccdb673619a170d88f177c8a754ed8f85322b274ae34"
+    },
+    "component_sources": {
+      "hand_pose_mano": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/hand_pose_mano/000146.txt",
+        "sha256": "a533cd3d7841cfbbad8ba6157162fa0bd241d1b06f14309a867503757adfb44f"
+      },
+      "hand_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/hand_pose/000146.txt",
+        "sha256": "e86a1278edb6ff5d6b4acacec659f0c6483b4489457db551c5e66156fec7b100"
+      },
+      "depth": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/depth/000146.png",
+        "sha256": "bd8dc1bac700f23cc8ffdea3d1e1cf038ea5231ac9c1defcaf3022689d41fb76"
+      },
+      "cam_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/cam_pose/000146.txt",
+        "sha256": "2467e62760c08c6646247552bb3c3aa4c7afeea53184bfc38e728ad7289807bb"
+      },
+      "obj_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/obj_pose/000146.txt",
+        "sha256": "b8cd258934d1971d8b7a54f10269393917a970f083e6134f27a9dcf1d5c5c4e1"
+      },
+      "obj_pose_rt": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/obj_pose_rt/000146.txt",
+        "sha256": "3eca271c35a37ffec03787794403b774fb8601d0d9e3a71da4c8a7e1b8ac6c51"
+      },
+      "rgb": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/rgb/000146.png",
+        "sha256": "a05baf34eae5db6ea7c0ccdb673619a170d88f177c8a754ed8f85322b274ae34"
+      }
+    },
+    "annotation_matches": {
+      "hand_pose_mano": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "hand_pose": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "depth": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "cam_pose": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose_rt": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      }
+    },
+    "frame_index": 146,
+    "timestamp_ns": null,
+    "clock_domain": null
+  },
+  "rgb_valid": true,
+  "intrinsic": {
+    "value": [
+      [
+        632.29296875,
+        0.0,
+        640.5956420898438
+      ],
+      [
+        0.0,
+        631.815673828125,
+        367.3528747558594
+      ],
+      [
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "extrinsic": {
+    "value": [
+      [
+        -0.9906443953514099,
+        0.06802894920110703,
+        0.11830098181962967,
+        -0.061109621077775955
+      ],
+      [
+        0.11820145696401596,
+        -0.00550162885338068,
+        0.9929746985435486,
+        -0.2933327853679657
+      ],
+      [
+        0.06820183992385864,
+        0.9976677894592285,
+        -0.0025910395197570324,
+        0.6673370599746704
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "mano": {
+    "value": [
+      [
+        1.6545131206512451,
+        0.8810691833496094,
+        -1.433882474899292,
+        0.04427279531955719,
+        0.26809507608413696,
+        0.045330096036195755,
+        -0.045739151537418365,
+        0.032967399805784225,
+        -0.27929994463920593,
+        0.006416820455342531,
+        0.03520970791578293,
+        -0.30499789118766785,
+        0.00784309022128582,
+        0.14051397144794464,
+        -0.129643052816391,
+        -0.21528618037700653,
+        -0.006156093440949917,
+        -0.46771693229675293,
+        -0.009763075970113277,
+        0.005931627005338669,
+        -0.3510958254337311,
+        -0.1256943643093109,
+        -0.27854663133621216,
+        -0.23620522022247314,
+        -0.23329922556877136,
+        0.02548634447157383,
+        -0.29687410593032837,
+        -0.053570929914712906,
+        -0.020346179604530334,
+        -0.06065757945179939,
+        0.02076874114573002,
+        -0.0008505195728503168,
+        -0.21260634064674377,
+        -0.23882624506950378,
+        0.002423439873382449,
+        -0.34939178824424744,
+        -0.03549252077937126,
+        -0.05985437333583832,
+        -0.3917539715766907,
+        0.8870458602905273,
+        0.05347927659749985,
+        -0.231246680021286,
+        -0.3195331394672394,
+        -0.013767085038125515,
+        0.047401413321495056,
+        0.07033149898052216,
+        -0.007284601218998432,
+        -0.36428308486938477,
+        -0.2806254029273987,
+        1.476506233215332,
+        -0.6854744553565979,
+        0.16803301870822906,
+        -0.18744522333145142,
+        -0.5487542748451233,
+        -2.63431978225708,
+        -0.5607357025146484,
+        -2.1435391902923584,
+        -0.6932340264320374,
+        0.10366678982973099,
+        0.25045138597488403,
+        0.7413784861564636
+      ],
+      [
+        1.5574653148651123,
+        -1.0966535806655884,
+        1.7886207103729248,
+        0.05228615552186966,
+        -0.3141782581806183,
+        0.18577824532985687,
+        0.014561057090759277,
+        -0.0456886850297451,
+        0.27550026774406433,
+        -0.011011692695319653,
+        -0.04303039610385895,
+        0.1838967353105545,
+        -0.01344660110771656,
+        -0.19626811146736145,
+        0.3888801336288452,
+        -0.20499096810817719,
+        -0.013293411582708359,
+        0.3958682715892792,
+        0.003251946996897459,
+        -0.036050885915756226,
+        0.290199875831604,
+        -0.3222946226596832,
+        0.4271879196166992,
+        0.45480868220329285,
+        -0.10017793625593185,
+        -0.05947145074605942,
+        0.2771100103855133,
+        -0.04022855684161186,
+        0.008191186003386974,
+        0.03122820146381855,
+        -0.01720811426639557,
+        0.0541866160929203,
+        0.4702620208263397,
+        -0.23846480250358582,
+        -0.02290438860654831,
+        0.32519856095314026,
+        -0.029706012457609177,
+        0.020899150520563126,
+        0.4011497497558594,
+        1.076732873916626,
+        -0.22445835173130035,
+        0.2684323489665985,
+        -0.34135475754737854,
+        0.16551639139652252,
+        -0.05739152431488037,
+        0.047952648252248764,
+        0.05909768119454384,
+        0.35264596343040466,
+        -0.4555988311767578,
+        0.13637742400169373,
+        0.8111323714256287,
+        -2.9508821964263916,
+        0.06259849667549133,
+        -1.952202320098877,
+        -3.399379253387451,
+        0.6082465648651123,
+        -1.1187307834625244,
+        -0.8084438443183899,
+        -0.2433871328830719,
+        0.18714679777622223,
+        0.7033883333206177
+      ]
+    ],
+    "valid": [
+      true,
+      true
+    ]
+  },
+  "keypoints_xyz": {
+    "value": [
+      [
+        [
+          0.009323665872216225,
+          0.25739654898643494,
+          0.7472549676895142
+        ],
+        [
+          -0.015778889879584312,
+          0.24265159666538239,
+          0.7205967903137207
+        ],
+        [
+          -0.03959148749709129,
+          0.24107857048511505,
+          0.7002625465393066
+        ],
+        [
+          -0.05429646745324135,
+          0.2427244782447815,
+          0.6784060001373291
+        ],
+        [
+          -0.0768171176314354,
+          0.25225630402565,
+          0.6580222845077515
+        ],
+        [
+          0.005494470242410898,
+          0.2411215603351593,
+          0.6592016220092773
+        ],
+        [
+          0.018298998475074768,
+          0.24460993707180023,
+          0.6292703747749329
+        ],
+        [
+          0.01894368603825569,
+          0.2543657720088959,
+          0.6096320152282715
+        ],
+        [
+          0.013575907796621323,
+          0.2634293735027313,
+          0.5889469981193542
+        ],
+        [
+          0.021537791937589645,
+          0.26143190264701843,
+          0.6546714305877686
+        ],
+        [
+          0.02979591116309166,
+          0.27254316210746765,
+          0.6256988644599915
+        ],
+        [
+          0.02177772857248783,
+          0.28496232628822327,
+          0.6073397994041443
+        ],
+        [
+          0.010484211146831512,
+          0.2973717451095581,
+          0.589023232460022
+        ],
+        [
+          0.027786361053586006,
+          0.28401878476142883,
+          0.6683496832847595
+        ],
+        [
+          0.03164341300725937,
+          0.2924484312534332,
+          0.6399043202400208
+        ],
+        [
+          0.02322789840400219,
+          0.30712535977363586,
+          0.6215287446975708
+        ],
+        [
+          0.012401803396642208,
+          0.31969308853149414,
+          0.6031158566474915
+        ],
+        [
+          0.02789771556854248,
+          0.30161118507385254,
+          0.6822603940963745
+        ],
+        [
+          0.028966084122657776,
+          0.31066128611564636,
+          0.6630369424819946
+        ],
+        [
+          0.022517461329698563,
+          0.32116901874542236,
+          0.6481038928031921
+        ],
+        [
+          0.01747428998351097,
+          0.33126869797706604,
+          0.6325629353523254
+        ]
+      ],
+      [
+        [
+          -0.14686506986618042,
+          0.19394515454769135,
+          0.7097555994987488
+        ],
+        [
+          -0.11347191780805588,
+          0.1835993081331253,
+          0.6897661089897156
+        ],
+        [
+          -0.08667974919080734,
+          0.1936729997396469,
+          0.6748716831207275
+        ],
+        [
+          -0.06582126766443253,
+          0.202834814786911,
+          0.6588390469551086
+        ],
+        [
+          -0.037993334233760834,
+          0.22087176144123077,
+          0.6481752395629883
+        ],
+        [
+          -0.11286687105894089,
+          0.18783174455165863,
+          0.6274702548980713
+        ],
+        [
+          -0.10901128500699997,
+          0.1988372504711151,
+          0.5972728729248047
+        ],
+        [
+          -0.10146656632423401,
+          0.21350476145744324,
+          0.5825288891792297
+        ],
+        [
+          -0.08934035152196884,
+          0.2275092601776123,
+          0.5682527422904968
+        ],
+        [
+          -0.1279892772436142,
+          0.20714887976646423,
+          0.6186113357543945
+        ],
+        [
+          -0.12096341699361801,
+          0.22603467106819153,
+          0.5917418003082275
+        ],
+        [
+          -0.10692102462053299,
+          0.2433641403913498,
+          0.5820833444595337
+        ],
+        [
+          -0.08832747489213943,
+          0.26311203837394714,
+          0.578447163105011
+        ],
+        [
+          -0.14185179769992828,
+          0.228260800242424,
+          0.6305545568466187
+        ],
+        [
+          -0.1302398145198822,
+          0.24171558022499084,
+          0.6063262820243835
+        ],
+        [
+          -0.11367538571357727,
+          0.2605394124984741,
+          0.5973097681999207
+        ],
+        [
+          -0.09702586382627487,
+          0.27709487080574036,
+          0.591475248336792
+        ],
+        [
+          -0.1480485051870346,
+          0.245717853307724,
+          0.6441524624824524
+        ],
+        [
+          -0.13690555095672607,
+          0.2578115165233612,
+          0.6284725666046143
+        ],
+        [
+          -0.1227841004729271,
+          0.2697086036205292,
+          0.6199532747268677
+        ],
+        [
+          -0.10897594690322876,
+          0.28114938735961914,
+          0.6100264191627502
+        ]
+      ]
+    ],
+    "valid": [
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ],
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ]
+    ]
+  },
+  "pose_cocoa": {
+    "value": [
+      [
+        -0.5325359106063843,
+        0.8459906578063965,
+        0.02656196430325508,
+        -0.040996234863996506
+      ],
+      [
+        0.28587132692337036,
+        0.20931175351142883,
+        -0.9351291656494141,
+        0.29851582646369934
+      ],
+      [
+        -0.7966698408126831,
+        -0.49039652943611145,
+        -0.3533102869987488,
+        0.6328908801078796
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "points_cocoa": {
+    "value": [
+      [
+        -0.040996234863996506,
+        0.29851582646369934,
+        0.6328908801078796
+      ],
+      [
+        -0.021220924332737923,
+        0.2514190673828125,
+        0.5517844557762146
+      ],
+      [
+        0.022042758762836456,
+        0.22819463908672333,
+        0.6165065765380859
+      ],
+      [
+        0.018152888864278793,
+        0.3651397228240967,
+        0.6682471632957458
+      ],
+      [
+        -0.025110794231295586,
+        0.38836416602134705,
+        0.6035249829292297
+      ],
+      [
+        -0.1001453623175621,
+        0.23189190030097961,
+        0.5975346565246582
+      ],
+      [
+        -0.056881677359342575,
+        0.20866745710372925,
+        0.6622568368911743
+      ],
+      [
+        -0.06077154725790024,
+        0.3456125557422638,
+        0.7139973640441895
+      ],
+      [
+        -0.10403522849082947,
+        0.36883699893951416,
+        0.6492752432823181
+      ],
+      [
+        0.00041091706953011453,
+        0.2398068606853485,
+        0.5841454863548279
+      ],
+      [
+        -0.07851351797580719,
+        0.22027967870235443,
+        0.6298957467079163
+      ],
+      [
+        -0.08240338414907455,
+        0.3572247624397278,
+        0.6816363334655762
+      ],
+      [
+        -0.003478952683508396,
+        0.37675195932388306,
+        0.6358860731124878
+      ],
+      [
+        -0.06068314239382744,
+        0.24165548384189606,
+        0.574659526348114
+      ],
+      [
+        -0.01741945929825306,
+        0.2184310406446457,
+        0.6393817067146301
+      ],
+      [
+        -0.021309329196810722,
+        0.35537612438201904,
+        0.69112229347229
+      ],
+      [
+        -0.0645730122923851,
+        0.3786005675792694,
+        0.6264001131057739
+      ],
+      [
+        -0.023165859282016754,
+        0.31989163160324097,
+        0.5776547193527222
+      ],
+      [
+        0.020097823813557625,
+        0.2966671884059906,
+        0.6423768997192383
+      ],
+      [
+        -0.05882661044597626,
+        0.2771399915218353,
+        0.6881271004676819
+      ],
+      [
+        -0.10209029167890549,
+        0.3003644347190857,
+        0.6234049201011658
+      ]
+    ],
+    "valid": [
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true
+    ]
+  }
+}

帧 292 / 584

原生 RGB(仅预览缩放)
RGB + 原生 3D 关键点投影(仅预览:keypoints_xyz #00e6ff, points_cocoa #ff48a4)
深度 Z,黑=无效,白≥3 m;不改源深度
原深度逐像素 valid:白=有效,黑=无效,不是深度值
原帧号、全部数值标注及有效性
{
+  "frame": {
+    "source_frame_id": 292,
+    "sync_id": "subject4/h1/7:292",
+    "source_locator": {
+      "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+      "member": "subject4/h1/7/cam2/rgb/000292.png",
+      "sha256": "5afac4426fca88dfdc520f8001c8adf56ad5eeb91b0202dc79b903cb2c681a7d"
+    },
+    "component_sources": {
+      "hand_pose_mano": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/hand_pose_mano/000292.txt",
+        "sha256": "561db2664f0b5803ad6d16cda983fc2acbef0ddb40340f10c3c05e01abac754b"
+      },
+      "hand_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/hand_pose/000292.txt",
+        "sha256": "42060df769167b1551f9cb155c794507dd0eb1dd58bd713e990d3619677a4811"
+      },
+      "depth": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/depth/000292.png",
+        "sha256": "ade5d2015c3e02185b2d62207d6a9845a70c7e26f609d5439da4e0096d061c2b"
+      },
+      "cam_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/cam_pose/000292.txt",
+        "sha256": "2467e62760c08c6646247552bb3c3aa4c7afeea53184bfc38e728ad7289807bb"
+      },
+      "obj_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/obj_pose/000292.txt",
+        "sha256": "864ce5c1f1e7dc569f7d88cb29f6fc3eee1cd53f4990590dfcac334537732a61"
+      },
+      "obj_pose_rt": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/obj_pose_rt/000292.txt",
+        "sha256": "8337468e6142be63d89eafb1d4b2cb3d0ffd29e83ffdf6a8f2ca1ac9305c8f01"
+      },
+      "rgb": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/rgb/000292.png",
+        "sha256": "5afac4426fca88dfdc520f8001c8adf56ad5eeb91b0202dc79b903cb2c681a7d"
+      }
+    },
+    "annotation_matches": {
+      "hand_pose_mano": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "hand_pose": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "depth": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "cam_pose": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose_rt": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      }
+    },
+    "frame_index": 292,
+    "timestamp_ns": null,
+    "clock_domain": null
+  },
+  "rgb_valid": true,
+  "intrinsic": {
+    "value": [
+      [
+        632.29296875,
+        0.0,
+        640.5956420898438
+      ],
+      [
+        0.0,
+        631.815673828125,
+        367.3528747558594
+      ],
+      [
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "extrinsic": {
+    "value": [
+      [
+        -0.9906443953514099,
+        0.06802894920110703,
+        0.11830098181962967,
+        -0.061109621077775955
+      ],
+      [
+        0.11820145696401596,
+        -0.00550162885338068,
+        0.9929746985435486,
+        -0.2933327853679657
+      ],
+      [
+        0.06820183992385864,
+        0.9976677894592285,
+        -0.0025910395197570324,
+        0.6673370599746704
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "mano": {
+    "value": [
+      [
+        1.2017014026641846,
+        1.253817081451416,
+        -1.46797513961792,
+        0.05670445039868355,
+        0.25673824548721313,
+        0.05390062928199768,
+        -0.011501568369567394,
+        0.044752590358257294,
+        -0.36865484714508057,
+        0.002329871989786625,
+        0.020953018218278885,
+        -0.4384158253669739,
+        0.004928406327962875,
+        0.16468551754951477,
+        -0.04126213490962982,
+        -0.25341796875,
+        -0.0038572056218981743,
+        -0.6761335134506226,
+        -0.009948598220944405,
+        0.018649278208613396,
+        -0.5019798874855042,
+        -0.24138857424259186,
+        -0.1614977866411209,
+        -0.09372156858444214,
+        0.14770151674747467,
+        0.056116294115781784,
+        -0.12757499516010284,
+        -0.047184936702251434,
+        -0.004884934984147549,
+        0.019028406590223312,
+        -0.022903690114617348,
+        -0.005811681039631367,
+        -0.12458775192499161,
+        -0.23412154614925385,
+        0.01715666800737381,
+        -0.2998145818710327,
+        -0.012882375158369541,
+        -0.04756156727671623,
+        -0.460102379322052,
+        1.1249886751174927,
+        -0.01869778335094452,
+        -0.41282445192337036,
+        -0.20248471200466156,
+        0.02288021706044674,
+        0.024625735357403755,
+        0.07889742404222488,
+        0.02330283634364605,
+        -0.5219765901565552,
+        -0.2806254029273987,
+        1.476506233215332,
+        -0.6854744553565979,
+        0.16803301870822906,
+        -0.18744522333145142,
+        -0.5487542748451233,
+        -2.63431978225708,
+        -0.5607357025146484,
+        -2.1435391902923584,
+        -0.6932340264320374,
+        0.14162121713161469,
+        0.2425588071346283,
+        0.7494577765464783
+      ],
+      [
+        1.8448221683502197,
+        -0.5064380764961243,
+        1.6374545097351074,
+        0.038850054144859314,
+        -0.2796785235404968,
+        0.7232538461685181,
+        0.1962374448776245,
+        0.008065328001976013,
+        0.8089422583580017,
+        -0.03829491138458252,
+        0.013623629696667194,
+        0.3365393280982971,
+        -0.07450265437364578,
+        0.017885863780975342,
+        0.9586271643638611,
+        -0.23017618060112,
+        -0.0407082624733448,
+        0.6756982207298279,
+        -0.011619498021900654,
+        0.004039316903799772,
+        0.5732011795043945,
+        -0.5500652194023132,
+        0.3716382086277008,
+        0.3936295807361603,
+        -0.34403276443481445,
+        0.012122486717998981,
+        0.5724484324455261,
+        -0.08576078712940216,
+        0.04578283056616783,
+        0.45880401134490967,
+        -0.26148533821105957,
+        0.14884883165359497,
+        0.8358225226402283,
+        -0.31061968207359314,
+        0.05572012811899185,
+        0.563292920589447,
+        -0.02641027607023716,
+        0.06818082183599472,
+        0.48979705572128296,
+        1.0069056749343872,
+        -0.3729687035083771,
+        0.10506514459848404,
+        -0.30229654908180237,
+        -0.143685981631279,
+        -0.05555962771177292,
+        0.0849929228425026,
+        -0.059027161449193954,
+        0.37952637672424316,
+        -0.4555988311767578,
+        0.13637742400169373,
+        0.8111323714256287,
+        -2.9508821964263916,
+        0.06259849667549133,
+        -1.952202320098877,
+        -3.399379253387451,
+        0.6082465648651123,
+        -1.1187307834625244,
+        -0.8084438443183899,
+        -0.3580889105796814,
+        0.1733328104019165,
+        0.7622451782226562
+      ]
+    ],
+    "valid": [
+      true,
+      true
+    ]
+  },
+  "keypoints_xyz": {
+    "value": [
+      [
+        [
+          0.04727809131145477,
+          0.2495039701461792,
+          0.7553342580795288
+        ],
+        [
+          0.021873602643609047,
+          0.22533540427684784,
+          0.7372040748596191
+        ],
+        [
+          -0.008536658249795437,
+          0.22094596922397614,
+          0.7309635877609253
+        ],
+        [
+          -0.03201400861144066,
+          0.22338366508483887,
+          0.719151496887207
+        ],
+        [
+          -0.06030053645372391,
+          0.23645399510860443,
+          0.7156529426574707
+        ],
+        [
+          0.022997712716460228,
+          0.22633907198905945,
+          0.6722272634506226
+        ],
+        [
+          0.024505792185664177,
+          0.2311365306377411,
+          0.639874279499054
+        ],
+        [
+          0.014527319930493832,
+          0.23943854868412018,
+          0.6221891641616821
+        ],
+        [
+          -0.0030289816204458475,
+          0.24468596279621124,
+          0.608097493648529
+        ],
+        [
+          0.029103022068738937,
+          0.2504134178161621,
+          0.6636499166488647
+        ],
+        [
+          0.0268265213817358,
+          0.2617422938346863,
+          0.6336910128593445
+        ],
+        [
+          0.008097955025732517,
+          0.26900139451026917,
+          0.6213569045066833
+        ],
+        [
+          -0.014736062847077847,
+          0.27424079179763794,
+          0.6138314604759216
+        ],
+        [
+          0.03114897385239601,
+          0.27475208044052124,
+          0.6754716634750366
+        ],
+        [
+          0.025351347401738167,
+          0.28135573863983154,
+          0.6468734741210938
+        ],
+        [
+          0.009178305976092815,
+          0.2904585599899292,
+          0.6301562786102295
+        ],
+        [
+          -0.009364767000079155,
+          0.2968008816242218,
+          0.6150217056274414
+        ],
+        [
+          0.02947346866130829,
+          0.29237958788871765,
+          0.6892367005348206
+        ],
+        [
+          0.023276157677173615,
+          0.3016936779022217,
+          0.6711416840553284
+        ],
+        [
+          0.016536545008420944,
+          0.31080809235572815,
+          0.655441403388977
+        ],
+        [
+          0.01244429312646389,
+          0.31999996304512024,
+          0.6383844017982483
+        ]
+      ],
+      [
+        [
+          -0.2615668475627899,
+          0.18013116717338562,
+          0.7686124444007874
+        ],
+        [
+          -0.23469224572181702,
+          0.17198437452316284,
+          0.7397488951683044
+        ],
+        [
+          -0.222685307264328,
+          0.1788787692785263,
+          0.710603654384613
+        ],
+        [
+          -0.22440795600414276,
+          0.18375012278556824,
+          0.6832291483879089
+        ],
+        [
+          -0.22600781917572021,
+          0.20168179273605347,
+          0.6535996198654175
+        ],
+        [
+          -0.255031943321228,
+          0.1588570475578308,
+          0.6821900010108948
+        ],
+        [
+          -0.25210076570510864,
+          0.17344240844249725,
+          0.6534403562545776
+        ],
+        [
+          -0.24178916215896606,
+          0.19282501935958862,
+          0.6507146954536438
+        ],
+        [
+          -0.2262730598449707,
+          0.2096729427576065,
+          0.6537327766418457
+        ],
+        [
+          -0.27718836069107056,
+          0.17130984365940094,
+          0.6763299107551575
+        ],
+        [
+          -0.267449289560318,
+          0.1908324807882309,
+          0.6507951021194458
+        ],
+        [
+          -0.2524266541004181,
+          0.20992909371852875,
+          0.6501443386077881
+        ],
+        [
+          -0.23552732169628143,
+          0.22616848349571228,
+          0.6637943983078003
+        ],
+        [
+          -0.29218700528144836,
+          0.1914631426334381,
+          0.6885531544685364
+        ],
+        [
+          -0.2822355329990387,
+          0.20459528267383575,
+          0.6634255647659302
+        ],
+        [
+          -0.2628486156463623,
+          0.22225119173526764,
+          0.6586892008781433
+        ],
+        [
+          -0.2432491034269333,
+          0.23614977300167084,
+          0.6586111187934875
+        ],
+        [
+          -0.29866912961006165,
+          0.21027275919914246,
+          0.7000523209571838
+        ],
+        [
+          -0.29606181383132935,
+          0.21992242336273193,
+          0.6796472668647766
+        ],
+        [
+          -0.2817822992801666,
+          0.23026636242866516,
+          0.6695164442062378
+        ],
+        [
+          -0.2659330368041992,
+          0.23940667510032654,
+          0.665621817111969
+        ]
+      ]
+    ],
+    "valid": [
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ],
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ]
+    ]
+  },
+  "pose_cocoa": {
+    "value": [
+      [
+        -0.9067906737327576,
+        0.41074609756469727,
+        -0.09496521204710007,
+        -0.03369191661477089
+      ],
+      [
+        0.23574334383010864,
+        0.307285875082016,
+        -0.9219549298286438,
+        0.2742753326892853
+      ],
+      [
+        -0.3495076894760132,
+        -0.8584073781967163,
+        -0.3754742443561554,
+        0.6750916838645935
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "points_cocoa": {
+    "value": [
+      [
+        -0.03369191661477089,
+        0.2742753326892853,
+        0.6750916838645935
+      ],
+      [
+        -0.05832001939415932,
+        0.23067715764045715,
+        0.5933598875999451
+      ],
+      [
+        0.015348452143371105,
+        0.21152515709400177,
+        0.6217542290687561
+      ],
+      [
+        0.029255643486976624,
+        0.3465409576892853,
+        0.6767405867576599
+      ],
+      [
+        -0.04441282898187637,
+        0.36569294333457947,
+        0.6483462452888489
+      ],
+      [
+        -0.0966394767165184,
+        0.20200973749160767,
+        0.6734427213668823
+      ],
+      [
+        -0.022971007972955704,
+        0.18285775184631348,
+        0.7018370628356934
+      ],
+      [
+        -0.009063816629350185,
+        0.3178735375404358,
+        0.7568234205245972
+      ],
+      [
+        -0.08273229002952576,
+        0.33702552318573,
+        0.7284290790557861
+      ],
+      [
+        -0.02148578315973282,
+        0.22110116481781006,
+        0.6075570583343506
+      ],
+      [
+        -0.0598052442073822,
+        0.19243374466896057,
+        0.6876398921012878
+      ],
+      [
+        -0.04589805379509926,
+        0.3274495303630829,
+        0.7426262497901917
+      ],
+      [
+        -0.007578592747449875,
+        0.3561169505119324,
+        0.6625434160232544
+      ],
+      [
+        -0.07747974991798401,
+        0.2163434475660324,
+        0.6334013342857361
+      ],
+      [
+        -0.0038112779147922993,
+        0.19719144701957703,
+        0.6617956161499023
+      ],
+      [
+        0.010095912963151932,
+        0.33220723271369934,
+        0.7167819738388062
+      ],
+      [
+        -0.06357255578041077,
+        0.3513592481613159,
+        0.6883876919746399
+      ],
+      [
+        -0.051366422325372696,
+        0.2981850504875183,
+        0.620853066444397
+      ],
+      [
+        0.02230204828083515,
+        0.2790330648422241,
+        0.649247407913208
+      ],
+      [
+        -0.016017412766814232,
+        0.25036564469337463,
+        0.7293302416801453
+      ],
+      [
+        -0.08968588709831238,
+        0.2695176303386688,
+        0.7009359002113342
+      ]
+    ],
+    "valid": [
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true
+    ]
+  }
+}

帧 438 / 584

原生 RGB(仅预览缩放)
RGB + 原生 3D 关键点投影(仅预览:keypoints_xyz #00e6ff, points_cocoa #ff48a4)
深度 Z,黑=无效,白≥3 m;不改源深度
原深度逐像素 valid:白=有效,黑=无效,不是深度值
原帧号、全部数值标注及有效性
{
+  "frame": {
+    "source_frame_id": 438,
+    "sync_id": "subject4/h1/7:438",
+    "source_locator": {
+      "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+      "member": "subject4/h1/7/cam2/rgb/000438.png",
+      "sha256": "7c07a582b274f51bc8c00bd6a702344dbd06a4dc1eb06c2f40b4ce779571cbd9"
+    },
+    "component_sources": {
+      "hand_pose_mano": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/hand_pose_mano/000438.txt",
+        "sha256": "be8a937322d91061c3bfacd9459b9986ef61ca8860a83cb7f027b0e073d8be68"
+      },
+      "hand_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/hand_pose/000438.txt",
+        "sha256": "2baf5ef27a943097e6dffaffe8a22447312a6a8c9c964c92925dc3e1aee1e3a7"
+      },
+      "depth": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/depth/000438.png",
+        "sha256": "f6ef44451d5f7b904358620c96e961aae617ba3ac57d7d74c05553095c4ca81f"
+      },
+      "cam_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/cam_pose/000438.txt",
+        "sha256": "2467e62760c08c6646247552bb3c3aa4c7afeea53184bfc38e728ad7289807bb"
+      },
+      "obj_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/obj_pose/000438.txt",
+        "sha256": "869a0fc6110e949ad21f07f79b9e724476fc063ce53b4b2c7c46474f0c9ab762"
+      },
+      "obj_pose_rt": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/obj_pose_rt/000438.txt",
+        "sha256": "1e060e91b5b25d9888eb1af5258ef5edd50a0c2808230eb1edf6bf1778b5f46d"
+      },
+      "rgb": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/rgb/000438.png",
+        "sha256": "7c07a582b274f51bc8c00bd6a702344dbd06a4dc1eb06c2f40b4ce779571cbd9"
+      }
+    },
+    "annotation_matches": {
+      "hand_pose_mano": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "hand_pose": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "depth": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "cam_pose": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose_rt": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      }
+    },
+    "frame_index": 438,
+    "timestamp_ns": null,
+    "clock_domain": null
+  },
+  "rgb_valid": true,
+  "intrinsic": {
+    "value": [
+      [
+        632.29296875,
+        0.0,
+        640.5956420898438
+      ],
+      [
+        0.0,
+        631.815673828125,
+        367.3528747558594
+      ],
+      [
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "extrinsic": {
+    "value": [
+      [
+        -0.9906443953514099,
+        0.06802894920110703,
+        0.11830098181962967,
+        -0.061109621077775955
+      ],
+      [
+        0.11820145696401596,
+        -0.00550162885338068,
+        0.9929746985435486,
+        -0.2933327853679657
+      ],
+      [
+        0.06820183992385864,
+        0.9976677894592285,
+        -0.0025910395197570324,
+        0.6673370599746704
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "mano": {
+    "value": [
+      [
+        1.153676986694336,
+        1.5796537399291992,
+        -1.6015673875808716,
+        0.0441138930618763,
+        0.31131309270858765,
+        -0.00626513222232461,
+        -0.02036752924323082,
+        0.0451199971139431,
+        -0.34308093786239624,
+        -0.0009102236945182085,
+        0.02689209207892418,
+        -0.3802049458026886,
+        -0.015653541311621666,
+        0.17522288858890533,
+        -0.151083305478096,
+        -0.26585128903388977,
+        -0.005229040049016476,
+        -0.7646550536155701,
+        -0.02005547657608986,
+        0.021737094968557358,
+        -0.5219047665596008,
+        -0.16009902954101562,
+        -0.27070680260658264,
+        -0.22880232334136963,
+        -0.21499472856521606,
+        0.005724928807467222,
+        -0.30150121450424194,
+        -0.050526686012744904,
+        -0.038071416318416595,
+        -0.0952521562576294,
+        -0.03314047306776047,
+        -0.048541996628046036,
+        -0.22275325655937195,
+        -0.29545819759368896,
+        -0.0030866072047501802,
+        -0.5464324951171875,
+        -0.030524782836437225,
+        -0.06140469014644623,
+        -0.5275866389274597,
+        0.9019661545753479,
+        -0.023597352206707,
+        -0.28409048914909363,
+        -0.2718367874622345,
+        -0.13753437995910645,
+        -0.011629355140030384,
+        0.0581522062420845,
+        -0.013459517620503902,
+        -0.34280645847320557,
+        -0.2806254029273987,
+        1.476506233215332,
+        -0.6854744553565979,
+        0.16803301870822906,
+        -0.18744522333145142,
+        -0.5487542748451233,
+        -2.63431978225708,
+        -0.5607357025146484,
+        -2.1435391902923584,
+        -0.6932340264320374,
+        0.1924525946378708,
+        0.18643872439861298,
+        0.7524847984313965
+      ],
+      [
+        -2.1714251041412354,
+        0.6081082820892334,
+        -1.8078553676605225,
+        -0.010575031861662865,
+        -0.24173542857170105,
+        0.697502851486206,
+        0.20180197060108185,
+        0.0415135994553566,
+        0.4217185378074646,
+        -0.025461535900831223,
+        0.020387917757034302,
+        -0.013804709538817406,
+        -0.1217774748802185,
+        0.07403827458620071,
+        1.1567624807357788,
+        -0.20310288667678833,
+        0.00981416366994381,
+        0.3319188356399536,
+        -0.01451727282255888,
+        0.004075824748724699,
+        0.35964834690093994,
+        -0.7797415256500244,
+        0.6071902513504028,
+        0.8347394466400146,
+        -0.33239734172821045,
+        0.005324136465787888,
+        0.5375992059707642,
+        -0.056371986865997314,
+        0.008091513998806477,
+        0.37781718373298645,
+        -0.2753085494041443,
+        0.3322887122631073,
+        1.052750587463379,
+        -0.32745134830474854,
+        0.0330868624150753,
+        0.6154453158378601,
+        -0.03810780122876167,
+        0.03570462018251419,
+        0.6540924906730652,
+        0.8452440500259399,
+        -0.190989688038826,
+        0.08434190601110458,
+        -0.332694947719574,
+        0.25225186347961426,
+        -0.028766237199306488,
+        0.0437852218747139,
+        -0.002592346863821149,
+        0.3574236035346985,
+        -0.4555988311767578,
+        0.13637742400169373,
+        0.8111323714256287,
+        -2.9508821964263916,
+        0.06259849667549133,
+        -1.952202320098877,
+        -3.399379253387451,
+        0.6082465648651123,
+        -1.1187307834625244,
+        -0.8084438443183899,
+        -0.30785971879959106,
+        0.23042257130146027,
+        0.7329102158546448
+      ]
+    ],
+    "valid": [
+      true,
+      true
+    ]
+  },
+  "keypoints_xyz": {
+    "value": [
+      [
+        [
+          0.09810946881771088,
+          0.19338387250900269,
+          0.758361279964447
+        ],
+        [
+          0.06787155568599701,
+          0.17252105474472046,
+          0.7439174652099609
+        ],
+        [
+          0.03821507841348648,
+          0.16292820870876312,
+          0.7405314445495605
+        ],
+        [
+          0.012601638212800026,
+          0.1591370850801468,
+          0.7354096174240112
+        ],
+        [
+          -0.01918838359415531,
+          0.15914127230644226,
+          0.7381255626678467
+        ],
+        [
+          0.051894087344408035,
+          0.18455664813518524,
+          0.682077944278717
+        ],
+        [
+          0.043679364025592804,
+          0.19682687520980835,
+          0.6528552770614624
+        ],
+        [
+          0.029552128165960312,
+          0.2088049352169037,
+          0.641099214553833
+        ],
+        [
+          0.009609466418623924,
+          0.21727968752384186,
+          0.6329612731933594
+        ],
+        [
+          0.05649656057357788,
+          0.20976848900318146,
+          0.6762815117835999
+        ],
+        [
+          0.043866321444511414,
+          0.22670185565948486,
+          0.6520987749099731
+        ],
+        [
+          0.02169405110180378,
+          0.23462040722370148,
+          0.6509717702865601
+        ],
+        [
+          -0.0019799538422375917,
+          0.23901085555553436,
+          0.6558687686920166
+        ],
+        [
+          0.06256590783596039,
+          0.2317543923854828,
+          0.6909816265106201
+        ],
+        [
+          0.046926841139793396,
+          0.24213969707489014,
+          0.6676869988441467
+        ],
+        [
+          0.02375091426074505,
+          0.25106626749038696,
+          0.6650250554084778
+        ],
+        [
+          -0.00038876800681464374,
+          0.25587424635887146,
+          0.665995717048645
+        ],
+        [
+          0.06528779864311218,
+          0.24677802622318268,
+          0.7074100971221924
+        ],
+        [
+          0.053060438483953476,
+          0.25723129510879517,
+          0.693488597869873
+        ],
+        [
+          0.036758553236722946,
+          0.2652674913406372,
+          0.6868056654930115
+        ],
+        [
+          0.021176235750317574,
+          0.2730497717857361,
+          0.6792084574699402
+        ]
+      ],
+      [
+        [
+          -0.21133767068386078,
+          0.23722092807292938,
+          0.7392774820327759
+        ],
+        [
+          -0.18609194457530975,
+          0.2617794871330261,
+          0.71975177526474
+        ],
+        [
+          -0.1740514487028122,
+          0.28749167919158936,
+          0.7044204473495483
+        ],
+        [
+          -0.16466976702213287,
+          0.3095432221889496,
+          0.6902156472206116
+        ],
+        [
+          -0.15597552061080933,
+          0.3422463834285736,
+          0.6820964813232422
+        ],
+        [
+          -0.20038816332817078,
+          0.28015556931495667,
+          0.6618122458457947
+        ],
+        [
+          -0.20607605576515198,
+          0.3084920644760132,
+          0.6472327709197998
+        ],
+        [
+          -0.20822732150554657,
+          0.3303232491016388,
+          0.6500990986824036
+        ],
+        [
+          -0.20598269999027252,
+          0.3534921407699585,
+          0.6507530212402344
+        ],
+        [
+          -0.22611813247203827,
+          0.2820793390274048,
+          0.657992959022522
+        ],
+        [
+          -0.22586876153945923,
+          0.315662682056427,
+          0.6576616764068604
+        ],
+        [
+          -0.22195477783679962,
+          0.33695316314697266,
+          0.6687151193618774
+        ],
+        [
+          -0.21505525708198547,
+          0.3548396825790405,
+          0.6881910562515259
+        ],
+        [
+          -0.24855734407901764,
+          0.2808801829814911,
+          0.6745930910110474
+        ],
+        [
+          -0.24205806851387024,
+          0.3098652958869934,
+          0.6700652241706848
+        ],
+        [
+          -0.2332676500082016,
+          0.32817092537879944,
+          0.6873176693916321
+        ],
+        [
+          -0.2241857498884201,
+          0.3374362289905548,
+          0.7074275612831116
+        ],
+        [
+          -0.2630871534347534,
+          0.28302010893821716,
+          0.6922666430473328
+        ],
+        [
+          -0.2572261691093445,
+          0.3047783672809601,
+          0.6893494725227356
+        ],
+        [
+          -0.24550622701644897,
+          0.31905198097229004,
+          0.6978607177734375
+        ],
+        [
+          -0.23418673872947693,
+          0.3294203579425812,
+          0.7091372013092041
+        ]
+      ]
+    ],
+    "valid": [
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ],
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ]
+    ]
+  },
+  "pose_cocoa": {
+    "value": [
+      [
+        -0.9786447882652283,
+        0.04291479289531708,
+        -0.20102936029434204,
+        -0.003596911672502756
+      ],
+      [
+        0.1816113293170929,
+        0.638617753982544,
+        -0.7477867603302002,
+        0.210251122713089
+      ],
+      [
+        0.09628993272781372,
+        -0.7683266997337341,
+        -0.6327733993530273,
+        0.7047473788261414
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "points_cocoa": {
+    "value": [
+      [
+        -0.003596911672502756,
+        0.210251122713089,
+        0.7047473788261414
+      ],
+      [
+        -0.05606796592473984,
+        0.19266247749328613,
+        0.6264859437942505
+      ],
+      [
+        0.023437997326254845,
+        0.17790821194648743,
+        0.6186633110046387
+      ],
+      [
+        0.0528777614235878,
+        0.2874179184436798,
+        0.7113298773765564
+      ],
+      [
+        -0.026628199964761734,
+        0.3021721839904785,
+        0.7191525101661682
+      ],
+      [
+        -0.060071587562561035,
+        0.13308434188365936,
+        0.6981649398803711
+      ],
+      [
+        0.019434375688433647,
+        0.11833006888628006,
+        0.6903422474861145
+      ],
+      [
+        0.0488741435110569,
+        0.22783978283405304,
+        0.7830088138580322
+      ],
+      [
+        -0.030631819739937782,
+        0.24259404838085175,
+        0.7908315062522888
+      ],
+      [
+        -0.01631498523056507,
+        0.18528534471988678,
+        0.6225746273994446
+      ],
+      [
+        -0.02031860500574112,
+        0.12570720911026,
+        0.6942536234855652
+      ],
+      [
+        0.009121160954236984,
+        0.2352169156074524,
+        0.7869201898574829
+      ],
+      [
+        0.013124781660735607,
+        0.29479506611824036,
+        0.7152411937713623
+      ],
+      [
+        -0.058069776743650436,
+        0.16287340223789215,
+        0.6623254418373108
+      ],
+      [
+        0.021436186507344246,
+        0.14811913669109344,
+        0.6545027494430542
+      ],
+      [
+        0.0508759543299675,
+        0.257628858089447,
+        0.7471693158149719
+      ],
+      [
+        -0.028630008921027184,
+        0.2723831236362457,
+        0.7549920082092285
+      ],
+      [
+        -0.04134808108210564,
+        0.24741733074188232,
+        0.6728192567825317
+      ],
+      [
+        0.038157880306243896,
+        0.23266306519508362,
+        0.6649965643882751
+      ],
+      [
+        0.0341542586684227,
+        0.17308492958545685,
+        0.7366755604743958
+      ],
+      [
+        -0.045351702719926834,
+        0.18783919513225555,
+        0.7444982528686523
+      ]
+    ],
+    "valid": [
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true
+    ]
+  }
+}

帧 583 / 584

原生 RGB(仅预览缩放)
RGB + 原生 3D 关键点投影(仅预览:keypoints_xyz #00e6ff, points_cocoa #ff48a4)
深度 Z,黑=无效,白≥3 m;不改源深度
原深度逐像素 valid:白=有效,黑=无效,不是深度值
原帧号、全部数值标注及有效性
{
+  "frame": {
+    "source_frame_id": 583,
+    "sync_id": "subject4/h1/7:583",
+    "source_locator": {
+      "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+      "member": "subject4/h1/7/cam2/rgb/000583.png",
+      "sha256": "7c07bbf9570a8dd91483fe6259aed9a58f164aba4e2aba78f506c0fa91add110"
+    },
+    "component_sources": {
+      "hand_pose_mano": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/hand_pose_mano/000583.txt",
+        "sha256": "42c2c595da0118a2e24332f26bfcff11838bba5a18b7e9356e9391e01316844e"
+      },
+      "hand_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/hand_pose/000583.txt",
+        "sha256": "ad04ed61285af5f86490163cc04346df81aa9614d17466c79485bd35a0446948"
+      },
+      "depth": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/depth/000583.png",
+        "sha256": "a23ab9e0f4c08ac223dde71dcd579f100c182b0a1fa07b69b22bde3884dc2a95"
+      },
+      "cam_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/cam_pose/000583.txt",
+        "sha256": "2467e62760c08c6646247552bb3c3aa4c7afeea53184bfc38e728ad7289807bb"
+      },
+      "obj_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/obj_pose/000583.txt",
+        "sha256": "f6c2a383b80958ad54dc8f7e0d33ecd09223110f2a036a74a1f870c527af8485"
+      },
+      "obj_pose_rt": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/obj_pose_rt/000583.txt",
+        "sha256": "5a46ab46c6af5e8dc6266f93c5ae5feb8f452d2141e90cd309f54dda99733cf6"
+      },
+      "rgb": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/rgb/000583.png",
+        "sha256": "7c07bbf9570a8dd91483fe6259aed9a58f164aba4e2aba78f506c0fa91add110"
+      }
+    },
+    "annotation_matches": {
+      "hand_pose_mano": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "hand_pose": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "depth": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "cam_pose": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose_rt": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      }
+    },
+    "frame_index": 583,
+    "timestamp_ns": null,
+    "clock_domain": null
+  },
+  "rgb_valid": true,
+  "intrinsic": {
+    "value": [
+      [
+        632.29296875,
+        0.0,
+        640.5956420898438
+      ],
+      [
+        0.0,
+        631.815673828125,
+        367.3528747558594
+      ],
+      [
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "extrinsic": {
+    "value": [
+      [
+        -0.9906443953514099,
+        0.06802894920110703,
+        0.11830098181962967,
+        -0.061109621077775955
+      ],
+      [
+        0.11820145696401596,
+        -0.00550162885338068,
+        0.9929746985435486,
+        -0.2933327853679657
+      ],
+      [
+        0.06820183992385864,
+        0.9976677894592285,
+        -0.0025910395197570324,
+        0.6673370599746704
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "mano": {
+    "value": [
+      [
+        1.2591043710708618,
+        1.0793436765670776,
+        -1.5103720426559448,
+        0.03340994939208031,
+        0.3228056728839874,
+        -0.07821039110422134,
+        0.00736130028963089,
+        0.044860951602458954,
+        -0.34319353103637695,
+        -0.0073201400227844715,
+        0.029256504029035568,
+        -0.2064988762140274,
+        -0.027639465406537056,
+        0.14684435725212097,
+        -0.37501099705696106,
+        -0.20725110173225403,
+        0.003951873164623976,
+        -0.45073044300079346,
+        -0.012203204445540905,
+        0.014346623793244362,
+        -0.27812620997428894,
+        -0.18587090075016022,
+        -0.2580273449420929,
+        -0.4124998152256012,
+        -0.3137627840042114,
+        0.006992853246629238,
+        -0.35082560777664185,
+        -0.045118238776922226,
+        -0.05261789634823799,
+        -0.16788744926452637,
+        -0.003028573701158166,
+        -0.08499280363321304,
+        -0.46834662556648254,
+        -0.24806950986385345,
+        0.0007639554096385837,
+        -0.23950041830539703,
+        -0.024439869448542595,
+        -0.04982245713472366,
+        -0.2905237078666687,
+        0.7547170519828796,
+        -0.04532362520694733,
+        -0.17603327333927155,
+        -0.32395726442337036,
+        -0.21300753951072693,
+        0.0027177261654287577,
+        0.04898405075073242,
+        0.0004385107895359397,
+        -0.2091580480337143,
+        -0.2806254029273987,
+        1.476506233215332,
+        -0.6854744553565979,
+        0.16803301870822906,
+        -0.18744522333145142,
+        -0.5487542748451233,
+        -2.63431978225708,
+        -0.5607357025146484,
+        -2.1435391902923584,
+        -0.6932340264320374,
+        0.1728573888540268,
+        0.11192719638347626,
+        0.8060998916625977
+      ],
+      [
+        0.979651927947998,
+        -1.1701430082321167,
+        1.3650344610214233,
+        0.035671260207891464,
+        -0.23242047429084778,
+        0.9175093173980713,
+        0.194064661860466,
+        -0.05034683272242546,
+        0.22226956486701965,
+        -0.04774567112326622,
+        -0.05082094669342041,
+        -0.05479954183101654,
+        -0.026752272620797157,
+        -0.05637355521321297,
+        1.0516794919967651,
+        -0.17926554381847382,
+        -0.017618492245674133,
+        0.14412200450897217,
+        0.011402745731174946,
+        0.000925535277929157,
+        0.04662485048174858,
+        -0.48833101987838745,
+        0.37762975692749023,
+        0.5960181355476379,
+        -0.13645552098751068,
+        -0.03331734985113144,
+        0.3506031930446625,
+        -0.06388898938894272,
+        -0.019688155502080917,
+        0.05134721100330353,
+        -0.12143892049789429,
+        0.09756811708211899,
+        0.8241648077964783,
+        -0.23145286738872528,
+        0.017975086346268654,
+        0.3451057970523834,
+        -0.025740794837474823,
+        0.021148517727851868,
+        0.2646710276603699,
+        1.092269778251648,
+        -0.44799330830574036,
+        0.15289244055747986,
+        -0.30898961424827576,
+        -0.09629514813423157,
+        -0.03233122080564499,
+        0.0844181478023529,
+        0.041561249643564224,
+        0.3536794185638428,
+        -0.4555988311767578,
+        0.13637742400169373,
+        0.8111323714256287,
+        -2.9508821964263916,
+        0.06259849667549133,
+        -1.952202320098877,
+        -3.399379253387451,
+        0.6082465648651123,
+        -1.1187307834625244,
+        -0.8084438443183899,
+        -0.2351813018321991,
+        0.13347721099853516,
+        0.8125974535942078
+      ]
+    ],
+    "valid": [
+      true,
+      true
+    ]
+  },
+  "keypoints_xyz": {
+    "value": [
+      [
+        [
+          0.07851426303386688,
+          0.11887234449386597,
+          0.8119763731956482
+        ],
+        [
+          0.05239542946219444,
+          0.09542103856801987,
+          0.7939193844795227
+        ],
+        [
+          0.027227099984884262,
+          0.08090458810329437,
+          0.7821370959281921
+        ],
+        [
+          0.006260219495743513,
+          0.07021140307188034,
+          0.7701913714408875
+        ],
+        [
+          -0.02275734767317772,
+          0.06137097626924515,
+          0.7591234445571899
+        ],
+        [
+          0.05857623741030693,
+          0.09021136909723282,
+          0.7294297218322754
+        ],
+        [
+          0.05944342166185379,
+          0.09513111412525177,
+          0.6970715522766113
+        ],
+        [
+          0.0500611774623394,
+          0.10423710197210312,
+          0.6794559359550476
+        ],
+        [
+          0.03677850589156151,
+          0.11090701073408127,
+          0.6616442799568176
+        ],
+        [
+          0.06757337599992752,
+          0.11274659633636475,
+          0.7193483710289001
+        ],
+        [
+          0.058574989438056946,
+          0.12341232597827911,
+          0.6904289126396179
+        ],
+        [
+          0.04043975844979286,
+          0.1320400834083557,
+          0.6780895590782166
+        ],
+        [
+          0.020431607961654663,
+          0.14025722444057465,
+          0.6656509041786194
+        ],
+        [
+          0.0710061565041542,
+          0.13781605660915375,
+          0.7291486859321594
+        ],
+        [
+          0.0583440326154232,
+          0.1425095498561859,
+          0.7024519443511963
+        ],
+        [
+          0.03976709023118019,
+          0.1514739990234375,
+          0.6883654594421387
+        ],
+        [
+          0.021066982299089432,
+          0.15802837908267975,
+          0.6732451319694519
+        ],
+        [
+          0.06996060162782669,
+          0.15673793852329254,
+          0.7411438226699829
+        ],
+        [
+          0.0608944445848465,
+          0.1641077697277069,
+          0.7233651876449585
+        ],
+        [
+          0.04539075493812561,
+          0.17080816626548767,
+          0.71389240026474
+        ],
+        [
+          0.03035694919526577,
+          0.17667682468891144,
+          0.704675018787384
+        ]
+      ],
+      [
+        [
+          -0.13865923881530762,
+          0.14027556777000427,
+          0.8189646601676941
+        ],
+        [
+          -0.11996633559465408,
+          0.10889395326375961,
+          0.8020091652870178
+        ],
+        [
+          -0.09770884364843369,
+          0.10170453041791916,
+          0.779781699180603
+        ],
+        [
+          -0.08517096191644669,
+          0.10215061902999878,
+          0.7549087405204773
+        ],
+        [
+          -0.06121049448847771,
+          0.10850030183792114,
+          0.7304049134254456
+        ],
+        [
+          -0.12392675876617432,
+          0.10100390017032623,
+          0.7401939630508423
+        ],
+        [
+          -0.09812848269939423,
+          0.10074120759963989,
+          0.7206428050994873
+        ],
+        [
+          -0.0772939994931221,
+          0.10534465312957764,
+          0.714796781539917
+        ],
+        [
+          -0.05539727956056595,
+          0.1065475344657898,
+          0.7067099809646606
+        ],
+        [
+          -0.12587493658065796,
+          0.12361064553260803,
+          0.7273308634757996
+        ],
+        [
+          -0.09643607586622238,
+          0.12663844227790833,
+          0.7114502191543579
+        ],
+        [
+          -0.07268668711185455,
+          0.12974940240383148,
+          0.7073184847831726
+        ],
+        [
+          -0.04567119851708412,
+          0.13357646763324738,
+          0.7035387754440308
+        ],
+        [
+          -0.1234576553106308,
+          0.1505129486322403,
+          0.7344684600830078
+        ],
+        [
+          -0.10048718005418777,
+          0.14881345629692078,
+          0.7151721715927124
+        ],
+        [
+          -0.0740397498011589,
+          0.1503012627363205,
+          0.712285041809082
+        ],
+        [
+          -0.049904949963092804,
+          0.1508866250514984,
+          0.7092190980911255
+        ],
+        [
+          -0.11680061370134354,
+          0.17029252648353577,
+          0.7440863251686096
+        ],
+        [
+          -0.09930016845464706,
+          0.17023234069347382,
+          0.7295945286750793
+        ],
+        [
+          -0.07982494682073593,
+          0.1682307869195938,
+          0.7240950465202332
+        ],
+        [
+          -0.06032879278063774,
+          0.166329488158226,
+          0.7177656292915344
+        ]
+      ]
+    ],
+    "valid": [
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ],
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ]
+    ]
+  },
+  "pose_cocoa": {
+    "value": [
+      [
+        -0.8919257521629333,
+        0.4496319591999054,
+        -0.047951288521289825,
+        -0.0012754679191857576
+      ],
+      [
+        0.25806698203086853,
+        0.4190884232521057,
+        -0.8704981207847595,
+        0.12530262768268585
+      ],
+      [
+        -0.3713076710700989,
+        -0.7887940406799316,
+        -0.4898311197757721,
+        0.7271248698234558
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "points_cocoa": {
+    "value": [
+      [
+        -0.0012754679191857576,
+        0.12530262768268585,
+        0.7271248698234558
+      ],
+      [
+        -0.020043393597006798,
+        0.09159418940544128,
+        0.6393812894821167
+      ],
+      [
+        0.05241743475198746,
+        0.07062860578298569,
+        0.6695466637611389
+      ],
+      [
+        0.05943966656923294,
+        0.19810879230499268,
+        0.7412800192832947
+      ],
+      [
+        -0.013021161779761314,
+        0.21907438337802887,
+        0.7111146450042725
+      ],
+      [
+        -0.06199060380458832,
+        0.05249645933508873,
+        0.7129697203636169
+      ],
+      [
+        0.010470226407051086,
+        0.031530871987342834,
+        0.7431350946426392
+      ],
+      [
+        0.01749245822429657,
+        0.15901106595993042,
+        0.8148684501647949
+      ],
+      [
+        -0.054968371987342834,
+        0.1799766570329666,
+        0.7847030758857727
+      ],
+      [
+        0.016187021508812904,
+        0.08111139386892319,
+        0.6544639468193054
+      ],
+      [
+        -0.025760188698768616,
+        0.04201366379857063,
+        0.7280523777008057
+      ],
+      [
+        -0.018737956881523132,
+        0.16949385404586792,
+        0.7997857332229614
+      ],
+      [
+        0.023209253326058388,
+        0.20859159529209137,
+        0.7261973023414612
+      ],
+      [
+        -0.04101699963212013,
+        0.07204532623291016,
+        0.6761754751205444
+      ],
+      [
+        0.03144383057951927,
+        0.05107973888516426,
+        0.7063408493995667
+      ],
+      [
+        0.038466062396764755,
+        0.17855992913246155,
+        0.7780742049217224
+      ],
+      [
+        -0.03399476781487465,
+        0.19952552020549774,
+        0.747908890247345
+      ],
+      [
+        -0.016532277688384056,
+        0.15533429384231567,
+        0.6752479672431946
+      ],
+      [
+        0.0559285506606102,
+        0.13436870276927948,
+        0.7054133415222168
+      ],
+      [
+        0.013981342315673828,
+        0.09527096897363663,
+        0.779001772403717
+      ],
+      [
+        -0.058479487895965576,
+        0.11623655259609222,
+        0.7488363981246948
+      ]
+    ],
+    "valid": [
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true
+    ]
+  }
+}

源网格

mesh_cocoa

源 OBJ 静态预览,不代表物体姿态投影
全部组件元数据
{
+  "schema_version": "hand-warehouse/1.1",
+  "dataset_id": "H2O",
+  "release_id": "shared-v1.1",
+  "sequence_id": "subject4_h1_7",
+  "camera_id": "cam2",
+  "sample_type": "video",
+  "num_frames": 584,
+  "hand_slots": [
+    "left",
+    "right"
+  ],
+  "sampling": {
+    "type": "dense",
+    "source_fps": null,
+    "frames_ref": "camera/frames.jsonl",
+    "selection": {
+      "max_frames": null,
+      "views": null
+    }
+  },
+  "camera": {
+    "model": "pinhole",
+    "schema_id": "camera/pinhole/v1",
+    "image_size": [
+      1280,
+      720
+    ]
+  },
+  "components": {
+    "rgb": {
+      "available": true,
+      "schema_id": "rgb/uint8/v1",
+      "data_ref": "observation/rgb.mkv",
+      "axes": [
+        "T",
+        "height",
+        "width",
+        "channel"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Verified source packet copy or lossless fixed-decoder RGB encoding"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl"
+      },
+      "storage": {
+        "profile": "mkv/ffv1_rgb/v1",
+        "codec": "ffv1",
+        "pixel_format": "bgr0",
+        "encoded_size": [
+          1280,
+          720
+        ],
+        "decoder": {
+          "name": "ffmpeg",
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "autorotate": false,
+          "color_space": "gbr",
+          "color_range": "pc",
+          "color_primaries": "unknown",
+          "color_transfer": "unknown",
+          "source_color_metadata": {
+            "color_space": "gbr",
+            "color_range": "pc",
+            "color_primaries": "unknown",
+            "color_transfer": "unknown"
+          }
+        },
+        "encoder_parameters": {
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "name": "ffv1",
+          "arguments": [
+            "-level",
+            "3",
+            "-pix_fmt",
+            "bgr0"
+          ],
+          "threads": 10
+        },
+        "source_lossy": false,
+        "storage_fps": 30,
+        "timebase_role": "index_only"
+      },
+      "valid_ref": "observation/rgb_valid.pt",
+      "valid_axes": [
+        "T"
+      ]
+    },
+    "intrinsic": {
+      "available": true,
+      "schema_id": "camera/pinhole/v1",
+      "data_ref": "camera/camera.pt",
+      "axes": [
+        "T",
+        "row",
+        "column"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam2/cam_intrinsics.txt",
+        "sha256": "ec260a45bda4bf1eb90fdcb46f5aaba5ec5d096763002619f95f1b4e818d8135"
+      },
+      "valid_ref": "camera/camera.pt",
+      "valid_axes": [
+        "T"
+      ],
+      "data_key": [
+        "intrinsic",
+        "data"
+      ],
+      "valid_key": [
+        "intrinsic",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "extrinsic": {
+      "available": true,
+      "schema_id": "transform/se3/v1",
+      "data_ref": "camera/camera.pt",
+      "axes": [
+        "T",
+        "row",
+        "column"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources"
+      },
+      "valid_ref": "camera/camera.pt",
+      "valid_axes": [
+        "T"
+      ],
+      "convention": "T_camera_from_world",
+      "source_convention": "T_world_from_camera",
+      "data_key": [
+        "extrinsic",
+        "data"
+      ],
+      "valid_key": [
+        "extrinsic",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "mano": {
+      "available": true,
+      "schema_id": "mano/axis_angle61/v1",
+      "data_ref": "annotation/mano/mano.pt",
+      "axes": [
+        "T",
+        "hand",
+        "parameter"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources"
+      },
+      "valid_ref": "annotation/mano/mano.pt",
+      "valid_axes": [
+        "T",
+        "hand"
+      ],
+      "model_profile": {
+        "version": "sha256:eab78181e459e156559df334b103d825e00c8711d2eeffee1cc176fb42051f4f",
+        "flat_hand_mean": true,
+        "left_shapedirs_correction": "not_applied",
+        "models": {
+          "left": {
+            "file": "MANO_LEFT.pkl",
+            "sha256": "c4022f7083f2ca7c78b2b3d595abbab52debd32b09d372b16923a801f0ea6a30"
+          },
+          "right": {
+            "file": "MANO_RIGHT.pkl",
+            "sha256": "45d60aa3b27ef9107a7afd4e00808f307fd91111e1cfa35afd5c4a62de264767"
+          }
+        }
+      },
+      "valid_policy": {
+        "revision": "usable-annotation-2026-09-20",
+        "meaning": "annotation usable for supervision, not merely record presence",
+        "source_rule": "Per-hand hand_pose_mano flag equals 1; corresponding side model available",
+        "source_locator": {
+          "frames_ref": "camera/frames.jsonl",
+          "source_field": "component_sources"
+        },
+        "scope": [
+          "T",
+          "hand"
+        ],
+        "numerical_checks": "Schema shape, finite valid floats, SE(3) where applicable; malformed input aborts",
+        "official_qa": {
+          "status": "not_provided",
+          "reason": "No separate applicable official QA in selected source inputs"
+        },
+        "local_excluded_frame_indices": [],
+        "local_exclusion_reasons": {},
+        "visibility_independent": true
+      },
+      "data_key": [
+        "motion",
+        "data"
+      ],
+      "valid_key": [
+        "motion",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "keypoints_xyz": {
+      "available": true,
+      "schema_id": "keypoints/xyz/v1",
+      "data_ref": "annotation/keypoints/keypoints.pt",
+      "axes": [
+        "T",
+        "hand",
+        "keypoint",
+        "coordinate"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources"
+      },
+      "valid_ref": "annotation/keypoints/keypoints.pt",
+      "valid_axes": [
+        "T",
+        "hand",
+        "keypoint"
+      ],
+      "keypoint_schema": "mano21/v1",
+      "unit": "m",
+      "valid_policy": {
+        "revision": "usable-annotation-2026-09-20",
+        "meaning": "annotation usable for supervision, not merely record presence",
+        "source_rule": "Per-hand hand_pose flag equals 1, broadcast to that hand's 21 source points independently of MANO",
+        "source_locator": {
+          "frames_ref": "camera/frames.jsonl",
+          "source_field": "component_sources"
+        },
+        "scope": [
+          "T",
+          "hand",
+          "keypoint"
+        ],
+        "numerical_checks": "Schema shape, finite valid floats, SE(3) where applicable; malformed input aborts",
+        "official_qa": {
+          "status": "not_provided",
+          "reason": "No separate applicable official QA in selected source inputs"
+        },
+        "local_excluded_frame_indices": [],
+        "local_exclusion_reasons": {},
+        "visibility_independent": true
+      },
+      "data_key": [
+        "xyz",
+        "data"
+      ],
+      "valid_key": [
+        "xyz",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "pose_cocoa": {
+      "available": true,
+      "schema_id": "object/rigid/v1",
+      "data_ref": "annotation/object/cocoa/object.pt",
+      "axes": [
+        "T",
+        "row",
+        "column"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources"
+      },
+      "valid_ref": "annotation/object/cocoa/object.pt",
+      "valid_axes": [
+        "T"
+      ],
+      "convention": "T_camera_from_object",
+      "unit": "m",
+      "valid_policy": {
+        "revision": "usable-annotation-2026-09-20",
+        "meaning": "annotation usable for supervision, not merely record presence",
+        "source_rule": "Source obj_pose_rt class equals this nonzero object class",
+        "source_locator": {
+          "frames_ref": "camera/frames.jsonl",
+          "source_field": "component_sources"
+        },
+        "scope": [
+          "T"
+        ],
+        "numerical_checks": "Schema shape, finite valid floats, SE(3) where applicable; malformed input aborts",
+        "official_qa": {
+          "status": "not_provided",
+          "reason": "No separate applicable official QA in selected source inputs"
+        },
+        "local_excluded_frame_indices": [],
+        "local_exclusion_reasons": {},
+        "visibility_independent": true
+      },
+      "data_key": [
+        "pose",
+        "data"
+      ],
+      "valid_key": [
+        "pose",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "points_cocoa": {
+      "available": true,
+      "schema_id": "object_keypoints/camera/v1",
+      "data_ref": "annotation/object/cocoa/object.pt",
+      "axes": [
+        "T",
+        "keypoint",
+        "coordinate"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources"
+      },
+      "valid_ref": "annotation/object/cocoa/object.pt",
+      "valid_axes": [
+        "T",
+        "keypoint"
+      ],
+      "keypoint_schema": "H2O_official_object21",
+      "keypoint_names": [
+        "center",
+        "corner_0",
+        "corner_1",
+        "corner_2",
+        "corner_3",
+        "corner_4",
+        "corner_5",
+        "corner_6",
+        "corner_7",
+        "edge_midpoint_0",
+        "edge_midpoint_1",
+        "edge_midpoint_2",
+        "edge_midpoint_3",
+        "edge_midpoint_4",
+        "edge_midpoint_5",
+        "edge_midpoint_6",
+        "edge_midpoint_7",
+        "edge_midpoint_8",
+        "edge_midpoint_9",
+        "edge_midpoint_10",
+        "edge_midpoint_11"
+      ],
+      "source_order": "official obj_point_order.jpg: center, 8 corners, 12 edge midpoints",
+      "unit": "m",
+      "valid_policy": {
+        "revision": "usable-annotation-2026-09-20",
+        "meaning": "annotation usable for supervision, not merely record presence",
+        "source_rule": "Source obj_pose class equals this nonzero object class, broadcast to its 21 points",
+        "source_locator": {
+          "frames_ref": "camera/frames.jsonl",
+          "source_field": "component_sources"
+        },
+        "scope": [
+          "T",
+          "keypoint"
+        ],
+        "numerical_checks": "Schema shape, finite valid floats, SE(3) where applicable; malformed input aborts",
+        "official_qa": {
+          "status": "not_provided",
+          "reason": "No separate applicable official QA in selected source inputs"
+        },
+        "local_excluded_frame_indices": [],
+        "local_exclusion_reasons": {},
+        "visibility_independent": true
+      },
+      "data_key": [
+        "keypoints",
+        "xyz",
+        "data"
+      ],
+      "valid_key": [
+        "keypoints",
+        "xyz",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "mesh_cocoa": {
+      "available": true,
+      "schema_id": "mesh/obj/v1",
+      "data_ref": "annotation/object/cocoa/assets/cocoa.obj",
+      "axes": [
+        "vertex"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/object.zip",
+        "member": "object/cocoa/cocoa.obj",
+        "texture_aliases": [
+          {
+            "file": "cocoa.png",
+            "sha256": "90dd612369a14e825d040e539f1f1028e5b6e46e598eb5a4c664034e3a49e91f",
+            "source": {
+              "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/object.zip",
+              "member": "object/cocoa/ovomaltine.png"
+            }
+          }
+        ]
+      },
+      "valid": true,
+      "unit": "m"
+    },
+    "depth": {
+      "available": true,
+      "schema_id": "depth/z_float32/v1",
+      "data_ref": "observation/depth.mkv",
+      "axes": [
+        "T",
+        "height",
+        "width"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources.depth",
+        "definition": "https://github.com/taeinkwon/h2oplayer/blob/main/utils.py",
+        "conversion": "registered millimetre camera-Z to metres; no viewer range clipping"
+      },
+      "storage": {
+        "profile": "mkv/depth_float32_bits/v1",
+        "codec": "ffv1",
+        "pixel_format": "gray16le",
+        "encoded_size": [
+          2560,
+          720
+        ],
+        "decoder": {
+          "name": "ffmpeg",
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "autorotate": false,
+          "color_space": "unknown",
+          "color_range": "unknown",
+          "color_primaries": "unknown",
+          "color_transfer": "unknown"
+        },
+        "encoder_parameters": {
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "name": "ffv1",
+          "arguments": [],
+          "threads": 10
+        },
+        "source_lossy": false,
+        "storage_fps": 30,
+        "timebase_role": "index_only"
+      },
+      "valid_storage": {
+        "profile": "mkv/bool_ffv1/v1",
+        "codec": "ffv1",
+        "pixel_format": "gray",
+        "encoded_size": [
+          1280,
+          720
+        ],
+        "decoder": {
+          "name": "ffmpeg",
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "autorotate": false,
+          "color_space": "unknown",
+          "color_range": "unknown",
+          "color_primaries": "unknown",
+          "color_transfer": "unknown"
+        },
+        "encoder_parameters": {
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "name": "ffv1",
+          "arguments": [],
+          "threads": 10
+        },
+        "source_lossy": false,
+        "storage_fps": 30,
+        "timebase_role": "index_only"
+      },
+      "valid_ref": "observation/depth_valid.mkv",
+      "valid_axes": [
+        "T",
+        "height",
+        "width"
+      ],
+      "unit": "m",
+      "depth_type": "z",
+      "depth_origin": "measured",
+      "invalid_value": "NaN"
+    },
+    "segment": {
+      "available": false,
+      "reason": "H2O provides no native segmentation; rendering deferred to v2.0",
+      "status": "source_missing"
+    },
+    "relations": {
+      "available": false,
+      "reason": "No source contact/grasp annotation",
+      "status": "source_missing"
+    }
+  },
+  "split": "test",
+  "view_type": "exo",
+  "split_scheme": "official_action_split",
+  "split_source_locator": {
+    "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/label_split.zip",
+    "member": "label_split/action_test.txt",
+    "record": 41
+  }
+}
持久化 QC
{
+  "num_frames": 584,
+  "numeric_components": {
+    "intrinsic": {
+      "shape": [
+        584,
+        3,
+        3
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 584,
+      "valid_total": 584
+    },
+    "extrinsic": {
+      "shape": [
+        584,
+        4,
+        4
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 584,
+      "valid_total": 584
+    },
+    "mano": {
+      "shape": [
+        584,
+        2,
+        61
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 1168,
+      "valid_total": 1168
+    },
+    "keypoints_xyz": {
+      "shape": [
+        584,
+        2,
+        21,
+        3
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 24528,
+      "valid_total": 24528
+    },
+    "pose_cocoa": {
+      "shape": [
+        584,
+        4,
+        4
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 584,
+      "valid_total": 584
+    },
+    "points_cocoa": {
+      "shape": [
+        584,
+        21,
+        3
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 12264,
+      "valid_total": 12264
+    }
+  },
+  "bundle_files": 4,
+  "scope": "v1.1 registry, keys, shapes, validity and timeline; not a media pixel comparison",
+  "selected_frames": [
+    0,
+    146,
+    292,
+    438,
+    583
+  ],
+  "preview_media": [
+    "rgb",
+    "depth",
+    "depth_valid"
+  ],
+  "decode_scope": "only selected frames emitted; sequential decoding may traverse earlier frames, no full-video pixel comparison"
+}
\ No newline at end of file diff --git a/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam2.report.json b/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam2.report.json new file mode 100644 index 0000000000000000000000000000000000000000..999cbbaf3ed69232540d35e3cef3000308e975a5 --- /dev/null +++ b/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam2.report.json @@ -0,0 +1,81 @@ +{ + "num_frames": 584, + "numeric_components": { + "intrinsic": { + "shape": [ + 584, + 3, + 3 + ], + "dtype": "torch.float32", + "valid_true": 584, + "valid_total": 584 + }, + "extrinsic": { + "shape": [ + 584, + 4, + 4 + ], + "dtype": "torch.float32", + "valid_true": 584, + "valid_total": 584 + }, + "mano": { + "shape": [ + 584, + 2, + 61 + ], + "dtype": "torch.float32", + "valid_true": 1168, + "valid_total": 1168 + }, + "keypoints_xyz": { + "shape": [ + 584, + 2, + 21, + 3 + ], + "dtype": "torch.float32", + "valid_true": 24528, + "valid_total": 24528 + }, + "pose_cocoa": { + "shape": [ + 584, + 4, + 4 + ], + "dtype": "torch.float32", + "valid_true": 584, + "valid_total": 584 + }, + "points_cocoa": { + "shape": [ + 584, + 21, + 3 + ], + "dtype": "torch.float32", + "valid_true": 12264, + "valid_total": 12264 + } + }, + "bundle_files": 4, + "scope": "v1.1 registry, keys, shapes, validity and timeline; not a media pixel comparison", + "selected_frames": [ + 0, + 146, + 292, + 438, + 583 + ], + "preview_media": [ + "rgb", + "depth", + "depth_valid" + ], + "decode_scope": "only selected frames emitted; sequential decoding may traverse earlier frames, no full-video pixel comparison" +} diff --git a/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam3.html b/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam3.html new file mode 100644 index 0000000000000000000000000000000000000000..93a4065c516a5244b3748669bc34820d58b41476 --- /dev/null +++ b/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam3.html @@ -0,0 +1,4182 @@ +subject4_h1_7_cam3

subject4_h1_7_cam3

直接读取 v1.1 bundle;预览只作人工核查。手/物体点来自源 3D 标注,仅为显示投影到 RGB;未生成新 UV、分割或接触标注。

帧 0 / 584

原生 RGB(仅预览缩放)
RGB + 原生 3D 关键点投影(仅预览:keypoints_xyz #00e6ff, points_cocoa #ff48a4)
深度 Z,黑=无效,白≥3 m;不改源深度
原深度逐像素 valid:白=有效,黑=无效,不是深度值
原帧号、全部数值标注及有效性
{
+  "frame": {
+    "source_frame_id": 0,
+    "sync_id": "subject4/h1/7:0",
+    "source_locator": {
+      "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+      "member": "subject4/h1/7/cam3/rgb/000000.png",
+      "sha256": "a6eca81f22b9786b1aa021ea8b42db3c84062ac7891f5fafeca4f15010d897ec"
+    },
+    "component_sources": {
+      "hand_pose_mano": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/hand_pose_mano/000000.txt",
+        "sha256": "67aca45d29b0cfe71012f9c9d32253401a5b862a38fc644b94dbe100f242ffc8"
+      },
+      "hand_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/hand_pose/000000.txt",
+        "sha256": "fc559b49c4f69c2ce4dcf10d4e19addc0f6a35d8229d5fb03e65889db991cc82"
+      },
+      "depth": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/depth/000000.png",
+        "sha256": "9b0c5ef85a06c18204aa0d3d1f9c1c65de1bc2b84cc011ce8be032ab0853d102"
+      },
+      "cam_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/cam_pose/000000.txt",
+        "sha256": "cdd8501bd470a316c1802e07aa05aa11a896b57327b64feec74b69754c675f73"
+      },
+      "obj_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/obj_pose/000000.txt",
+        "sha256": "33dfbc19ec657738dde94bb003cd7d09eebf1cfc677d6d53a58c2649861f1b1e"
+      },
+      "obj_pose_rt": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/obj_pose_rt/000000.txt",
+        "sha256": "320f25eb076435423d38944c848eb1eb08d2c0d07a709f0b20f50aa488cc67a7"
+      },
+      "rgb": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/rgb/000000.png",
+        "sha256": "a6eca81f22b9786b1aa021ea8b42db3c84062ac7891f5fafeca4f15010d897ec"
+      }
+    },
+    "annotation_matches": {
+      "hand_pose_mano": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "hand_pose": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "depth": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "cam_pose": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose_rt": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      }
+    },
+    "frame_index": 0,
+    "timestamp_ns": null,
+    "clock_domain": null
+  },
+  "rgb_valid": true,
+  "intrinsic": {
+    "value": [
+      [
+        631.3969116210938,
+        0.0,
+        638.1939697265625
+      ],
+      [
+        0.0,
+        630.835693359375,
+        367.2545166015625
+      ],
+      [
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "extrinsic": {
+    "value": [
+      [
+        0.7998588681221008,
+        0.5121832489967346,
+        -0.312879353761673,
+        0.27799317240715027
+      ],
+      [
+        -0.30177295207977295,
+        0.7938140630722046,
+        0.5280069708824158,
+        -0.42933890223503113
+      ],
+      [
+        0.5188048481941223,
+        -0.3279128074645996,
+        0.7895030975341797,
+        0.5125041604042053
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "mano": {
+    "value": [
+      [
+        -1.5324851274490356,
+        2.0571670532226562,
+        -1.342767357826233,
+        0.004794743377715349,
+        0.1707584261894226,
+        -0.6018233895301819,
+        0.1699988692998886,
+        -0.00020761990163009614,
+        -0.7155240774154663,
+        -0.047670040279626846,
+        0.010327726602554321,
+        -0.1493668556213379,
+        -0.08601675927639008,
+        -0.03311705216765404,
+        -0.8589394092559814,
+        -0.21975138783454895,
+        0.030946308746933937,
+        -0.5646840333938599,
+        -0.005143176298588514,
+        -0.0020604562014341354,
+        -0.3331383466720581,
+        -0.4338557720184326,
+        -0.37572646141052246,
+        -0.5886749625205994,
+        -0.31636539101600647,
+        0.008779612369835377,
+        -0.4466293454170227,
+        -0.07524889707565308,
+        -0.0031842770986258984,
+        -0.23183982074260712,
+        -0.1047976166009903,
+        -0.18011412024497986,
+        -0.6970809698104858,
+        -0.30140432715415955,
+        -0.03360113874077797,
+        -0.5651438236236572,
+        -0.043166544288396835,
+        -0.045574817806482315,
+        -0.4815016984939575,
+        0.8711068034172058,
+        0.3190931975841522,
+        -0.1111631914973259,
+        -0.2661822438240051,
+        0.06150209903717041,
+        0.015476319938898087,
+        0.08050798624753952,
+        -0.06933743506669998,
+        -0.38123515248298645,
+        -0.2806254029273987,
+        1.476506233215332,
+        -0.6854744553565979,
+        0.16803301870822906,
+        -0.18744522333145142,
+        -0.5487542748451233,
+        -2.63431978225708,
+        -0.5607357025146484,
+        -2.1435391902923584,
+        -0.6932340264320374,
+        0.1909564733505249,
+        0.006935688201338053,
+        0.7016183137893677
+      ],
+      [
+        2.59074330329895,
+        1.5942636728286743,
+        -0.09984482824802399,
+        0.039051394909620285,
+        -0.37876221537590027,
+        0.19084596633911133,
+        0.15678124129772186,
+        -0.08973533660173416,
+        0.6323488354682922,
+        -0.03988899290561676,
+        -0.02587687410414219,
+        0.3320583999156952,
+        -0.059423819184303284,
+        -0.21750974655151367,
+        0.7102867364883423,
+        -0.19489334523677826,
+        -0.012446731328964233,
+        0.47452813386917114,
+        0.0021097674034535885,
+        -0.028252437710762024,
+        0.11033516377210617,
+        -0.17313151061534882,
+        0.36597415804862976,
+        0.37573477625846863,
+        -0.3820681869983673,
+        0.00449522165581584,
+        0.591370165348053,
+        -0.055342692881822586,
+        0.03855744004249573,
+        0.3542528748512268,
+        -0.03029007650911808,
+        0.04169467091560364,
+        0.5991495847702026,
+        -0.3130511939525604,
+        0.007519695907831192,
+        0.6511586308479309,
+        -0.008511385880410671,
+        0.030142562463879585,
+        0.3059384822845459,
+        0.6466566324234009,
+        0.019822046160697937,
+        0.19402238726615906,
+        -0.09911049902439117,
+        0.16130289435386658,
+        0.20247028768062592,
+        0.055118627846241,
+        -0.013596867211163044,
+        0.24345824122428894,
+        -0.4555988311767578,
+        0.13637742400169373,
+        0.8111323714256287,
+        -2.9508821964263916,
+        0.06259849667549133,
+        -1.952202320098877,
+        -3.399379253387451,
+        0.6082465648651123,
+        -1.1187307834625244,
+        -0.8084438443183899,
+        0.2646311819553375,
+        -0.2640670835971832,
+        0.898673951625824
+      ]
+    ],
+    "valid": [
+      true,
+      true
+    ]
+  },
+  "keypoints_xyz": {
+    "value": [
+      [
+        [
+          0.0966133326292038,
+          0.013880855403840542,
+          0.7074947953224182
+        ],
+        [
+          0.11584530770778656,
+          -0.02000015415251255,
+          0.7138522863388062
+        ],
+        [
+          0.12389665842056274,
+          -0.04573482275009155,
+          0.729849100112915
+        ],
+        [
+          0.12120253592729568,
+          -0.06655985862016678,
+          0.7458401322364807
+        ],
+        [
+          0.12484198063611984,
+          -0.0848660096526146,
+          0.7716891765594482
+        ],
+        [
+          0.07875409722328186,
+          -0.07205410301685333,
+          0.7256374955177307
+        ],
+        [
+          0.07304716110229492,
+          -0.09536778926849365,
+          0.747906506061554
+        ],
+        [
+          0.08178634196519852,
+          -0.09699127078056335,
+          0.767962634563446
+        ],
+        [
+          0.09459256380796432,
+          -0.09970161318778992,
+          0.7869071960449219
+        ],
+        [
+          0.056905295699834824,
+          -0.06490705907344818,
+          0.7383641600608826
+        ],
+        [
+          0.05811052396893501,
+          -0.08193281292915344,
+          0.7655622363090515
+        ],
+        [
+          0.07141313701868057,
+          -0.08267152309417725,
+          0.7850064635276794
+        ],
+        [
+          0.08751624077558517,
+          -0.08261577785015106,
+          0.8039056658744812
+        ],
+        [
+          0.04869699850678444,
+          -0.04206744581460953,
+          0.7505003213882446
+        ],
+        [
+          0.048752035945653915,
+          -0.06261271983385086,
+          0.7722480297088623
+        ],
+        [
+          0.062290795147418976,
+          -0.06531785428524017,
+          0.7930633425712585
+        ],
+        [
+          0.07911133766174316,
+          -0.06654133647680283,
+          0.8111312389373779
+        ],
+        [
+          0.04759448021650314,
+          -0.022103041410446167,
+          0.7606599926948547
+        ],
+        [
+          0.047646258026361465,
+          -0.034751925617456436,
+          0.7777652740478516
+        ],
+        [
+          0.05761830136179924,
+          -0.040730129927396774,
+          0.7932511568069458
+        ],
+        [
+          0.06805761158466339,
+          -0.045374155044555664,
+          0.807915985584259
+        ]
+      ],
+      [
+        [
+          0.361153244972229,
+          -0.2572687268257141,
+          0.9050411581993103
+        ],
+        [
+          0.3347574472427368,
+          -0.27493956685066223,
+          0.8802879452705383
+        ],
+        [
+          0.31066206097602844,
+          -0.28574705123901367,
+          0.8617473840713501
+        ],
+        [
+          0.2847878634929657,
+          -0.2916562259197235,
+          0.853281557559967
+        ],
+        [
+          0.2504379153251648,
+          -0.29183512926101685,
+          0.8461733460426331
+        ],
+        [
+          0.3178098797798157,
+          -0.3340398371219635,
+          0.8911962509155273
+        ],
+        [
+          0.3020973205566406,
+          -0.3594084084033966,
+          0.9037429094314575
+        ],
+        [
+          0.28250324726104736,
+          -0.36122453212738037,
+          0.9138531684875488
+        ],
+        [
+          0.2600764036178589,
+          -0.35818758606910706,
+          0.9189096093177795
+        ],
+        [
+          0.3179417848587036,
+          -0.3399554491043091,
+          0.9165991544723511
+        ],
+        [
+          0.28976622223854065,
+          -0.35203900933265686,
+          0.9303153157234192
+        ],
+        [
+          0.2666049003601074,
+          -0.346417099237442,
+          0.9350828528404236
+        ],
+        [
+          0.241190567612648,
+          -0.3372513949871063,
+          0.9400940537452698
+        ],
+        [
+          0.32084184885025024,
+          -0.32521992921829224,
+          0.9401570558547974
+        ],
+        [
+          0.2963672876358032,
+          -0.3410029709339142,
+          0.9475577473640442
+        ],
+        [
+          0.27156496047973633,
+          -0.331893652677536,
+          0.9510045051574707
+        ],
+        [
+          0.24889899790287018,
+          -0.323565274477005,
+          0.9530445337295532
+        ],
+        [
+          0.31978362798690796,
+          -0.3088078200817108,
+          0.956206202507019
+        ],
+        [
+          0.3027647137641907,
+          -0.32150858640670776,
+          0.9642887711524963
+        ],
+        [
+          0.28261101245880127,
+          -0.31949132680892944,
+          0.966103732585907
+        ],
+        [
+          0.2644985616207123,
+          -0.3138860762119293,
+          0.9661334156990051
+        ]
+      ]
+    ],
+    "valid": [
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ],
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ]
+    ]
+  },
+  "pose_cocoa": {
+    "value": [
+      [
+        -0.11587517708539963,
+        -0.9838971495628357,
+        0.13608576357364655,
+        0.2357352077960968
+      ],
+      [
+        -0.7026392221450806,
+        -0.015641428530216217,
+        -0.7113743424415588,
+        -0.27254557609558105
+      ],
+      [
+        0.7020477056503296,
+        -0.17805007100105286,
+        -0.689512312412262,
+        0.9315624833106995
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "points_cocoa": {
+    "value": [
+      [
+        0.2357352077960968,
+        -0.27254557609558105,
+        0.9315624833106995
+      ],
+      [
+        0.19509783387184143,
+        -0.3539053499698639,
+        0.901286780834198
+      ],
+      [
+        0.2045116424560547,
+        -0.29682230949401855,
+        0.844251811504364
+      ],
+      [
+        0.18458254635334015,
+        -0.19264501333236694,
+        0.9452275037765503
+      ],
+      [
+        0.1751687377691269,
+        -0.2497280389070511,
+        1.0022624731063843
+      ],
+      [
+        0.28688788414001465,
+        -0.3524461090564728,
+        0.9178974628448486
+      ],
+      [
+        0.2963016927242279,
+        -0.29536309838294983,
+        0.8608624935150146
+      ],
+      [
+        0.2763725817203522,
+        -0.19118578732013702,
+        0.9618382453918457
+      ],
+      [
+        0.2669588029384613,
+        -0.24826881289482117,
+        1.0188732147216797
+      ],
+      [
+        0.19980473816394806,
+        -0.32536381483078003,
+        0.872769296169281
+      ],
+      [
+        0.2915947735309601,
+        -0.3239046037197113,
+        0.8893799781799316
+      ],
+      [
+        0.27166569232940674,
+        -0.2197273075580597,
+        0.9903557300567627
+      ],
+      [
+        0.17987564206123352,
+        -0.2211865335702896,
+        0.9737449884414673
+      ],
+      [
+        0.24099285900592804,
+        -0.35317572951316833,
+        0.9095921516418457
+      ],
+      [
+        0.2504066526889801,
+        -0.296092689037323,
+        0.8525571823120117
+      ],
+      [
+        0.23047757148742676,
+        -0.19191540777683258,
+        0.953532874584198
+      ],
+      [
+        0.2210637629032135,
+        -0.24899843335151672,
+        1.0105677843093872
+      ],
+      [
+        0.18513329327106476,
+        -0.3018167018890381,
+        0.9517746567726135
+      ],
+      [
+        0.19454708695411682,
+        -0.24473366141319275,
+        0.8947396874427795
+      ],
+      [
+        0.28633713722229004,
+        -0.24327443540096283,
+        0.9113503694534302
+      ],
+      [
+        0.2769233286380768,
+        -0.300357460975647,
+        0.9683853387832642
+      ]
+    ],
+    "valid": [
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true
+    ]
+  }
+}

帧 146 / 584

原生 RGB(仅预览缩放)
RGB + 原生 3D 关键点投影(仅预览:keypoints_xyz #00e6ff, points_cocoa #ff48a4)
深度 Z,黑=无效,白≥3 m;不改源深度
原深度逐像素 valid:白=有效,黑=无效,不是深度值
原帧号、全部数值标注及有效性
{
+  "frame": {
+    "source_frame_id": 146,
+    "sync_id": "subject4/h1/7:146",
+    "source_locator": {
+      "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+      "member": "subject4/h1/7/cam3/rgb/000146.png",
+      "sha256": "06c7a741f99aaf91bd0083ebee5ff1ef78de7df8f386379484021d1bf185dab0"
+    },
+    "component_sources": {
+      "hand_pose_mano": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/hand_pose_mano/000146.txt",
+        "sha256": "688f97c2adab64ccfa22a7ac774d49788bb037904a1ca93c37221df3dc4cb4ae"
+      },
+      "hand_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/hand_pose/000146.txt",
+        "sha256": "4ea4ffc6cab69fd84879fd7d3b0bc580f2934888d411299244205f40290e6f7d"
+      },
+      "depth": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/depth/000146.png",
+        "sha256": "7f73e4b773ae20c793d49a96bc8ef7515688475096171b4833315faccbcb1f24"
+      },
+      "cam_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/cam_pose/000146.txt",
+        "sha256": "cdd8501bd470a316c1802e07aa05aa11a896b57327b64feec74b69754c675f73"
+      },
+      "obj_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/obj_pose/000146.txt",
+        "sha256": "5aca3d461836ad21c3c2c21749a2fc4fae5ed81450eb828a4514ae8d43455d9d"
+      },
+      "obj_pose_rt": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/obj_pose_rt/000146.txt",
+        "sha256": "e198aac997e3c9a0bb711ae25d1d84d7cec6ad9a1e0b8ec400924bd4705e02e0"
+      },
+      "rgb": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/rgb/000146.png",
+        "sha256": "06c7a741f99aaf91bd0083ebee5ff1ef78de7df8f386379484021d1bf185dab0"
+      }
+    },
+    "annotation_matches": {
+      "hand_pose_mano": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "hand_pose": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "depth": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "cam_pose": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose_rt": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      }
+    },
+    "frame_index": 146,
+    "timestamp_ns": null,
+    "clock_domain": null
+  },
+  "rgb_valid": true,
+  "intrinsic": {
+    "value": [
+      [
+        631.3969116210938,
+        0.0,
+        638.1939697265625
+      ],
+      [
+        0.0,
+        630.835693359375,
+        367.2545166015625
+      ],
+      [
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "extrinsic": {
+    "value": [
+      [
+        0.7998588681221008,
+        0.5121832489967346,
+        -0.312879353761673,
+        0.27799317240715027
+      ],
+      [
+        -0.30177295207977295,
+        0.7938140630722046,
+        0.5280069708824158,
+        -0.42933890223503113
+      ],
+      [
+        0.5188048481941223,
+        -0.3279128074645996,
+        0.7895030975341797,
+        0.5125041604042053
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "mano": {
+    "value": [
+      [
+        -1.1836894750595093,
+        2.309875249862671,
+        -1.44035804271698,
+        0.04427279531955719,
+        0.26809507608413696,
+        0.045330096036195755,
+        -0.045739151537418365,
+        0.032967399805784225,
+        -0.27929994463920593,
+        0.006416820455342531,
+        0.03520970791578293,
+        -0.30499789118766785,
+        0.00784309022128582,
+        0.14051397144794464,
+        -0.129643052816391,
+        -0.21528618037700653,
+        -0.006156093440949917,
+        -0.46771693229675293,
+        -0.009763075970113277,
+        0.005931627005338669,
+        -0.3510958254337311,
+        -0.1256943643093109,
+        -0.27854663133621216,
+        -0.23620522022247314,
+        -0.23329922556877136,
+        0.02548634447157383,
+        -0.29687410593032837,
+        -0.053570929914712906,
+        -0.020346179604530334,
+        -0.06065757945179939,
+        0.02076874114573002,
+        -0.0008505195728503168,
+        -0.21260634064674377,
+        -0.23882624506950378,
+        0.002423439873382449,
+        -0.34939178824424744,
+        -0.03549252077937126,
+        -0.05985437333583832,
+        -0.3917539715766907,
+        0.8870458602905273,
+        0.05347927659749985,
+        -0.231246680021286,
+        -0.3195331394672394,
+        -0.013767085038125515,
+        0.047401413321495056,
+        0.07033149898052216,
+        -0.007284601218998432,
+        -0.36428308486938477,
+        -0.2806254029273987,
+        1.476506233215332,
+        -0.6854744553565979,
+        0.16803301870822906,
+        -0.18744522333145142,
+        -0.5487542748451233,
+        -2.63431978225708,
+        -0.5607357025146484,
+        -2.1435391902923584,
+        -0.6932340264320374,
+        0.24105073511600494,
+        -0.07879079878330231,
+        0.918468713760376
+      ],
+      [
+        2.855172872543335,
+        1.016908884048462,
+        -0.44969645142555237,
+        0.05228615552186966,
+        -0.3141782581806183,
+        0.18577824532985687,
+        0.014561057090759277,
+        -0.0456886850297451,
+        0.27550026774406433,
+        -0.011011692695319653,
+        -0.04303039610385895,
+        0.1838967353105545,
+        -0.01344660110771656,
+        -0.19626811146736145,
+        0.3888801336288452,
+        -0.20499096810817719,
+        -0.013293411582708359,
+        0.3958682715892792,
+        0.003251946996897459,
+        -0.036050885915756226,
+        0.290199875831604,
+        -0.3222946226596832,
+        0.4271879196166992,
+        0.45480868220329285,
+        -0.10017793625593185,
+        -0.05947145074605942,
+        0.2771100103855133,
+        -0.04022855684161186,
+        0.008191186003386974,
+        0.03122820146381855,
+        -0.01720811426639557,
+        0.0541866160929203,
+        0.4702620208263397,
+        -0.23846480250358582,
+        -0.02290438860654831,
+        0.32519856095314026,
+        -0.029706012457609177,
+        0.020899150520563126,
+        0.4011497497558594,
+        1.076732873916626,
+        -0.22445835173130035,
+        0.2684323489665985,
+        -0.34135475754737854,
+        0.16551639139652252,
+        -0.05739152431488037,
+        0.047952648252248764,
+        0.05909768119454384,
+        0.35264596343040466,
+        -0.4555988311767578,
+        0.13637742400169373,
+        0.8111323714256287,
+        -2.9508821964263916,
+        0.06259849667549133,
+        -1.952202320098877,
+        -3.399379253387451,
+        0.6082465648651123,
+        -1.1187307834625244,
+        -0.8084438443183899,
+        0.16693995893001556,
+        -0.20312929153442383,
+        0.9444167017936707
+      ]
+    ],
+    "valid": [
+      true,
+      true
+    ]
+  },
+  "keypoints_xyz": {
+    "value": [
+      [
+        [
+          0.14670760929584503,
+          -0.0718456506729126,
+          0.9243451356887817
+        ],
+        [
+          0.15478333830833435,
+          -0.10994121432304382,
+          0.9308043122291565
+        ],
+        [
+          0.16253165900707245,
+          -0.1362527310848236,
+          0.9459918737411499
+        ],
+        [
+          0.16147658228874207,
+          -0.1583942174911499,
+          0.9603200554847717
+        ],
+        [
+          0.16573892533779144,
+          -0.17882947623729706,
+          0.9843567609786987
+        ],
+        [
+          0.1034444123506546,
+          -0.14911997318267822,
+          0.9381256699562073
+        ],
+        [
+          0.07555520534515381,
+          -0.1651589572429657,
+          0.9442040920257568
+        ],
+        [
+          0.061784666031599045,
+          -0.1752886027097702,
+          0.9579525589942932
+        ],
+        [
+          0.052350111305713654,
+          -0.18905705213546753,
+          0.9740848541259766
+        ],
+        [
+          0.0836845189332962,
+          -0.1361081451177597,
+          0.949556291103363
+        ],
+        [
+          0.0582815557718277,
+          -0.14960609376430511,
+          0.963823676109314
+        ],
+        [
+          0.05153544247150421,
+          -0.16105961799621582,
+          0.9832888245582581
+        ],
+        [
+          0.04741796851158142,
+          -0.17384573817253113,
+          1.0041836500167847
+        ],
+        [
+          0.0815209448337555,
+          -0.11204200237989426,
+          0.9619032144546509
+        ],
+        [
+          0.06050053983926773,
+          -0.12826092541217804,
+          0.9756932258605957
+        ],
+        [
+          0.05356645956635475,
+          -0.13879883289337158,
+          0.9972516298294067
+        ],
+        [
+          0.048988375812768936,
+          -0.15138830244541168,
+          1.0181019306182861
+        ],
+        [
+          0.0854588970541954,
+          -0.09276500344276428,
+          0.9726690053939819
+        ],
+        [
+          0.07174121588468552,
+          -0.10274092108011246,
+          0.9855101704597473
+        ],
+        [
+          0.0661068707704544,
+          -0.111829973757267,
+          1.0016543865203857
+        ],
+        [
+          0.05910089984536171,
+          -0.12100085616111755,
+          1.0170091390609741
+        ]
+      ],
+      [
+        [
+          0.26346203684806824,
+          -0.1963309496641159,
+          0.9507839679718018
+        ],
+        [
+          0.2278737872838974,
+          -0.20286117494106293,
+          0.9331048130989075
+        ],
+        [
+          0.19594500958919525,
+          -0.1983218789100647,
+          0.9341490268707275
+        ],
+        [
+          0.16828583180904388,
+          -0.19756558537483215,
+          0.9373829960823059
+        ],
+        [
+          0.13618649542331696,
+          -0.18548211455345154,
+          0.9434710741043091
+        ],
+        [
+          0.19118496775627136,
+          -0.24852889776229858,
+          0.9547252655029297
+        ],
+        [
+          0.16860949993133545,
+          -0.26485008001327515,
+          0.97121262550354
+        ],
+        [
+          0.1510530710220337,
+          -0.2659660577774048,
+          0.9846279621124268
+        ],
+        [
+          0.13026653230190277,
+          -0.2651396691799164,
+          0.9953151941299438
+        ],
+        [
+          0.19395360350608826,
+          -0.2522779405117035,
+          0.9803884029388428
+        ],
+        [
+          0.1690184772014618,
+          -0.26090356707572937,
+          1.0011693239212036
+        ],
+        [
+          0.14859670400619507,
+          -0.2541153132915497,
+          1.0124677419662476
+        ],
+        [
+          0.12744002044200897,
+          -0.23962801694869995,
+          1.0220298767089844
+        ],
+        [
+          0.20710952579975128,
+          -0.23861655592918396,
+          1.0009020566940308
+        ],
+        [
+          0.1812155693769455,
+          -0.24593324959278107,
+          1.0142754316329956
+        ],
+        [
+          0.15882626175880432,
+          -0.2368793487548828,
+          1.0255342721939087
+        ],
+        [
+          0.13866817951202393,
+          -0.22643834352493286,
+          1.033898949623108
+        ],
+        [
+          0.21591198444366455,
+          -0.22226645052433014,
+          1.0144387483596802
+        ],
+        [
+          0.19553010165691376,
+          -0.22385475039482117,
+          1.024355173110962
+        ],
+        [
+          0.1768801212310791,
+          -0.21878713369369507,
+          1.0306823253631592
+        ],
+        [
+          0.15778180956840515,
+          -0.2151545137166977,
+          1.0371750593185425
+        ]
+      ]
+    ],
+    "valid": [
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ],
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ]
+    ]
+  },
+  "pose_cocoa": {
+    "value": [
+      [
+        -0.09066341817378998,
+        -0.995745837688446,
+        -0.01645190455019474,
+        0.11291561275720596
+      ],
+      [
+        -0.6962346434593201,
+        0.0751873105764389,
+        -0.7138652205467224,
+        -0.160898819565773
+      ],
+      [
+        0.7120656371116638,
+        -0.0532672144472599,
+        -0.7000895738601685,
+        1.0150625705718994
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "points_cocoa": {
+    "value": [
+      [
+        0.11291561275720596,
+        -0.160898819565773,
+        1.0150625705718994
+      ],
+      [
+        0.06158045306801796,
+        -0.23794400691986084,
+        0.9902399778366089
+      ],
+      [
+        0.06894603371620178,
+        -0.18138130009174347,
+        0.9323911666870117
+      ],
+      [
+        0.07135532796382904,
+        -0.07683922350406647,
+        1.034915804862976
+      ],
+      [
+        0.06398975849151611,
+        -0.13340193033218384,
+        1.0927647352218628
+      ],
+      [
+        0.15447589755058289,
+        -0.24495840072631836,
+        0.9952093958854675
+      ],
+      [
+        0.161841481924057,
+        -0.188395693898201,
+        0.9373605847358704
+      ],
+      [
+        0.16425077617168427,
+        -0.08385361731052399,
+        1.0398852825164795
+      ],
+      [
+        0.15688520669937134,
+        -0.14041633903980255,
+        1.0977340936660767
+      ],
+      [
+        0.06526324152946472,
+        -0.20966264605522156,
+        0.9613155722618103
+      ],
+      [
+        0.15815868973731995,
+        -0.21667705476284027,
+        0.966284990310669
+      ],
+      [
+        0.1605679839849472,
+        -0.11213497817516327,
+        1.0688097476959229
+      ],
+      [
+        0.06767254322767258,
+        -0.10512057691812515,
+        1.0638402700424194
+      ],
+      [
+        0.10802818089723587,
+        -0.2414512038230896,
+        0.9927247166633606
+      ],
+      [
+        0.1153937503695488,
+        -0.18488849699497223,
+        0.9348758459091187
+      ],
+      [
+        0.11780305206775665,
+        -0.08034642040729523,
+        1.0374006032943726
+      ],
+      [
+        0.11043747514486313,
+        -0.1369091272354126,
+        1.0952494144439697
+      ],
+      [
+        0.06278510391712189,
+        -0.18567296862602234,
+        1.0415023565292358
+      ],
+      [
+        0.07015068084001541,
+        -0.12911026179790497,
+        0.9836534857749939
+      ],
+      [
+        0.16304612159729004,
+        -0.1361246556043625,
+        0.9886229038238525
+      ],
+      [
+        0.1556805521249771,
+        -0.19268736243247986,
+        1.0464717149734497
+      ]
+    ],
+    "valid": [
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true
+    ]
+  }
+}

帧 292 / 584

原生 RGB(仅预览缩放)
RGB + 原生 3D 关键点投影(仅预览:keypoints_xyz #00e6ff, points_cocoa #ff48a4)
深度 Z,黑=无效,白≥3 m;不改源深度
原深度逐像素 valid:白=有效,黑=无效,不是深度值
原帧号、全部数值标注及有效性
{
+  "frame": {
+    "source_frame_id": 292,
+    "sync_id": "subject4/h1/7:292",
+    "source_locator": {
+      "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+      "member": "subject4/h1/7/cam3/rgb/000292.png",
+      "sha256": "1eb42103b8ba6169b12ead3e4ee88729e710a16ee0e3454c0d7e778e2c652f88"
+    },
+    "component_sources": {
+      "hand_pose_mano": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/hand_pose_mano/000292.txt",
+        "sha256": "6cbbe1c340b52c9b3c0b99826ae340455e747f39fe177685f890a9faab1ed3c1"
+      },
+      "hand_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/hand_pose/000292.txt",
+        "sha256": "0d602535f9987322b6ea0e0c80c13df764b3efb2796b6fdfec12edca2e0ebb2b"
+      },
+      "depth": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/depth/000292.png",
+        "sha256": "c04dc38e53b1a4020b4f3bb00dc96fa13dd5d8fb3d7ae39eb80afbf6feac3cf2"
+      },
+      "cam_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/cam_pose/000292.txt",
+        "sha256": "cdd8501bd470a316c1802e07aa05aa11a896b57327b64feec74b69754c675f73"
+      },
+      "obj_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/obj_pose/000292.txt",
+        "sha256": "3218a7f0888ed7dcba0dc6d635154d46a9abe39071a2f238c630a7d2fa173298"
+      },
+      "obj_pose_rt": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/obj_pose_rt/000292.txt",
+        "sha256": "99afe00fd1f5b0885c9a179ad06073b0b351b9d31929d2ffcce1caccecb112cf"
+      },
+      "rgb": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/rgb/000292.png",
+        "sha256": "1eb42103b8ba6169b12ead3e4ee88729e710a16ee0e3454c0d7e778e2c652f88"
+      }
+    },
+    "annotation_matches": {
+      "hand_pose_mano": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "hand_pose": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "depth": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "cam_pose": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose_rt": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      }
+    },
+    "frame_index": 292,
+    "timestamp_ns": null,
+    "clock_domain": null
+  },
+  "rgb_valid": true,
+  "intrinsic": {
+    "value": [
+      [
+        631.3969116210938,
+        0.0,
+        638.1939697265625
+      ],
+      [
+        0.0,
+        630.835693359375,
+        367.2545166015625
+      ],
+      [
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "extrinsic": {
+    "value": [
+      [
+        0.7998588681221008,
+        0.5121832489967346,
+        -0.312879353761673,
+        0.27799317240715027
+      ],
+      [
+        -0.30177295207977295,
+        0.7938140630722046,
+        0.5280069708824158,
+        -0.42933890223503113
+      ],
+      [
+        0.5188048481941223,
+        -0.3279128074645996,
+        0.7895030975341797,
+        0.5125041604042053
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "mano": {
+    "value": [
+      [
+        1.709958791732788,
+        -2.420790433883667,
+        1.0231176614761353,
+        0.05670445039868355,
+        0.25673824548721313,
+        0.05390062928199768,
+        -0.011501568369567394,
+        0.044752590358257294,
+        -0.36865484714508057,
+        0.002329871989786625,
+        0.020953018218278885,
+        -0.4384158253669739,
+        0.004928406327962875,
+        0.16468551754951477,
+        -0.04126213490962982,
+        -0.25341796875,
+        -0.0038572056218981743,
+        -0.6761335134506226,
+        -0.009948598220944405,
+        0.018649278208613396,
+        -0.5019798874855042,
+        -0.24138857424259186,
+        -0.1614977866411209,
+        -0.09372156858444214,
+        0.14770151674747467,
+        0.056116294115781784,
+        -0.12757499516010284,
+        -0.047184936702251434,
+        -0.004884934984147549,
+        0.019028406590223312,
+        -0.022903690114617348,
+        -0.005811681039631367,
+        -0.12458775192499161,
+        -0.23412154614925385,
+        0.01715666800737381,
+        -0.2998145818710327,
+        -0.012882375158369541,
+        -0.04756156727671623,
+        -0.460102379322052,
+        1.1249886751174927,
+        -0.01869778335094452,
+        -0.41282445192337036,
+        -0.20248471200466156,
+        0.02288021706044674,
+        0.024625735357403755,
+        0.07889742404222488,
+        0.02330283634364605,
+        -0.5219765901565552,
+        -0.2806254029273987,
+        1.476506233215332,
+        -0.6854744553565979,
+        0.16803301870822906,
+        -0.18744522333145142,
+        -0.5487542748451233,
+        -2.63431978225708,
+        -0.5607357025146484,
+        -2.1435391902923584,
+        -0.6932340264320374,
+        0.21719804406166077,
+        -0.06062481552362442,
+        0.8926006555557251
+      ],
+      [
+        -2.449824094772339,
+        -1.4720693826675415,
+        0.6533290147781372,
+        0.038850054144859314,
+        -0.2796785235404968,
+        0.7232538461685181,
+        0.1962374448776245,
+        0.008065328001976013,
+        0.8089422583580017,
+        -0.03829491138458252,
+        0.013623629696667194,
+        0.3365393280982971,
+        -0.07450265437364578,
+        0.017885863780975342,
+        0.9586271643638611,
+        -0.23017618060112,
+        -0.0407082624733448,
+        0.6756982207298279,
+        -0.011619498021900654,
+        0.004039316903799772,
+        0.5732011795043945,
+        -0.5500652194023132,
+        0.3716382086277008,
+        0.3936295807361603,
+        -0.34403276443481445,
+        0.012122486717998981,
+        0.5724484324455261,
+        -0.08576078712940216,
+        0.04578283056616783,
+        0.45880401134490967,
+        -0.26148533821105957,
+        0.14884883165359497,
+        0.8358225226402283,
+        -0.31061968207359314,
+        0.05572012811899185,
+        0.563292920589447,
+        -0.02641027607023716,
+        0.06818082183599472,
+        0.48979705572128296,
+        1.0069056749343872,
+        -0.3729687035083771,
+        0.10506514459848404,
+        -0.30229654908180237,
+        -0.143685981631279,
+        -0.05555962771177292,
+        0.0849929228425026,
+        -0.059027161449193954,
+        0.37952637672424316,
+        -0.4555988311767578,
+        0.13637742400169373,
+        0.8111323714256287,
+        -2.9508821964263916,
+        0.06259849667549133,
+        -1.952202320098877,
+        -3.399379253387451,
+        0.6082465648651123,
+        -1.1187307834625244,
+        -0.8084438443183899,
+        0.29443421959877014,
+        -0.21214723587036133,
+        0.9662191867828369
+      ]
+    ],
+    "valid": [
+      true,
+      true
+    ]
+  },
+  "keypoints_xyz": {
+    "value": [
+      [
+        [
+          0.12285490334033966,
+          -0.05367964506149292,
+          0.8984771966934204
+        ],
+        [
+          0.1380637139081955,
+          -0.08989743888378143,
+          0.8945818543434143
+        ],
+        [
+          0.15965284407138824,
+          -0.10946125537157059,
+          0.9061646461486816
+        ],
+        [
+          0.17108315229415894,
+          -0.12712912261486053,
+          0.9220973253250122
+        ],
+        [
+          0.1887149214744568,
+          -0.13524429500102997,
+          0.9467238187789917
+        ],
+        [
+          0.10015104711055756,
+          -0.13897749781608582,
+          0.9140251278877258
+        ],
+        [
+          0.07957921922206879,
+          -0.1609400361776352,
+          0.9269267320632935
+        ],
+        [
+          0.07567381858825684,
+          -0.17468270659446716,
+          0.9435743689537048
+        ],
+        [
+          0.08049333095550537,
+          -0.1902855485677719,
+          0.959934651851654
+        ],
+        [
+          0.08517113327980042,
+          -0.13138766586780548,
+          0.9342343807220459
+        ],
+        [
+          0.06753211468458176,
+          -0.14991600811481476,
+          0.9536413550376892
+        ],
+        [
+          0.07383798807859421,
+          -0.16367830336093903,
+          0.9717084169387817
+        ],
+        [
+          0.08657144755125046,
+          -0.1764213740825653,
+          0.9884699583053589
+        ],
+        [
+          0.08491171896457672,
+          -0.10964860767126083,
+          0.9504718780517578
+        ],
+        [
+          0.0718756839632988,
+          -0.13088013231754303,
+          0.967035710811615
+        ],
+        [
+          0.07326500862836838,
+          -0.14606299996376038,
+          0.986820638179779
+        ],
+        [
+          0.07803818583488464,
+          -0.16234858334064484,
+          1.0048518180847168
+        ],
+        [
+          0.0901792049407959,
+          -0.09120908379554749,
+          0.9621015787124634
+        ],
+        [
+          0.08281576633453369,
+          -0.10320650041103363,
+          0.9780524373054504
+        ],
+        [
+          0.07728318125009537,
+          -0.11368193477392197,
+          0.9933707118034363
+        ],
+        [
+          0.06886179745197296,
+          -0.12406478822231293,
+          1.0079808235168457
+        ]
+      ],
+      [
+        [
+          0.3909562826156616,
+          -0.2053488790988922,
+          0.972586452960968
+        ],
+        [
+          0.3550399839878082,
+          -0.22035525739192963,
+          0.9622641205787659
+        ],
+        [
+          0.3274839222431183,
+          -0.2344709187746048,
+          0.9713500142097473
+        ],
+        [
+          0.3122824430465698,
+          -0.2539062798023224,
+          0.9842823147773743
+        ],
+        [
+          0.2928466498851776,
+          -0.2687024474143982,
+          1.0088858604431152
+        ],
+        [
+          0.34147655963897705,
+          -0.2794828712940216,
+          0.9770632386207581
+        ],
+        [
+          0.3196716606616974,
+          -0.29333972930908203,
+          0.9965670704841614
+        ],
+        [
+          0.3056909739971161,
+          -0.28176870942115784,
+          1.009220004081726
+        ],
+        [
+          0.29138311743736267,
+          -0.2648402750492096,
+          1.0157333612442017
+        ],
+        [
+          0.3530353903770447,
+          -0.2871689200401306,
+          0.9991457462310791
+        ],
+        [
+          0.32656100392341614,
+          -0.2933312952518463,
+          1.0188723802566528
+        ],
+        [
+          0.31007498502731323,
+          -0.2783440351486206,
+          1.0285871028900146
+        ],
+        [
+          0.3008227050304413,
+          -0.25294893980026245,
+          1.0308486223220825
+        ],
+        [
+          0.36746251583099365,
+          -0.27422812581062317,
+          1.019268274307251
+        ],
+        [
+          0.34244921803474426,
+          -0.28308331966400146,
+          1.0333678722381592
+        ],
+        [
+          0.3204971253871918,
+          -0.27012673020362854,
+          1.0411298274993896
+        ],
+        [
+          0.3018369972705841,
+          -0.25531435012817383,
+          1.0442461967468262
+        ],
+        [
+          0.3750070035457611,
+          -0.2589576244354248,
+          1.0346935987472534
+        ],
+        [
+          0.359266072511673,
+          -0.26891374588012695,
+          1.04770827293396
+        ],
+        [
+          0.3399178683757782,
+          -0.2657735347747803,
+          1.0531232357025146
+        ],
+        [
+          0.32311785221099854,
+          -0.2577621042728424,
+          1.0549910068511963
+        ]
+      ]
+    ],
+    "valid": [
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ],
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ]
+    ]
+  },
+  "pose_cocoa": {
+    "value": [
+      [
+        0.47092634439468384,
+        -0.8797991275787354,
+        0.06466998904943466,
+        0.13632002472877502
+      ],
+      [
+        -0.5316600203514099,
+        -0.34154871106147766,
+        -0.7750363349914551,
+        -0.13710801303386688
+      ],
+      [
+        0.7039645910263062,
+        0.33060285449028015,
+        -0.6285983920097351,
+        0.9788951277732849
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "points_cocoa": {
+    "value": [
+      [
+        0.13632002472877502,
+        -0.13710801303386688,
+        0.9788951277732849
+      ],
+      [
+        0.11914530396461487,
+        -0.23138636350631714,
+        0.9768842458724976
+      ],
+      [
+        0.0808868333697319,
+        -0.18819382786750793,
+        0.9196935296058655
+      ],
+      [
+        0.0714162290096283,
+        -0.07469354569911957,
+        1.0117486715316772
+      ],
+      [
+        0.10967469960451126,
+        -0.11788607388734818,
+        1.068939447402954
+      ],
+      [
+        0.20122380554676056,
+        -0.1995224803686142,
+        0.9460415244102478
+      ],
+      [
+        0.1629653424024582,
+        -0.1563299596309662,
+        0.8888508081436157
+      ],
+      [
+        0.153494730591774,
+        -0.04282967001199722,
+        0.9809060096740723
+      ],
+      [
+        0.19175320863723755,
+        -0.08602219820022583,
+        1.0380966663360596
+      ],
+      [
+        0.10001606494188309,
+        -0.20979009568691254,
+        0.9482889175415039
+      ],
+      [
+        0.18209457397460938,
+        -0.1779262274503708,
+        0.9174461960792542
+      ],
+      [
+        0.17262397706508636,
+        -0.06442593783140182,
+        1.009501338005066
+      ],
+      [
+        0.09054546058177948,
+        -0.09628980606794357,
+        1.040343999862671
+      ],
+      [
+        0.16018454730510712,
+        -0.21545442938804626,
+        0.9614629149436951
+      ],
+      [
+        0.12192608416080475,
+        -0.17226189374923706,
+        0.904272198677063
+      ],
+      [
+        0.11245547980070114,
+        -0.058761607855558395,
+        0.9963273406028748
+      ],
+      [
+        0.1507139503955841,
+        -0.1019541397690773,
+        1.0535180568695068
+      ],
+      [
+        0.11440999805927277,
+        -0.17463621497154236,
+        1.022911787033081
+      ],
+      [
+        0.0761515274643898,
+        -0.13144369423389435,
+        0.9657211303710938
+      ],
+      [
+        0.1582300364971161,
+        -0.0995798110961914,
+        0.934878408908844
+      ],
+      [
+        0.19648849964141846,
+        -0.1427723467350006,
+        0.9920691251754761
+      ]
+    ],
+    "valid": [
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true
+    ]
+  }
+}

帧 438 / 584

原生 RGB(仅预览缩放)
RGB + 原生 3D 关键点投影(仅预览:keypoints_xyz #00e6ff, points_cocoa #ff48a4)
深度 Z,黑=无效,白≥3 m;不改源深度
原深度逐像素 valid:白=有效,黑=无效,不是深度值
原帧号、全部数值标注及有效性
{
+  "frame": {
+    "source_frame_id": 438,
+    "sync_id": "subject4/h1/7:438",
+    "source_locator": {
+      "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+      "member": "subject4/h1/7/cam3/rgb/000438.png",
+      "sha256": "45a2d57237f06f015f27f04b47180be468e5193b0f37ee2bf36f341dd4fe6757"
+    },
+    "component_sources": {
+      "hand_pose_mano": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/hand_pose_mano/000438.txt",
+        "sha256": "7b15fe3cf54b1fe5a984b3b96bdf54fc0fb3fa91cb6f5e7003fc5a430706e070"
+      },
+      "hand_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/hand_pose/000438.txt",
+        "sha256": "e3b15dc1f67953a21290f9bc7c39ba9cc5451be61b7ddeed664140df7c869ab6"
+      },
+      "depth": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/depth/000438.png",
+        "sha256": "bd3b85c187e292f460386a906759420b63f5a9dc0ac09173c57ee0f5aef1e1ba"
+      },
+      "cam_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/cam_pose/000438.txt",
+        "sha256": "cdd8501bd470a316c1802e07aa05aa11a896b57327b64feec74b69754c675f73"
+      },
+      "obj_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/obj_pose/000438.txt",
+        "sha256": "146382539d4845ec2fcd0fbf4d8b826f7041dbbf94ca1af0dc3350547a792cd2"
+      },
+      "obj_pose_rt": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/obj_pose_rt/000438.txt",
+        "sha256": "5904097a0e8fbaef177076a3f92b9b0f0b29fc242ee6d7ff6b857031ed00b555"
+      },
+      "rgb": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/rgb/000438.png",
+        "sha256": "45a2d57237f06f015f27f04b47180be468e5193b0f37ee2bf36f341dd4fe6757"
+      }
+    },
+    "annotation_matches": {
+      "hand_pose_mano": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "hand_pose": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "depth": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "cam_pose": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose_rt": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      }
+    },
+    "frame_index": 438,
+    "timestamp_ns": null,
+    "clock_domain": null
+  },
+  "rgb_valid": true,
+  "intrinsic": {
+    "value": [
+      [
+        631.3969116210938,
+        0.0,
+        638.1939697265625
+      ],
+      [
+        0.0,
+        630.835693359375,
+        367.2545166015625
+      ],
+      [
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "extrinsic": {
+    "value": [
+      [
+        0.7998588681221008,
+        0.5121832489967346,
+        -0.312879353761673,
+        0.27799317240715027
+      ],
+      [
+        -0.30177295207977295,
+        0.7938140630722046,
+        0.5280069708824158,
+        -0.42933890223503113
+      ],
+      [
+        0.5188048481941223,
+        -0.3279128074645996,
+        0.7895030975341797,
+        0.5125041604042053
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "mano": {
+    "value": [
+      [
+        1.8548312187194824,
+        -2.021656036376953,
+        1.0322383642196655,
+        0.0441138930618763,
+        0.31131309270858765,
+        -0.00626513222232461,
+        -0.02036752924323082,
+        0.0451199971139431,
+        -0.34308093786239624,
+        -0.0009102236945182085,
+        0.02689209207892418,
+        -0.3802049458026886,
+        -0.015653541311621666,
+        0.17522288858890533,
+        -0.151083305478096,
+        -0.26585128903388977,
+        -0.005229040049016476,
+        -0.7646550536155701,
+        -0.02005547657608986,
+        0.021737094968557358,
+        -0.5219047665596008,
+        -0.16009902954101562,
+        -0.27070680260658264,
+        -0.22880232334136963,
+        -0.21499472856521606,
+        0.005724928807467222,
+        -0.30150121450424194,
+        -0.050526686012744904,
+        -0.038071416318416595,
+        -0.0952521562576294,
+        -0.03314047306776047,
+        -0.048541996628046036,
+        -0.22275325655937195,
+        -0.29545819759368896,
+        -0.0030866072047501802,
+        -0.5464324951171875,
+        -0.030524782836437225,
+        -0.06140469014644623,
+        -0.5275866389274597,
+        0.9019661545753479,
+        -0.023597352206707,
+        -0.28409048914909363,
+        -0.2718367874622345,
+        -0.13753437995910645,
+        -0.011629355140030384,
+        0.0581522062420845,
+        -0.013459517620503902,
+        -0.34280645847320557,
+        -0.2806254029273987,
+        1.476506233215332,
+        -0.6854744553565979,
+        0.16803301870822906,
+        -0.18744522333145142,
+        -0.5487542748451233,
+        -2.63431978225708,
+        -0.5607357025146484,
+        -2.1435391902923584,
+        -0.6932340264320374,
+        0.19081223011016846,
+        -0.06435453146696091,
+        0.8216617107391357
+      ],
+      [
+        -2.2821390628814697,
+        -0.47177791595458984,
+        1.3161365985870361,
+        -0.010575031861662865,
+        -0.24173542857170105,
+        0.697502851486206,
+        0.20180197060108185,
+        0.0415135994553566,
+        0.4217185378074646,
+        -0.025461535900831223,
+        0.020387917757034302,
+        -0.013804709538817406,
+        -0.1217774748802185,
+        0.07403827458620071,
+        1.1567624807357788,
+        -0.20310288667678833,
+        0.00981416366994381,
+        0.3319188356399536,
+        -0.01451727282255888,
+        0.004075824748724699,
+        0.35964834690093994,
+        -0.7797415256500244,
+        0.6071902513504028,
+        0.8347394466400146,
+        -0.33239734172821045,
+        0.005324136465787888,
+        0.5375992059707642,
+        -0.056371986865997314,
+        0.008091513998806477,
+        0.37781718373298645,
+        -0.2753085494041443,
+        0.3322887122631073,
+        1.052750587463379,
+        -0.32745134830474854,
+        0.0330868624150753,
+        0.6154453158378601,
+        -0.03810780122876167,
+        0.03570462018251419,
+        0.6540924906730652,
+        0.8452440500259399,
+        -0.190989688038826,
+        0.08434190601110458,
+        -0.332694947719574,
+        0.25225186347961426,
+        -0.028766237199306488,
+        0.0437852218747139,
+        -0.002592346863821149,
+        0.3574236035346985,
+        -0.4555988311767578,
+        0.13637742400169373,
+        0.8111323714256287,
+        -2.9508821964263916,
+        0.06259849667549133,
+        -1.952202320098877,
+        -3.399379253387451,
+        0.6082465648651123,
+        -1.1187307834625244,
+        -0.8084438443183899,
+        0.2254108041524887,
+        -0.18622328341007233,
+        1.0009534358978271
+      ]
+    ],
+    "valid": [
+      true,
+      true
+    ]
+  },
+  "keypoints_xyz": {
+    "value": [
+      [
+        [
+          0.09646908193826675,
+          -0.05740935355424881,
+          0.827538251876831
+        ],
+        [
+          0.11688226461410522,
+          -0.09119562059640884,
+          0.827500581741333
+        ],
+        [
+          0.14062844216823578,
+          -0.11076811701059341,
+          0.8335031270980835
+        ],
+        [
+          0.15890882909297943,
+          -0.12718814611434937,
+          0.8431397676467896
+        ],
+        [
+          0.18570476770401,
+          -0.13830086588859558,
+          0.8564238548278809
+        ],
+        [
+          0.0919189378619194,
+          -0.13962186872959137,
+          0.8629406094551086
+        ],
+        [
+          0.07920898497104645,
+          -0.15959426760673523,
+          0.8855584263801575
+        ],
+        [
+          0.0811530202627182,
+          -0.16871477663516998,
+          0.9054152965545654
+        ],
+        [
+          0.09053386747837067,
+          -0.17916163802146912,
+          0.9238169193267822
+        ],
+        [
+          0.07945898920297623,
+          -0.1299641728401184,
+          0.8839619755744934
+        ],
+        [
+          0.072090744972229,
+          -0.1456318348646164,
+          0.9110044836997986
+        ],
+        [
+          0.08733554929494858,
+          -0.15187576413154602,
+          0.9278625249862671
+        ],
+        [
+          0.10795776546001434,
+          -0.15581344068050385,
+          0.9406270980834961
+        ],
+        [
+          0.07814813405275345,
+          -0.10547666996717453,
+          0.895578920841217
+        ],
+        [
+          0.07510723173618317,
+          -0.12488140165805817,
+          0.9181463122367859
+        ],
+        [
+          0.09005950391292572,
+          -0.13223597407341003,
+          0.9367536306381226
+        ],
+        [
+          0.10873661190271378,
+          -0.1391882598400116,
+          0.9512317180633545
+        ],
+        [
+          0.0820002481341362,
+          -0.08442047238349915,
+          0.9022729396820068
+        ],
+        [
+          0.08154220879077911,
+          -0.09515757858753204,
+          0.9206330180168152
+        ],
+        [
+          0.08895035833120346,
+          -0.10318398475646973,
+          0.9366233348846436
+        ],
+        [
+          0.09532460570335388,
+          -0.11173839122056961,
+          0.9523484706878662
+        ]
+      ],
+      [
+        [
+          0.321932852268219,
+          -0.1794249266386032,
+          1.0073206424713135
+        ],
+        [
+          0.2854383587837219,
+          -0.17207974195480347,
+          1.022680401802063
+        ],
+        [
+          0.26155886054039,
+          -0.16643191874027252,
+          1.043632984161377
+        ],
+        [
+          0.24123148620128632,
+          -0.16279380023479462,
+          1.062331199645996
+        ],
+        [
+          0.2225647121667862,
+          -0.14959710836410522,
+          1.0885686874389648
+        ],
+        [
+          0.2599596679210663,
+          -0.21373410522937775,
+          1.061600923538208
+        ],
+        [
+          0.2500174641609192,
+          -0.21360108256340027,
+          1.0924067497253418
+        ],
+        [
+          0.24857006967067719,
+          -0.20171566307544708,
+          1.111010193824768
+        ],
+        [
+          0.24208401143550873,
+          -0.18905992805957794,
+          1.1294499635696411
+        ],
+        [
+          0.27781906723976135,
+          -0.22643204033374786,
+          1.0757473707199097
+        ],
+        [
+          0.2700800895690918,
+          -0.21032044291496277,
+          1.104182243347168
+        ],
+        [
+          0.2685687243938446,
+          -0.1898730993270874,
+          1.1172360181808472
+        ],
+        [
+          0.27020061016082764,
+          -0.1633484661579132,
+          1.1236096620559692
+        ],
+        [
+          0.3053121268749237,
+          -0.22355200350284576,
+          1.079791784286499
+        ],
+        [
+          0.29123738408088684,
+          -0.21030229330062866,
+          1.1027966737747192
+        ],
+        [
+          0.29001584649086,
+          -0.1845012754201889,
+          1.1093411445617676
+        ],
+        [
+          0.29216042160987854,
+          -0.16075681149959564,
+          1.1072591543197632
+        ],
+        [
+          0.3263976573944092,
+          -0.21494273841381073,
+          1.0828464031219482
+        ],
+        [
+          0.315324604511261,
+          -0.20421762764453888,
+          1.099539041519165
+        ],
+        [
+          0.30770766735076904,
+          -0.1858830451965332,
+          1.1039389371871948
+        ],
+        [
+          0.3028300702571869,
+          -0.16747669875621796,
+          1.1043957471847534
+        ]
+      ]
+    ],
+    "valid": [
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ],
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ]
+    ]
+  },
+  "pose_cocoa": {
+    "value": [
+      [
+        0.7923485040664673,
+        -0.6090691685676575,
+        -0.03491378203034401,
+        0.14322209358215332
+      ],
+      [
+        -0.2444530427455902,
+        -0.2645375430583954,
+        -0.932878315448761,
+        -0.13277511298656464
+      ],
+      [
+        0.5589516162872314,
+        0.7476997971534729,
+        -0.35849469900131226,
+        0.9026201963424683
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "points_cocoa": {
+    "value": [
+      [
+        0.14322209358215332,
+        -0.13277511298656464,
+        0.9026201963424683
+      ],
+      [
+        0.1444404274225235,
+        -0.22335229814052582,
+        0.9339525103569031
+      ],
+      [
+        0.08006933331489563,
+        -0.20349271595478058,
+        0.8885427713394165
+      ],
+      [
+        0.08518228679895401,
+        -0.06687724590301514,
+        0.9410426020622253
+      ],
+      [
+        0.14955337345600128,
+        -0.08673682808876038,
+        0.9864522814750671
+      ],
+      [
+        0.20126189291477203,
+        -0.19867298007011414,
+        0.864197850227356
+      ],
+      [
+        0.13689081370830536,
+        -0.1788133978843689,
+        0.8187881112098694
+      ],
+      [
+        0.14200375974178314,
+        -0.042197927832603455,
+        0.8712879419326782
+      ],
+      [
+        0.206374853849411,
+        -0.062057506293058395,
+        0.91669762134552
+      ],
+      [
+        0.11225488036870956,
+        -0.2134225070476532,
+        0.9112476706504822
+      ],
+      [
+        0.1690763533115387,
+        -0.18874318897724152,
+        0.8414930105209351
+      ],
+      [
+        0.17418931424617767,
+        -0.052127715200185776,
+        0.8939927816390991
+      ],
+      [
+        0.11736782640218735,
+        -0.07680703699588776,
+        0.9637474417686462
+      ],
+      [
+        0.17285116016864777,
+        -0.21101263165473938,
+        0.8990751504898071
+      ],
+      [
+        0.1084800735116005,
+        -0.19115304946899414,
+        0.8536654710769653
+      ],
+      [
+        0.11359302699565887,
+        -0.054537586867809296,
+        0.9061652421951294
+      ],
+      [
+        0.17796410620212555,
+        -0.07439716905355453,
+        0.951574981212616
+      ],
+      [
+        0.1469969004392624,
+        -0.1550445705652237,
+        0.9602023959159851
+      ],
+      [
+        0.08262580633163452,
+        -0.13518498837947845,
+        0.9147926568984985
+      ],
+      [
+        0.13944728672504425,
+        -0.11050566285848618,
+        0.8450380563735962
+      ],
+      [
+        0.20381838083267212,
+        -0.13036523759365082,
+        0.890447735786438
+      ]
+    ],
+    "valid": [
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true
+    ]
+  }
+}

帧 583 / 584

原生 RGB(仅预览缩放)
RGB + 原生 3D 关键点投影(仅预览:keypoints_xyz #00e6ff, points_cocoa #ff48a4)
深度 Z,黑=无效,白≥3 m;不改源深度
原深度逐像素 valid:白=有效,黑=无效,不是深度值
原帧号、全部数值标注及有效性
{
+  "frame": {
+    "source_frame_id": 583,
+    "sync_id": "subject4/h1/7:583",
+    "source_locator": {
+      "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+      "member": "subject4/h1/7/cam3/rgb/000583.png",
+      "sha256": "0337b0bc33457c3f959112bddda915ec19c6e2b9b8587bf2291bdca3ef698e6a"
+    },
+    "component_sources": {
+      "hand_pose_mano": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/hand_pose_mano/000583.txt",
+        "sha256": "f50f227c2bf7b182029f6adc13ffb6f58e94c45edf95d565365796fd32822892"
+      },
+      "hand_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/hand_pose/000583.txt",
+        "sha256": "dd53001b26404f943dd44dcdd6388e00b6356e30362dc5b078e31658ec5cde89"
+      },
+      "depth": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/depth/000583.png",
+        "sha256": "d3450fa0b0cff71c64397e926b35582df579866695e91646e32c6bbbcfb317de"
+      },
+      "cam_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/cam_pose/000583.txt",
+        "sha256": "cdd8501bd470a316c1802e07aa05aa11a896b57327b64feec74b69754c675f73"
+      },
+      "obj_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/obj_pose/000583.txt",
+        "sha256": "9b2609178db43975973e8565c83a334abce9a6177aef5a8b880c5b52d87fd048"
+      },
+      "obj_pose_rt": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/obj_pose_rt/000583.txt",
+        "sha256": "f969ab1959f947e096d159b580db579ca7329d53a151279cec33a7f7ec4e93d8"
+      },
+      "rgb": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/rgb/000583.png",
+        "sha256": "0337b0bc33457c3f959112bddda915ec19c6e2b9b8587bf2291bdca3ef698e6a"
+      }
+    },
+    "annotation_matches": {
+      "hand_pose_mano": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "hand_pose": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "depth": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "cam_pose": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose_rt": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      }
+    },
+    "frame_index": 583,
+    "timestamp_ns": null,
+    "clock_domain": null
+  },
+  "rgb_valid": true,
+  "intrinsic": {
+    "value": [
+      [
+        631.3969116210938,
+        0.0,
+        638.1939697265625
+      ],
+      [
+        0.0,
+        630.835693359375,
+        367.2545166015625
+      ],
+      [
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "extrinsic": {
+    "value": [
+      [
+        0.7998588681221008,
+        0.5121832489967346,
+        -0.312879353761673,
+        0.27799317240715027
+      ],
+      [
+        -0.30177295207977295,
+        0.7938140630722046,
+        0.5280069708824158,
+        -0.42933890223503113
+      ],
+      [
+        0.5188048481941223,
+        -0.3279128074645996,
+        0.7895030975341797,
+        0.5125041604042053
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "mano": {
+    "value": [
+      [
+        -1.568138837814331,
+        2.345588207244873,
+        -1.0595636367797852,
+        0.03340994939208031,
+        0.3228056728839874,
+        -0.07821039110422134,
+        0.00736130028963089,
+        0.044860951602458954,
+        -0.34319353103637695,
+        -0.0073201400227844715,
+        0.029256504029035568,
+        -0.2064988762140274,
+        -0.027639465406537056,
+        0.14684435725212097,
+        -0.37501099705696106,
+        -0.20725110173225403,
+        0.003951873164623976,
+        -0.45073044300079346,
+        -0.012203204445540905,
+        0.014346623793244362,
+        -0.27812620997428894,
+        -0.18587090075016022,
+        -0.2580273449420929,
+        -0.4124998152256012,
+        -0.3137627840042114,
+        0.006992853246629238,
+        -0.35082560777664185,
+        -0.045118238776922226,
+        -0.05261789634823799,
+        -0.16788744926452637,
+        -0.003028573701158166,
+        -0.08499280363321304,
+        -0.46834662556648254,
+        -0.24806950986385345,
+        0.0007639554096385837,
+        -0.23950041830539703,
+        -0.024439869448542595,
+        -0.04982245713472366,
+        -0.2905237078666687,
+        0.7547170519828796,
+        -0.04532362520694733,
+        -0.17603327333927155,
+        -0.32395726442337036,
+        -0.21300753951072693,
+        0.0027177261654287577,
+        0.04898405075073242,
+        0.0004385107895359397,
+        -0.2091580480337143,
+        -0.2806254029273987,
+        1.476506233215332,
+        -0.6854744553565979,
+        0.16803301870822906,
+        -0.18744522333145142,
+        -0.5487542748451233,
+        -2.63431978225708,
+        -0.5607357025146484,
+        -2.1435391902923584,
+        -0.6932340264320374,
+        0.2530611455440521,
+        -0.06729326397180557,
+        0.7514695525169373
+      ],
+      [
+        2.35845947265625,
+        1.187900424003601,
+        0.22882770001888275,
+        0.035671260207891464,
+        -0.23242047429084778,
+        0.9175093173980713,
+        0.194064661860466,
+        -0.05034683272242546,
+        0.22226956486701965,
+        -0.04774567112326622,
+        -0.05082094669342041,
+        -0.05479954183101654,
+        -0.026752272620797157,
+        -0.05637355521321297,
+        1.0516794919967651,
+        -0.17926554381847382,
+        -0.017618492245674133,
+        0.14412200450897217,
+        0.011402745731174946,
+        0.000925535277929157,
+        0.04662485048174858,
+        -0.48833101987838745,
+        0.37762975692749023,
+        0.5960181355476379,
+        -0.13645552098751068,
+        -0.03331734985113144,
+        0.3506031930446625,
+        -0.06388898938894272,
+        -0.019688155502080917,
+        0.05134721100330353,
+        -0.12143892049789429,
+        0.09756811708211899,
+        0.8241648077964783,
+        -0.23145286738872528,
+        0.017975086346268654,
+        0.3451057970523834,
+        -0.025740794837474823,
+        0.021148517727851868,
+        0.2646710276603699,
+        1.092269778251648,
+        -0.44799330830574036,
+        0.15289244055747986,
+        -0.30898961424827576,
+        -0.09629514813423157,
+        -0.03233122080564499,
+        0.0844181478023529,
+        0.041561249643564224,
+        0.3536794185638428,
+        -0.4555988311767578,
+        0.13637742400169373,
+        0.8111323714256287,
+        -2.9508821964263916,
+        0.06259849667549133,
+        -1.952202320098877,
+        -3.399379253387451,
+        0.6082465648651123,
+        -1.1187307834625244,
+        -0.8084438443183899,
+        0.23402200639247894,
+        -0.1416180282831192,
+        0.8632332682609558
+      ]
+    ],
+    "valid": [
+      true,
+      true
+    ]
+  },
+  "keypoints_xyz": {
+    "value": [
+      [
+        [
+          0.1587180197238922,
+          -0.06034812331199646,
+          0.757345974445343
+        ],
+        [
+          0.17437882721424103,
+          -0.09645894914865494,
+          0.7543531060218811
+        ],
+        [
+          0.19088177382946014,
+          -0.12301653623580933,
+          0.7566642761230469
+        ],
+        [
+          0.2031167894601822,
+          -0.146103173494339,
+          0.7604014277458191
+        ],
+        [
+          0.22183990478515625,
+          -0.17096106708049774,
+          0.7690154314041138
+        ],
+        [
+          0.13408473134040833,
+          -0.1460721343755722,
+          0.7661505937576294
+        ],
+        [
+          0.11399242281913757,
+          -0.16824565827846527,
+          0.7794411182403564
+        ],
+        [
+          0.10947659611701965,
+          -0.18129782378673553,
+          0.7964853644371033
+        ],
+        [
+          0.1084822416305542,
+          -0.19730091094970703,
+          0.8132508993148804
+        ],
+        [
+          0.11629228293895721,
+          -0.13918446004390717,
+          0.784217357635498
+        ],
+        [
+          0.10472803562879562,
+          -0.1600259244441986,
+          0.8057339787483215
+        ],
+        [
+          0.11025983840227127,
+          -0.17288295924663544,
+          0.8246991634368896
+        ],
+        [
+          0.1173134371638298,
+          -0.18679334223270416,
+          0.8441752195358276
+        ],
+        [
+          0.1136261597275734,
+          -0.11807186901569366,
+          0.8010535836219788
+        ],
+        [
+          0.10753939300775528,
+          -0.14161592721939087,
+          0.8184806704521179
+        ],
+        [
+          0.1123589426279068,
+          -0.155838742852211,
+          0.8384400606155396
+        ],
+        [
+          0.1172185093164444,
+          -0.17207591235637665,
+          0.8567162156105042
+        ],
+        [
+          0.1171073168516159,
+          -0.10010671615600586,
+          0.8140207529067993
+        ],
+        [
+          0.11262821406126022,
+          -0.11399378627538681,
+          0.8295021653175354
+        ],
+        [
+          0.11811459064483643,
+          -0.12448372691869736,
+          0.8448271751403809
+        ],
+        [
+          0.12355442345142365,
+          -0.13498453795909882,
+          0.8591644167900085
+        ]
+      ],
+      [
+        [
+          0.33054405450820923,
+          -0.1348196566104889,
+          0.8696005344390869
+        ],
+        [
+          0.31296002864837646,
+          -0.15530718863010406,
+          0.8397210836410522
+        ],
+        [
+          0.28426098823547363,
+          -0.16665804386138916,
+          0.8303046822547913
+        ],
+        [
+          0.26011455059051514,
+          -0.18038611114025116,
+          0.8324379920959473
+        ],
+        [
+          0.2258087694644928,
+          -0.18622593581676483,
+          0.8344050645828247
+        ],
+        [
+          0.28282517194747925,
+          -0.20837178826332092,
+          0.8529533743858337
+        ],
+        [
+          0.25131192803382874,
+          -0.2128366231918335,
+          0.847050130367279
+        ],
+        [
+          0.23043911159038544,
+          -0.20645390450954437,
+          0.8434405326843262
+        ],
+        [
+          0.20819780230522156,
+          -0.20300209522247314,
+          0.837138295173645
+        ],
+        [
+          0.27213820815086365,
+          -0.20813830196857452,
+          0.8767452836036682
+        ],
+        [
+          0.2390906661748886,
+          -0.20667102932929993,
+          0.8709386587142944
+        ],
+        [
+          0.21719950437545776,
+          -0.19848011434078217,
+          0.8642702102661133
+        ],
+        [
+          0.1927558332681656,
+          -0.18831458687782288,
+          0.8566584587097168
+        ],
+        [
+          0.26836958527565,
+          -0.18861037492752075,
+          0.8963661193847656
+        ],
+        [
+          0.23956209421157837,
+          -0.19474947452545166,
+          0.8904232978820801
+        ],
+        [
+          0.21658748388290405,
+          -0.1852654367685318,
+          0.8808193206787109
+        ],
+        [
+          0.1955466866493225,
+          -0.1773167848587036,
+          0.8715276718139648
+        ],
+        [
+          0.264196515083313,
+          -0.16886058449745178,
+          0.9073471426963806
+        ],
+        [
+          0.24209731817245483,
+          -0.1727786511182785,
+          0.9038037657737732
+        ],
+        [
+          0.2239469587802887,
+          -0.16989226639270782,
+          0.8950992822647095
+        ],
+        [
+          0.20528796315193176,
+          -0.16758772730827332,
+          0.8867142796516418
+        ]
+      ]
+    ],
+    "valid": [
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ],
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ]
+    ]
+  },
+  "pose_cocoa": {
+    "value": [
+      [
+        0.4418811500072479,
+        -0.8957497477531433,
+        -0.0487176775932312,
+        0.17265096306800842
+      ],
+      [
+        -0.531460702419281,
+        -0.2176501750946045,
+        -0.8186439275741577,
+        -0.15571695566177368
+      ],
+      [
+        0.7226965427398682,
+        0.38763484358787537,
+        -0.5722315311431885,
+        0.8230589032173157
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "points_cocoa": {
+    "value": [
+      [
+        0.17265096306800842,
+        -0.15571695566177368,
+        0.8230589032173157
+      ],
+      [
+        0.1452498435974121,
+        -0.24740087985992432,
+        0.8285965919494629
+      ],
+      [
+        0.1093510314822197,
+        -0.20422454178333282,
+        0.7698841094970703
+      ],
+      [
+        0.11648549884557724,
+        -0.08433813601732254,
+        0.8536846041679382
+      ],
+      [
+        0.15238431096076965,
+        -0.12751446664333344,
+        0.9123970866203308
+      ],
+      [
+        0.228816419839859,
+        -0.22709578275680542,
+        0.7924332618713379
+      ],
+      [
+        0.1929176151752472,
+        -0.18391944468021393,
+        0.7337207198143005
+      ],
+      [
+        0.20005208253860474,
+        -0.06403304636478424,
+        0.8175212740898132
+      ],
+      [
+        0.23595088720321655,
+        -0.10720938444137573,
+        0.8762337565422058
+      ],
+      [
+        0.1273004412651062,
+        -0.22581270337104797,
+        0.7992403507232666
+      ],
+      [
+        0.2108670175075531,
+        -0.20550762116909027,
+        0.7630770206451416
+      ],
+      [
+        0.21800148487091064,
+        -0.08562121540307999,
+        0.8468775153160095
+      ],
+      [
+        0.13443490862846375,
+        -0.10592630505561829,
+        0.8830408453941345
+      ],
+      [
+        0.18703313171863556,
+        -0.23724833130836487,
+        0.8105149269104004
+      ],
+      [
+        0.15113432705402374,
+        -0.19407199323177338,
+        0.7518024444580078
+      ],
+      [
+        0.1582687944173813,
+        -0.07418559491634369,
+        0.8356029391288757
+      ],
+      [
+        0.1941675990819931,
+        -0.11736192554235458,
+        0.8943154215812683
+      ],
+      [
+        0.14881707727909088,
+        -0.18745768070220947,
+        0.8704968690872192
+      ],
+      [
+        0.11291826516389847,
+        -0.14428134262561798,
+        0.8117843270301819
+      ],
+      [
+        0.19648484885692596,
+        -0.12397624552249908,
+        0.7756209969520569
+      ],
+      [
+        0.23238365352153778,
+        -0.16715258359909058,
+        0.8343334794044495
+      ]
+    ],
+    "valid": [
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true
+    ]
+  }
+}

源网格

mesh_cocoa

源 OBJ 静态预览,不代表物体姿态投影
全部组件元数据
{
+  "schema_version": "hand-warehouse/1.1",
+  "dataset_id": "H2O",
+  "release_id": "shared-v1.1",
+  "sequence_id": "subject4_h1_7",
+  "camera_id": "cam3",
+  "sample_type": "video",
+  "num_frames": 584,
+  "hand_slots": [
+    "left",
+    "right"
+  ],
+  "sampling": {
+    "type": "dense",
+    "source_fps": null,
+    "frames_ref": "camera/frames.jsonl",
+    "selection": {
+      "max_frames": null,
+      "views": null
+    }
+  },
+  "camera": {
+    "model": "pinhole",
+    "schema_id": "camera/pinhole/v1",
+    "image_size": [
+      1280,
+      720
+    ]
+  },
+  "components": {
+    "rgb": {
+      "available": true,
+      "schema_id": "rgb/uint8/v1",
+      "data_ref": "observation/rgb.mkv",
+      "axes": [
+        "T",
+        "height",
+        "width",
+        "channel"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Verified source packet copy or lossless fixed-decoder RGB encoding"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl"
+      },
+      "storage": {
+        "profile": "mkv/ffv1_rgb/v1",
+        "codec": "ffv1",
+        "pixel_format": "bgr0",
+        "encoded_size": [
+          1280,
+          720
+        ],
+        "decoder": {
+          "name": "ffmpeg",
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "autorotate": false,
+          "color_space": "gbr",
+          "color_range": "pc",
+          "color_primaries": "unknown",
+          "color_transfer": "unknown",
+          "source_color_metadata": {
+            "color_space": "gbr",
+            "color_range": "pc",
+            "color_primaries": "unknown",
+            "color_transfer": "unknown"
+          }
+        },
+        "encoder_parameters": {
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "name": "ffv1",
+          "arguments": [
+            "-level",
+            "3",
+            "-pix_fmt",
+            "bgr0"
+          ],
+          "threads": 10
+        },
+        "source_lossy": false,
+        "storage_fps": 30,
+        "timebase_role": "index_only"
+      },
+      "valid_ref": "observation/rgb_valid.pt",
+      "valid_axes": [
+        "T"
+      ]
+    },
+    "intrinsic": {
+      "available": true,
+      "schema_id": "camera/pinhole/v1",
+      "data_ref": "camera/camera.pt",
+      "axes": [
+        "T",
+        "row",
+        "column"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam3/cam_intrinsics.txt",
+        "sha256": "f406b977e4559315cefa9088f607eb353d1f28529e81d1eb2ad90ce948c5b8de"
+      },
+      "valid_ref": "camera/camera.pt",
+      "valid_axes": [
+        "T"
+      ],
+      "data_key": [
+        "intrinsic",
+        "data"
+      ],
+      "valid_key": [
+        "intrinsic",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "extrinsic": {
+      "available": true,
+      "schema_id": "transform/se3/v1",
+      "data_ref": "camera/camera.pt",
+      "axes": [
+        "T",
+        "row",
+        "column"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources"
+      },
+      "valid_ref": "camera/camera.pt",
+      "valid_axes": [
+        "T"
+      ],
+      "convention": "T_camera_from_world",
+      "source_convention": "T_world_from_camera",
+      "data_key": [
+        "extrinsic",
+        "data"
+      ],
+      "valid_key": [
+        "extrinsic",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "mano": {
+      "available": true,
+      "schema_id": "mano/axis_angle61/v1",
+      "data_ref": "annotation/mano/mano.pt",
+      "axes": [
+        "T",
+        "hand",
+        "parameter"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources"
+      },
+      "valid_ref": "annotation/mano/mano.pt",
+      "valid_axes": [
+        "T",
+        "hand"
+      ],
+      "model_profile": {
+        "version": "sha256:eab78181e459e156559df334b103d825e00c8711d2eeffee1cc176fb42051f4f",
+        "flat_hand_mean": true,
+        "left_shapedirs_correction": "not_applied",
+        "models": {
+          "left": {
+            "file": "MANO_LEFT.pkl",
+            "sha256": "c4022f7083f2ca7c78b2b3d595abbab52debd32b09d372b16923a801f0ea6a30"
+          },
+          "right": {
+            "file": "MANO_RIGHT.pkl",
+            "sha256": "45d60aa3b27ef9107a7afd4e00808f307fd91111e1cfa35afd5c4a62de264767"
+          }
+        }
+      },
+      "valid_policy": {
+        "revision": "usable-annotation-2026-09-20",
+        "meaning": "annotation usable for supervision, not merely record presence",
+        "source_rule": "Per-hand hand_pose_mano flag equals 1; corresponding side model available",
+        "source_locator": {
+          "frames_ref": "camera/frames.jsonl",
+          "source_field": "component_sources"
+        },
+        "scope": [
+          "T",
+          "hand"
+        ],
+        "numerical_checks": "Schema shape, finite valid floats, SE(3) where applicable; malformed input aborts",
+        "official_qa": {
+          "status": "not_provided",
+          "reason": "No separate applicable official QA in selected source inputs"
+        },
+        "local_excluded_frame_indices": [],
+        "local_exclusion_reasons": {},
+        "visibility_independent": true
+      },
+      "data_key": [
+        "motion",
+        "data"
+      ],
+      "valid_key": [
+        "motion",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "keypoints_xyz": {
+      "available": true,
+      "schema_id": "keypoints/xyz/v1",
+      "data_ref": "annotation/keypoints/keypoints.pt",
+      "axes": [
+        "T",
+        "hand",
+        "keypoint",
+        "coordinate"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources"
+      },
+      "valid_ref": "annotation/keypoints/keypoints.pt",
+      "valid_axes": [
+        "T",
+        "hand",
+        "keypoint"
+      ],
+      "keypoint_schema": "mano21/v1",
+      "unit": "m",
+      "valid_policy": {
+        "revision": "usable-annotation-2026-09-20",
+        "meaning": "annotation usable for supervision, not merely record presence",
+        "source_rule": "Per-hand hand_pose flag equals 1, broadcast to that hand's 21 source points independently of MANO",
+        "source_locator": {
+          "frames_ref": "camera/frames.jsonl",
+          "source_field": "component_sources"
+        },
+        "scope": [
+          "T",
+          "hand",
+          "keypoint"
+        ],
+        "numerical_checks": "Schema shape, finite valid floats, SE(3) where applicable; malformed input aborts",
+        "official_qa": {
+          "status": "not_provided",
+          "reason": "No separate applicable official QA in selected source inputs"
+        },
+        "local_excluded_frame_indices": [],
+        "local_exclusion_reasons": {},
+        "visibility_independent": true
+      },
+      "data_key": [
+        "xyz",
+        "data"
+      ],
+      "valid_key": [
+        "xyz",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "pose_cocoa": {
+      "available": true,
+      "schema_id": "object/rigid/v1",
+      "data_ref": "annotation/object/cocoa/object.pt",
+      "axes": [
+        "T",
+        "row",
+        "column"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources"
+      },
+      "valid_ref": "annotation/object/cocoa/object.pt",
+      "valid_axes": [
+        "T"
+      ],
+      "convention": "T_camera_from_object",
+      "unit": "m",
+      "valid_policy": {
+        "revision": "usable-annotation-2026-09-20",
+        "meaning": "annotation usable for supervision, not merely record presence",
+        "source_rule": "Source obj_pose_rt class equals this nonzero object class",
+        "source_locator": {
+          "frames_ref": "camera/frames.jsonl",
+          "source_field": "component_sources"
+        },
+        "scope": [
+          "T"
+        ],
+        "numerical_checks": "Schema shape, finite valid floats, SE(3) where applicable; malformed input aborts",
+        "official_qa": {
+          "status": "not_provided",
+          "reason": "No separate applicable official QA in selected source inputs"
+        },
+        "local_excluded_frame_indices": [],
+        "local_exclusion_reasons": {},
+        "visibility_independent": true
+      },
+      "data_key": [
+        "pose",
+        "data"
+      ],
+      "valid_key": [
+        "pose",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "points_cocoa": {
+      "available": true,
+      "schema_id": "object_keypoints/camera/v1",
+      "data_ref": "annotation/object/cocoa/object.pt",
+      "axes": [
+        "T",
+        "keypoint",
+        "coordinate"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources"
+      },
+      "valid_ref": "annotation/object/cocoa/object.pt",
+      "valid_axes": [
+        "T",
+        "keypoint"
+      ],
+      "keypoint_schema": "H2O_official_object21",
+      "keypoint_names": [
+        "center",
+        "corner_0",
+        "corner_1",
+        "corner_2",
+        "corner_3",
+        "corner_4",
+        "corner_5",
+        "corner_6",
+        "corner_7",
+        "edge_midpoint_0",
+        "edge_midpoint_1",
+        "edge_midpoint_2",
+        "edge_midpoint_3",
+        "edge_midpoint_4",
+        "edge_midpoint_5",
+        "edge_midpoint_6",
+        "edge_midpoint_7",
+        "edge_midpoint_8",
+        "edge_midpoint_9",
+        "edge_midpoint_10",
+        "edge_midpoint_11"
+      ],
+      "source_order": "official obj_point_order.jpg: center, 8 corners, 12 edge midpoints",
+      "unit": "m",
+      "valid_policy": {
+        "revision": "usable-annotation-2026-09-20",
+        "meaning": "annotation usable for supervision, not merely record presence",
+        "source_rule": "Source obj_pose class equals this nonzero object class, broadcast to its 21 points",
+        "source_locator": {
+          "frames_ref": "camera/frames.jsonl",
+          "source_field": "component_sources"
+        },
+        "scope": [
+          "T",
+          "keypoint"
+        ],
+        "numerical_checks": "Schema shape, finite valid floats, SE(3) where applicable; malformed input aborts",
+        "official_qa": {
+          "status": "not_provided",
+          "reason": "No separate applicable official QA in selected source inputs"
+        },
+        "local_excluded_frame_indices": [],
+        "local_exclusion_reasons": {},
+        "visibility_independent": true
+      },
+      "data_key": [
+        "keypoints",
+        "xyz",
+        "data"
+      ],
+      "valid_key": [
+        "keypoints",
+        "xyz",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "mesh_cocoa": {
+      "available": true,
+      "schema_id": "mesh/obj/v1",
+      "data_ref": "annotation/object/cocoa/assets/cocoa.obj",
+      "axes": [
+        "vertex"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/object.zip",
+        "member": "object/cocoa/cocoa.obj",
+        "texture_aliases": [
+          {
+            "file": "cocoa.png",
+            "sha256": "90dd612369a14e825d040e539f1f1028e5b6e46e598eb5a4c664034e3a49e91f",
+            "source": {
+              "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/object.zip",
+              "member": "object/cocoa/ovomaltine.png"
+            }
+          }
+        ]
+      },
+      "valid": true,
+      "unit": "m"
+    },
+    "depth": {
+      "available": true,
+      "schema_id": "depth/z_float32/v1",
+      "data_ref": "observation/depth.mkv",
+      "axes": [
+        "T",
+        "height",
+        "width"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources.depth",
+        "definition": "https://github.com/taeinkwon/h2oplayer/blob/main/utils.py",
+        "conversion": "registered millimetre camera-Z to metres; no viewer range clipping"
+      },
+      "storage": {
+        "profile": "mkv/depth_float32_bits/v1",
+        "codec": "ffv1",
+        "pixel_format": "gray16le",
+        "encoded_size": [
+          2560,
+          720
+        ],
+        "decoder": {
+          "name": "ffmpeg",
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "autorotate": false,
+          "color_space": "unknown",
+          "color_range": "unknown",
+          "color_primaries": "unknown",
+          "color_transfer": "unknown"
+        },
+        "encoder_parameters": {
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "name": "ffv1",
+          "arguments": [],
+          "threads": 10
+        },
+        "source_lossy": false,
+        "storage_fps": 30,
+        "timebase_role": "index_only"
+      },
+      "valid_storage": {
+        "profile": "mkv/bool_ffv1/v1",
+        "codec": "ffv1",
+        "pixel_format": "gray",
+        "encoded_size": [
+          1280,
+          720
+        ],
+        "decoder": {
+          "name": "ffmpeg",
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "autorotate": false,
+          "color_space": "unknown",
+          "color_range": "unknown",
+          "color_primaries": "unknown",
+          "color_transfer": "unknown"
+        },
+        "encoder_parameters": {
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "name": "ffv1",
+          "arguments": [],
+          "threads": 10
+        },
+        "source_lossy": false,
+        "storage_fps": 30,
+        "timebase_role": "index_only"
+      },
+      "valid_ref": "observation/depth_valid.mkv",
+      "valid_axes": [
+        "T",
+        "height",
+        "width"
+      ],
+      "unit": "m",
+      "depth_type": "z",
+      "depth_origin": "measured",
+      "invalid_value": "NaN"
+    },
+    "segment": {
+      "available": false,
+      "reason": "H2O provides no native segmentation; rendering deferred to v2.0",
+      "status": "source_missing"
+    },
+    "relations": {
+      "available": false,
+      "reason": "No source contact/grasp annotation",
+      "status": "source_missing"
+    }
+  },
+  "split": "test",
+  "view_type": "exo",
+  "split_scheme": "official_action_split",
+  "split_source_locator": {
+    "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/label_split.zip",
+    "member": "label_split/action_test.txt",
+    "record": 41
+  }
+}
持久化 QC
{
+  "num_frames": 584,
+  "numeric_components": {
+    "intrinsic": {
+      "shape": [
+        584,
+        3,
+        3
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 584,
+      "valid_total": 584
+    },
+    "extrinsic": {
+      "shape": [
+        584,
+        4,
+        4
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 584,
+      "valid_total": 584
+    },
+    "mano": {
+      "shape": [
+        584,
+        2,
+        61
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 1168,
+      "valid_total": 1168
+    },
+    "keypoints_xyz": {
+      "shape": [
+        584,
+        2,
+        21,
+        3
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 24528,
+      "valid_total": 24528
+    },
+    "pose_cocoa": {
+      "shape": [
+        584,
+        4,
+        4
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 584,
+      "valid_total": 584
+    },
+    "points_cocoa": {
+      "shape": [
+        584,
+        21,
+        3
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 12264,
+      "valid_total": 12264
+    }
+  },
+  "bundle_files": 4,
+  "scope": "v1.1 registry, keys, shapes, validity and timeline; not a media pixel comparison",
+  "selected_frames": [
+    0,
+    146,
+    292,
+    438,
+    583
+  ],
+  "preview_media": [
+    "rgb",
+    "depth",
+    "depth_valid"
+  ],
+  "decode_scope": "only selected frames emitted; sequential decoding may traverse earlier frames, no full-video pixel comparison"
+}
\ No newline at end of file diff --git a/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam3.report.json b/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam3.report.json new file mode 100644 index 0000000000000000000000000000000000000000..999cbbaf3ed69232540d35e3cef3000308e975a5 --- /dev/null +++ b/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam3.report.json @@ -0,0 +1,81 @@ +{ + "num_frames": 584, + "numeric_components": { + "intrinsic": { + "shape": [ + 584, + 3, + 3 + ], + "dtype": "torch.float32", + "valid_true": 584, + "valid_total": 584 + }, + "extrinsic": { + "shape": [ + 584, + 4, + 4 + ], + "dtype": "torch.float32", + "valid_true": 584, + "valid_total": 584 + }, + "mano": { + "shape": [ + 584, + 2, + 61 + ], + "dtype": "torch.float32", + "valid_true": 1168, + "valid_total": 1168 + }, + "keypoints_xyz": { + "shape": [ + 584, + 2, + 21, + 3 + ], + "dtype": "torch.float32", + "valid_true": 24528, + "valid_total": 24528 + }, + "pose_cocoa": { + "shape": [ + 584, + 4, + 4 + ], + "dtype": "torch.float32", + "valid_true": 584, + "valid_total": 584 + }, + "points_cocoa": { + "shape": [ + 584, + 21, + 3 + ], + "dtype": "torch.float32", + "valid_true": 12264, + "valid_total": 12264 + } + }, + "bundle_files": 4, + "scope": "v1.1 registry, keys, shapes, validity and timeline; not a media pixel comparison", + "selected_frames": [ + 0, + 146, + 292, + 438, + 583 + ], + "preview_media": [ + "rgb", + "depth", + "depth_valid" + ], + "decode_scope": "only selected frames emitted; sequential decoding may traverse earlier frames, no full-video pixel comparison" +} diff --git a/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam4.html b/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam4.html new file mode 100644 index 0000000000000000000000000000000000000000..51657f5c71ff7766069c88c2b1db886fdb6ab92f --- /dev/null +++ b/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam4.html @@ -0,0 +1,4182 @@ +subject4_h1_7_cam4

subject4_h1_7_cam4

直接读取 v1.1 bundle;预览只作人工核查。手/物体点来自源 3D 标注,仅为显示投影到 RGB;未生成新 UV、分割或接触标注。

帧 0 / 584

原生 RGB(仅预览缩放)
RGB + 原生 3D 关键点投影(仅预览:keypoints_xyz #00e6ff, points_cocoa #ff48a4)
深度 Z,黑=无效,白≥3 m;不改源深度
原深度逐像素 valid:白=有效,黑=无效,不是深度值
原帧号、全部数值标注及有效性
{
+  "frame": {
+    "source_frame_id": 0,
+    "sync_id": "subject4/h1/7:0",
+    "source_locator": {
+      "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+      "member": "subject4/h1/7/cam4/rgb/000000.png",
+      "sha256": "3f2d97038f34886535a6df5de254a1fd7246c471b8cfb0b766188d9a017a7c2e"
+    },
+    "component_sources": {
+      "hand_pose_mano": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/hand_pose_mano/000000.txt",
+        "sha256": "1b0f5af1dca065c9cd812078f7fdf288c0aaa1e1ceba5010812db2e09dcc9a79"
+      },
+      "hand_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/hand_pose/000000.txt",
+        "sha256": "5912dd6695784f23dfc2733c65585a41490d227fcec1f6301ff2cac95491063d"
+      },
+      "depth": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/depth/000000.png",
+        "sha256": "aade4a8cf395f3de43cf541e44bfee8d3902ef8ac50727c7ce9325378effd60d"
+      },
+      "cam_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/cam_pose/000000.txt",
+        "sha256": "3aaaebfd69835ddc19587e77044b718530483ea5d09bb639d41efc847735a7e4"
+      },
+      "obj_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/obj_pose/000000.txt",
+        "sha256": "8de58a392f88549321ad07ac46b328fb63ed6551b6cc74184f5f2a73b89be7c2"
+      },
+      "obj_pose_rt": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/obj_pose_rt/000000.txt",
+        "sha256": "8ceee38f2c2d1a36e6ca86fb04e63d3b66c85a8dccb2ce865dbf32e797d6d314"
+      },
+      "rgb": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/rgb/000000.png",
+        "sha256": "3f2d97038f34886535a6df5de254a1fd7246c471b8cfb0b766188d9a017a7c2e"
+      }
+    },
+    "annotation_matches": {
+      "hand_pose_mano": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "hand_pose": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "depth": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "cam_pose": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose_rt": {
+        "source_frame_id": 0,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      }
+    },
+    "frame_index": 0,
+    "timestamp_ns": null,
+    "clock_domain": null
+  },
+  "rgb_valid": true,
+  "intrinsic": {
+    "value": [
+      [
+        636.6593017578125,
+        0.0,
+        635.2838745117188
+      ],
+      [
+        0.0,
+        636.251953125,
+        366.8740234375
+      ],
+      [
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "extrinsic": {
+    "value": [
+      [
+        0.9997727274894714,
+        0.0060347444377839565,
+        -0.020451098680496216,
+        0.0032945063430815935
+      ],
+      [
+        -0.006354047451168299,
+        0.9998583793640137,
+        -0.015584171749651432,
+        -0.007256696000695229
+      ],
+      [
+        0.020354149863123894,
+        0.015710240229964256,
+        0.9996694922447205,
+        -0.03010079823434353
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "mano": {
+    "value": [
+      [
+        -1.9956263303756714,
+        1.878720998764038,
+        -0.3258252441883087,
+        0.004794743377715349,
+        0.1707584261894226,
+        -0.6018233895301819,
+        0.1699988692998886,
+        -0.00020761990163009614,
+        -0.7155240774154663,
+        -0.047670040279626846,
+        0.010327726602554321,
+        -0.1493668556213379,
+        -0.08601675927639008,
+        -0.03311705216765404,
+        -0.8589394092559814,
+        -0.21975138783454895,
+        0.030946308746933937,
+        -0.5646840333938599,
+        -0.005143176298588514,
+        -0.0020604562014341354,
+        -0.3331383466720581,
+        -0.4338557720184326,
+        -0.37572646141052246,
+        -0.5886749625205994,
+        -0.31636539101600647,
+        0.008779612369835377,
+        -0.4466293454170227,
+        -0.07524889707565308,
+        -0.0031842770986258984,
+        -0.23183982074260712,
+        -0.1047976166009903,
+        -0.18011412024497986,
+        -0.6970809698104858,
+        -0.30140432715415955,
+        -0.03360113874077797,
+        -0.5651438236236572,
+        -0.043166544288396835,
+        -0.045574817806482315,
+        -0.4815016984939575,
+        0.8711068034172058,
+        0.3190931975841522,
+        -0.1111631914973259,
+        -0.2661822438240051,
+        0.06150209903717041,
+        0.015476319938898087,
+        0.08050798624753952,
+        -0.06933743506669998,
+        -0.38123515248298645,
+        -0.2806254029273987,
+        1.476506233215332,
+        -0.6854744553565979,
+        0.16803301870822906,
+        -0.18744522333145142,
+        -0.5487542748451233,
+        -2.63431978225708,
+        -0.5607357025146484,
+        -2.1435391902923584,
+        -0.6932340264320374,
+        -0.08790842443704605,
+        0.17496360838413239,
+        0.40804189443588257
+      ],
+      [
+        -1.8155182600021362,
+        -1.8646996021270752,
+        0.2076154351234436,
+        0.039051394909620285,
+        -0.37876221537590027,
+        0.19084596633911133,
+        0.15678124129772186,
+        -0.08973533660173416,
+        0.6323488354682922,
+        -0.03988899290561676,
+        -0.02587687410414219,
+        0.3320583999156952,
+        -0.059423819184303284,
+        -0.21750974655151367,
+        0.7102867364883423,
+        -0.19489334523677826,
+        -0.012446731328964233,
+        0.47452813386917114,
+        0.0021097674034535885,
+        -0.028252437710762024,
+        0.11033516377210617,
+        -0.17313151061534882,
+        0.36597415804862976,
+        0.37573477625846863,
+        -0.3820681869983673,
+        0.00449522165581584,
+        0.591370165348053,
+        -0.055342692881822586,
+        0.03855744004249573,
+        0.3542528748512268,
+        -0.03029007650911808,
+        0.04169467091560364,
+        0.5991495847702026,
+        -0.3130511939525604,
+        0.007519695907831192,
+        0.6511586308479309,
+        -0.008511385880410671,
+        0.030142562463879585,
+        0.3059384822845459,
+        0.6466566324234009,
+        0.019822046160697937,
+        0.19402238726615906,
+        -0.09911049902439117,
+        0.16130289435386658,
+        0.20247028768062592,
+        0.055118627846241,
+        -0.013596867211163044,
+        0.24345824122428894,
+        -0.4555988311767578,
+        0.13637742400169373,
+        0.8111323714256287,
+        -2.9508821964263916,
+        0.06259849667549133,
+        -1.952202320098877,
+        -3.399379253387451,
+        0.6082465648651123,
+        -1.1187307834625244,
+        -0.8084438443183899,
+        0.11760370433330536,
+        0.029178205877542496,
+        0.34338727593421936
+      ]
+    ],
+    "valid": [
+      true,
+      true
+    ]
+  },
+  "keypoints_xyz": {
+    "value": [
+      [
+        [
+          -0.18225155770778656,
+          0.1819087564945221,
+          0.4139183461666107
+        ],
+        [
+          -0.1530817449092865,
+          0.16289250552654266,
+          0.3953249454498291
+        ],
+        [
+          -0.13064058125019073,
+          0.1412564069032669,
+          0.39196792244911194
+        ],
+        [
+          -0.11840793490409851,
+          0.11798742413520813,
+          0.39432841539382935
+        ],
+        [
+          -0.09689095616340637,
+          0.0965580940246582,
+          0.4040410816669464
+        ],
+        [
+          -0.161177858710289,
+          0.09887068718671799,
+          0.38758376240730286
+        ],
+        [
+          -0.14747479557991028,
+          0.0699436292052269,
+          0.3944726884365082
+        ],
+        [
+          -0.12986443936824799,
+          0.06625032424926758,
+          0.40702229738235474
+        ],
+        [
+          -0.1091851219534874,
+          0.06416495889425278,
+          0.41693490743637085
+        ],
+        [
+          -0.17468594014644623,
+          0.0889425203204155,
+          0.40781694650650024
+        ],
+        [
+          -0.1548573523759842,
+          0.06681191176176071,
+          0.4199877679347992
+        ],
+        [
+          -0.1341329663991928,
+          0.06636148691177368,
+          0.43120741844177246
+        ],
+        [
+          -0.11165981739759445,
+          0.06815740466117859,
+          0.4416104853153229
+        ],
+        [
+          -0.18228097259998322,
+          0.09855601191520691,
+          0.4320286512374878
+        ],
+        [
+          -0.16502831876277924,
+          0.07493738830089569,
+          0.438320130109787
+        ],
+        [
+          -0.14282143115997314,
+          0.07258857041597366,
+          0.4495108127593994
+        ],
+        [
+          -0.11979024112224579,
+          0.07403001934289932,
+          0.45836302638053894
+        ],
+        [
+          -0.18423086404800415,
+          0.11022191494703293,
+          0.45108428597450256
+        ],
+        [
+          -0.17173448204994202,
+          0.09441370517015457,
+          0.45790550112724304
+        ],
+        [
+          -0.15407420694828033,
+          0.08949235826730728,
+          0.4641416370868683
+        ],
+        [
+          -0.13685739040374756,
+          0.08614275604486465,
+          0.47030317783355713
+        ]
+      ],
+      [
+        [
+          0.21412576735019684,
+          0.03597656264901161,
+          0.34975457191467285
+        ],
+        [
+          0.18581415712833405,
+          0.017052479088306427,
+          0.3282591700553894
+        ],
+        [
+          0.1603618562221527,
+          0.0025762785226106644,
+          0.31470322608947754
+        ],
+        [
+          0.1370059996843338,
+          -0.012413948774337769,
+          0.31228286027908325
+        ],
+        [
+          0.10570808500051498,
+          -0.02769729681313038,
+          0.3164469599723816
+        ],
+        [
+          0.19574692845344543,
+          -0.0419047512114048,
+          0.31024688482284546
+        ],
+        [
+          0.19711942970752716,
+          -0.07423242181539536,
+          0.3111984431743622
+        ],
+        [
+          0.18688419461250305,
+          -0.08916526287794113,
+          0.3239143490791321
+        ],
+        [
+          0.17033368349075317,
+          -0.09999112039804459,
+          0.3360236585140228
+        ],
+        [
+          0.21038970351219177,
+          -0.055220168083906174,
+          0.3272353708744049
+        ],
+        [
+          0.19817499816417694,
+          -0.08386892825365067,
+          0.33980756998062134
+        ],
+        [
+          0.18009011447429657,
+          -0.09293613582849503,
+          0.3532799482345581
+        ],
+        [
+          0.15921369194984436,
+          -0.10045003890991211,
+          0.36948877573013306
+        ],
+        [
+          0.2199942022562027,
+          -0.05022435262799263,
+          0.3529902994632721
+        ],
+        [
+          0.20875132083892822,
+          -0.07772230356931686,
+          0.35750019550323486
+        ],
+        [
+          0.1876043826341629,
+          -0.08442997187376022,
+          0.372259259223938
+        ],
+        [
+          0.1677222102880478,
+          -0.09017576277256012,
+          0.38486698269844055
+        ],
+        [
+          0.22212131321430206,
+          -0.04335564747452736,
+          0.3748156726360321
+        ],
+        [
+          0.21630416810512543,
+          -0.0648442953824997,
+          0.3793633282184601
+        ],
+        [
+          0.2002842128276825,
+          -0.07419604808092117,
+          0.38769644498825073
+        ],
+        [
+          0.18391826748847961,
+          -0.07906457036733627,
+          0.3959386348724365
+        ]
+      ]
+    ],
+    "valid": [
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ],
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ]
+    ]
+  },
+  "pose_cocoa": {
+    "value": [
+      [
+        0.473866730928421,
+        -0.8804492950439453,
+        -0.01612846925854683,
+        0.13061803579330444
+      ],
+      [
+        -0.8536989688873291,
+        -0.45482319593429565,
+        -0.25364264845848083,
+        -0.04936354607343674
+      ],
+      [
+        0.21598343551158905,
+        0.1339617371559143,
+        -0.9671636819839478,
+        0.3988461494445801
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "points_cocoa": {
+    "value": [
+      [
+        0.13061803579330444,
+        -0.04936354607343674,
+        0.3988461494445801
+      ],
+      [
+        0.10761615633964539,
+        -0.12382929027080536,
+        0.343050092458725
+      ],
+      [
+        0.06911881268024445,
+        -0.054474037140607834,
+        0.325503408908844
+      ],
+      [
+        0.07148074358701706,
+        -0.01732931099832058,
+        0.4671398103237152
+      ],
+      [
+        0.1099780946969986,
+        -0.08668456971645355,
+        0.4846864938735962
+      ],
+      [
+        0.18975532054901123,
+        -0.08139777928590775,
+        0.33055248856544495
+      ],
+      [
+        0.1512579768896103,
+        -0.012042523361742496,
+        0.31300583481788635
+      ],
+      [
+        0.1536199003458023,
+        0.025102203711867332,
+        0.4546422064304352
+      ],
+      [
+        0.19211725890636444,
+        -0.04425305128097534,
+        0.47218888998031616
+      ],
+      [
+        0.08836748450994492,
+        -0.08915166556835175,
+        0.3342767655849457
+      ],
+      [
+        0.17050664126873016,
+        -0.046720150858163834,
+        0.32177916169166565
+      ],
+      [
+        0.17286857962608337,
+        -0.00957542471587658,
+        0.46341556310653687
+      ],
+      [
+        0.09072942286729813,
+        -0.05200693756341934,
+        0.4759131669998169
+      ],
+      [
+        0.1486857384443283,
+        -0.10261353850364685,
+        0.33680129051208496
+      ],
+      [
+        0.11018838733434677,
+        -0.03325828164815903,
+        0.319254606962204
+      ],
+      [
+        0.11255032569169998,
+        0.003886446123942733,
+        0.4608910083770752
+      ],
+      [
+        0.15104767680168152,
+        -0.06546881049871445,
+        0.4784376919269562
+      ],
+      [
+        0.10879712551832199,
+        -0.10525692999362946,
+        0.4138683080673218
+      ],
+      [
+        0.07029977440834045,
+        -0.03590167313814163,
+        0.3963216245174408
+      ],
+      [
+        0.1524389386177063,
+        0.006529839709401131,
+        0.38382402062416077
+      ],
+      [
+        0.19093628227710724,
+        -0.06282541900873184,
+        0.40137070417404175
+      ]
+    ],
+    "valid": [
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true
+    ]
+  }
+}

帧 146 / 584

原生 RGB(仅预览缩放)
RGB + 原生 3D 关键点投影(仅预览:keypoints_xyz #00e6ff, points_cocoa #ff48a4)
深度 Z,黑=无效,白≥3 m;不改源深度
原深度逐像素 valid:白=有效,黑=无效,不是深度值
原帧号、全部数值标注及有效性
{
+  "frame": {
+    "source_frame_id": 146,
+    "sync_id": "subject4/h1/7:146",
+    "source_locator": {
+      "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+      "member": "subject4/h1/7/cam4/rgb/000146.png",
+      "sha256": "55769e3de9a2a72023ef642e4eebaf98dadc875bb14b169a926bd23b94117bec"
+    },
+    "component_sources": {
+      "hand_pose_mano": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/hand_pose_mano/000146.txt",
+        "sha256": "225b10f327bea46e30ea37f977d3593f195acaf039a399f8acf62654fb255560"
+      },
+      "hand_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/hand_pose/000146.txt",
+        "sha256": "8eed8ff164d32a59071db1b59212fbf77ceda39f7ec942433ac2bf20496ff793"
+      },
+      "depth": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/depth/000146.png",
+        "sha256": "c8b43e1abbd7bf862dd00490e38635fa35d5810c96e0caaf44ef5a67200396a3"
+      },
+      "cam_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/cam_pose/000146.txt",
+        "sha256": "157c1a578f53d2f0cafc7e9a7ffd240f2ab55eab9e82b9e8df1dffaf03b8bc7c"
+      },
+      "obj_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/obj_pose/000146.txt",
+        "sha256": "901585f185ab1c6e05bc8315f0808cc607a0642f693000824338e97a3ad8550c"
+      },
+      "obj_pose_rt": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/obj_pose_rt/000146.txt",
+        "sha256": "12df98f62c7d7949ea322960a1775eb6f1b9af24cb3d196407e0709a7b5abe2a"
+      },
+      "rgb": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/rgb/000146.png",
+        "sha256": "55769e3de9a2a72023ef642e4eebaf98dadc875bb14b169a926bd23b94117bec"
+      }
+    },
+    "annotation_matches": {
+      "hand_pose_mano": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "hand_pose": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "depth": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "cam_pose": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose_rt": {
+        "source_frame_id": 146,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      }
+    },
+    "frame_index": 146,
+    "timestamp_ns": null,
+    "clock_domain": null
+  },
+  "rgb_valid": true,
+  "intrinsic": {
+    "value": [
+      [
+        636.6593017578125,
+        0.0,
+        635.2838745117188
+      ],
+      [
+        0.0,
+        636.251953125,
+        366.8740234375
+      ],
+      [
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "extrinsic": {
+    "value": [
+      [
+        0.9988685250282288,
+        0.04643140360713005,
+        -0.010296531021595001,
+        -0.01663155108690262
+      ],
+      [
+        -0.04667479544878006,
+        0.9986019730567932,
+        -0.024812500923871994,
+        0.008029008284211159
+      ],
+      [
+        0.009130051359534264,
+        0.025264674797654152,
+        0.9996392130851746,
+        -0.037361957132816315
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "mano": {
+    "value": [
+      [
+        -1.7798776626586914,
+        2.2693533897399902,
+        -0.44388875365257263,
+        0.04427279531955719,
+        0.26809507608413696,
+        0.045330096036195755,
+        -0.045739151537418365,
+        0.032967399805784225,
+        -0.27929994463920593,
+        0.006416820455342531,
+        0.03520970791578293,
+        -0.30499789118766785,
+        0.00784309022128582,
+        0.14051397144794464,
+        -0.129643052816391,
+        -0.21528618037700653,
+        -0.006156093440949917,
+        -0.46771693229675293,
+        -0.009763075970113277,
+        0.005931627005338669,
+        -0.3510958254337311,
+        -0.1256943643093109,
+        -0.27854663133621216,
+        -0.23620522022247314,
+        -0.23329922556877136,
+        0.02548634447157383,
+        -0.29687410593032837,
+        -0.053570929914712906,
+        -0.020346179604530334,
+        -0.06065757945179939,
+        0.02076874114573002,
+        -0.0008505195728503168,
+        -0.21260634064674377,
+        -0.23882624506950378,
+        0.002423439873382449,
+        -0.34939178824424744,
+        -0.03549252077937126,
+        -0.05985437333583832,
+        -0.3917539715766907,
+        0.8870458602905273,
+        0.05347927659749985,
+        -0.231246680021286,
+        -0.3195331394672394,
+        -0.013767085038125515,
+        0.047401413321495056,
+        0.07033149898052216,
+        -0.007284601218998432,
+        -0.36428308486938477,
+        -0.2806254029273987,
+        1.476506233215332,
+        -0.6854744553565979,
+        0.16803301870822906,
+        -0.18744522333145142,
+        -0.5487542748451233,
+        -2.63431978225708,
+        -0.5607357025146484,
+        -2.1435391902923584,
+        -0.6932340264320374,
+        0.07655326277017593,
+        0.06865650415420532,
+        0.5136125683784485
+      ],
+      [
+        -2.11118745803833,
+        -1.481785535812378,
+        0.6683292984962463,
+        0.05228615552186966,
+        -0.3141782581806183,
+        0.18577824532985687,
+        0.014561057090759277,
+        -0.0456886850297451,
+        0.27550026774406433,
+        -0.011011692695319653,
+        -0.04303039610385895,
+        0.1838967353105545,
+        -0.01344660110771656,
+        -0.19626811146736145,
+        0.3888801336288452,
+        -0.20499096810817719,
+        -0.013293411582708359,
+        0.3958682715892792,
+        0.003251946996897459,
+        -0.036050885915756226,
+        0.290199875831604,
+        -0.3222946226596832,
+        0.4271879196166992,
+        0.45480868220329285,
+        -0.10017793625593185,
+        -0.05947145074605942,
+        0.2771100103855133,
+        -0.04022855684161186,
+        0.008191186003386974,
+        0.03122820146381855,
+        -0.01720811426639557,
+        0.0541866160929203,
+        0.4702620208263397,
+        -0.23846480250358582,
+        -0.02290438860654831,
+        0.32519856095314026,
+        -0.029706012457609177,
+        0.020899150520563126,
+        0.4011497497558594,
+        1.076732873916626,
+        -0.22445835173130035,
+        0.2684323489665985,
+        -0.34135475754737854,
+        0.16551639139652252,
+        -0.05739152431488037,
+        0.047952648252248764,
+        0.05909768119454384,
+        0.35264596343040466,
+        -0.4555988311767578,
+        0.13637742400169373,
+        0.8111323714256287,
+        -2.9508821964263916,
+        0.06259849667549133,
+        -1.952202320098877,
+        -3.399379253387451,
+        0.6082465648651123,
+        -1.1187307834625244,
+        -0.8084438443183899,
+        0.02881816029548645,
+        0.01644871011376381,
+        0.4318814277648926
+      ]
+    ],
+    "valid": [
+      true,
+      true
+    ]
+  },
+  "keypoints_xyz": {
+    "value": [
+      [
+        [
+          -0.017789864912629128,
+          0.07560165226459503,
+          0.5194889903068542
+        ],
+        [
+          0.002362942323088646,
+          0.04685927554965019,
+          0.501434862613678
+        ],
+        [
+          0.023382877930998802,
+          0.024071479216217995,
+          0.4967578649520874
+        ],
+        [
+          0.035580337047576904,
+          0.0006701350212097168,
+          0.49625399708747864
+        ],
+        [
+          0.056513458490371704,
+          -0.022418934851884842,
+          0.5027524828910828
+        ],
+        [
+          -0.025839073583483696,
+          -0.011694695800542831,
+          0.5008478760719299
+        ],
+        [
+          -0.04153567552566528,
+          -0.040121082216501236,
+          0.5050386786460876
+        ],
+        [
+          -0.04337083920836449,
+          -0.05990109592676163,
+          0.5143467783927917
+        ],
+        [
+          -0.039462484419345856,
+          -0.0813647136092186,
+          0.5222758054733276
+        ],
+        [
+          -0.04001663625240326,
+          -0.015133315697312355,
+          0.5227017998695374
+        ],
+        [
+          -0.05029340088367462,
+          -0.04338501766324043,
+          0.5339842438697815
+        ],
+        [
+          -0.04314026981592178,
+          -0.06295309215784073,
+          0.5450072884559631
+        ],
+        [
+          -0.03274865075945854,
+          -0.0828428864479065,
+          0.5556582808494568
+        ],
+        [
+          -0.042191728949546814,
+          -0.001658812165260315,
+          0.5461541414260864
+        ],
+        [
+          -0.04835023358464241,
+          -0.029780946671962738,
+          0.5542963147163391
+        ],
+        [
+          -0.0405636802315712,
+          -0.04949004203081131,
+          0.5675181150436401
+        ],
+        [
+          -0.03062768094241619,
+          -0.06942916661500931,
+          0.5783759951591492
+        ],
+        [
+          -0.03881654515862465,
+          0.011541918851435184,
+          0.5639688372612
+        ],
+        [
+          -0.041098564863204956,
+          -0.007753754034638405,
+          0.572632372379303
+        ],
+        [
+          -0.03530896082520485,
+          -0.02367650903761387,
+          0.58201003074646
+        ],
+        [
+          -0.03102084808051586,
+          -0.040032096207141876,
+          0.5911240577697754
+        ]
+      ],
+      [
+        [
+          0.12534022331237793,
+          0.023247068747878075,
+          0.4382486641407013
+        ],
+        [
+          0.08896031975746155,
+          0.007477756589651108,
+          0.4312093257904053
+        ],
+        [
+          0.06187959387898445,
+          -0.004693536087870598,
+          0.44384410977363586
+        ],
+        [
+          0.040430471301078796,
+          -0.018622802570462227,
+          0.4548881947994232
+        ],
+        [
+          0.013667890802025795,
+          -0.02676112949848175,
+          0.4756481349468231
+        ],
+        [
+          0.08168685436248779,
+          -0.05447525531053543,
+          0.43403396010398865
+        ],
+        [
+          0.07560636848211288,
+          -0.08442935347557068,
+          0.44469451904296875
+        ],
+        [
+          0.06804557144641876,
+          -0.09875605255365372,
+          0.4597618579864502
+        ],
+        [
+          0.05594237521290779,
+          -0.11208487302064896,
+          0.4746895432472229
+        ],
+        [
+          0.09768567234277725,
+          -0.06564431637525558,
+          0.4513431787490845
+        ],
+        [
+          0.08970305323600769,
+          -0.09222166985273361,
+          0.4702622890472412
+        ],
+        [
+          0.0765938088297844,
+          -0.10086975246667862,
+          0.4888133704662323
+        ],
+        [
+          0.059939514845609665,
+          -0.1031167209148407,
+          0.5104121565818787
+        ],
+        [
+          0.11501464247703552,
+          -0.0560774989426136,
+          0.47105878591537476
+        ],
+        [
+          0.10222090035676956,
+          -0.07932788878679276,
+          0.485152006149292
+        ],
+        [
+          0.0868551954627037,
+          -0.08711118996143341,
+          0.50548255443573
+        ],
+        [
+          0.07152567058801651,
+          -0.09164386242628098,
+          0.5236427187919617
+        ],
+        [
+          0.12456919252872467,
+          -0.04388431832194328,
+          0.48803192377090454
+        ],
+        [
+          0.1130707785487175,
+          -0.058648500591516495,
+          0.5009194016456604
+        ],
+        [
+          0.0994294136762619,
+          -0.06596275418996811,
+          0.514108419418335
+        ],
+        [
+          0.08588723093271255,
+          -0.07469352334737778,
+          0.5267765522003174
+        ]
+      ]
+    ],
+    "valid": [
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ],
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ]
+    ]
+  },
+  "pose_cocoa": {
+    "value": [
+      [
+        0.46548157930374146,
+        -0.8691049218177795,
+        -0.16728588938713074,
+        0.023237407207489014
+      ],
+      [
+        -0.860645055770874,
+        -0.4003962278366089,
+        -0.3146006464958191,
+        -0.045042816549539566
+      ],
+      [
+        0.20644031465053558,
+        0.2904147505760193,
+        -0.9343670010566711,
+        0.5521035194396973
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "points_cocoa": {
+    "value": [
+      [
+        0.023237407207489014,
+        -0.045042816549539566,
+        0.5521035194396973
+      ],
+      [
+        -0.01064403634518385,
+        -0.12171541154384613,
+        0.5056192278862
+      ],
+      [
+        -0.04846016690135002,
+        -0.051795851439237595,
+        0.48884785175323486
+      ],
+      [
+        -0.02396196871995926,
+        -0.0057241227477788925,
+        0.6256813406944275
+      ],
+      [
+        0.013854162767529488,
+        -0.07564368098974228,
+        0.6424527168273926
+      ],
+      [
+        0.07043678313493729,
+        -0.08436151593923569,
+        0.4785257577896118
+      ],
+      [
+        0.03262064978480339,
+        -0.014441956765949726,
+        0.46175438165664673
+      ],
+      [
+        0.05711884796619415,
+        0.0316297709941864,
+        0.5985878705978394
+      ],
+      [
+        0.09493497759103775,
+        -0.038289785385131836,
+        0.6153592467308044
+      ],
+      [
+        -0.029552102088928223,
+        -0.08675563335418701,
+        0.4972335398197174
+      ],
+      [
+        0.05152871459722519,
+        -0.04940173402428627,
+        0.4701400697231293
+      ],
+      [
+        0.07602691650390625,
+        -0.00333000672981143,
+        0.6069735288619995
+      ],
+      [
+        -0.005053902510553598,
+        -0.04068390280008316,
+        0.6340669989585876
+      ],
+      [
+        0.02989637292921543,
+        -0.10303846001625061,
+        0.4920724928379059
+      ],
+      [
+        -0.007919758558273315,
+        -0.03311890363693237,
+        0.4753011167049408
+      ],
+      [
+        0.016578441485762596,
+        0.012952824123203754,
+        0.612134575843811
+      ],
+      [
+        0.05439457297325134,
+        -0.05696673318743706,
+        0.6289059519767761
+      ],
+      [
+        0.0016050632111728191,
+        -0.0986795425415039,
+        0.5740359425544739
+      ],
+      [
+        -0.03621106594800949,
+        -0.028759988024830818,
+        0.5572645664215088
+      ],
+      [
+        0.04486975073814392,
+        0.008593907579779625,
+        0.5301710963249207
+      ],
+      [
+        0.08268588036298752,
+        -0.06132565066218376,
+        0.5469425320625305
+      ]
+    ],
+    "valid": [
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true
+    ]
+  }
+}

帧 292 / 584

原生 RGB(仅预览缩放)
RGB + 原生 3D 关键点投影(仅预览:keypoints_xyz #00e6ff, points_cocoa #ff48a4)
深度 Z,黑=无效,白≥3 m;不改源深度
原深度逐像素 valid:白=有效,黑=无效,不是深度值
原帧号、全部数值标注及有效性
{
+  "frame": {
+    "source_frame_id": 292,
+    "sync_id": "subject4/h1/7:292",
+    "source_locator": {
+      "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+      "member": "subject4/h1/7/cam4/rgb/000292.png",
+      "sha256": "68cc5b3aba29d70b74f9730cbb9784c9ba55a5f3f8dd4365516a4a8fa6028e73"
+    },
+    "component_sources": {
+      "hand_pose_mano": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/hand_pose_mano/000292.txt",
+        "sha256": "ce4dcc32f1896cc909801b5fb48d122100a54edeb2c469739f60248030e0fe06"
+      },
+      "hand_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/hand_pose/000292.txt",
+        "sha256": "2805810aeba58eb1a25122e301d64426d97ee6db7f236c4446b2b84c8f3dde83"
+      },
+      "depth": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/depth/000292.png",
+        "sha256": "5dceda5ba0e6aba4bc0eff0ce160c1fbf3fdd2a21a0c14e4d9bd3ddcef4d67ce"
+      },
+      "cam_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/cam_pose/000292.txt",
+        "sha256": "8361e55572ac354156bbb58c55be1598db3470e5e511709536f52f134df49b4f"
+      },
+      "obj_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/obj_pose/000292.txt",
+        "sha256": "abb58ec971c8627b387141fb909cf07de20d684238978534afd8b99a34a02b9f"
+      },
+      "obj_pose_rt": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/obj_pose_rt/000292.txt",
+        "sha256": "5dbbf2a4f1715bd6d7b325b3494222b8d2d632e1fb67445b52729a2a9af20f2f"
+      },
+      "rgb": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/rgb/000292.png",
+        "sha256": "68cc5b3aba29d70b74f9730cbb9784c9ba55a5f3f8dd4365516a4a8fa6028e73"
+      }
+    },
+    "annotation_matches": {
+      "hand_pose_mano": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "hand_pose": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "depth": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "cam_pose": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose_rt": {
+        "source_frame_id": 292,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      }
+    },
+    "frame_index": 292,
+    "timestamp_ns": null,
+    "clock_domain": null
+  },
+  "rgb_valid": true,
+  "intrinsic": {
+    "value": [
+      [
+        636.6593017578125,
+        0.0,
+        635.2838745117188
+      ],
+      [
+        0.0,
+        636.251953125,
+        366.8740234375
+      ],
+      [
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "extrinsic": {
+    "value": [
+      [
+        0.9952535629272461,
+        0.09078129380941391,
+        -0.03506235033273697,
+        -0.028113611042499542
+      ],
+      [
+        -0.09156396239995956,
+        0.9955692887306213,
+        -0.021398544311523438,
+        -0.007046691607683897
+      ],
+      [
+        0.03296440467238426,
+        0.024507084861397743,
+        0.99915611743927,
+        -0.02516326494514942
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "mano": {
+    "value": [
+      [
+        -2.1897175312042236,
+        2.13486909866333,
+        -0.011984213255345821,
+        0.05670445039868355,
+        0.25673824548721313,
+        0.05390062928199768,
+        -0.011501568369567394,
+        0.044752590358257294,
+        -0.36865484714508057,
+        0.002329871989786625,
+        0.020953018218278885,
+        -0.4384158253669739,
+        0.004928406327962875,
+        0.16468551754951477,
+        -0.04126213490962982,
+        -0.25341796875,
+        -0.0038572056218981743,
+        -0.6761335134506226,
+        -0.009948598220944405,
+        0.018649278208613396,
+        -0.5019798874855042,
+        -0.24138857424259186,
+        -0.1614977866411209,
+        -0.09372156858444214,
+        0.14770151674747467,
+        0.056116294115781784,
+        -0.12757499516010284,
+        -0.047184936702251434,
+        -0.004884934984147549,
+        0.019028406590223312,
+        -0.022903690114617348,
+        -0.005811681039631367,
+        -0.12458775192499161,
+        -0.23412154614925385,
+        0.01715666800737381,
+        -0.2998145818710327,
+        -0.012882375158369541,
+        -0.04756156727671623,
+        -0.460102379322052,
+        1.1249886751174927,
+        -0.01869778335094452,
+        -0.41282445192337036,
+        -0.20248471200466156,
+        0.02288021706044674,
+        0.024625735357403755,
+        0.07889742404222488,
+        0.02330283634364605,
+        -0.5219765901565552,
+        -0.2806254029273987,
+        1.476506233215332,
+        -0.6854744553565979,
+        0.16803301870822906,
+        -0.18744522333145142,
+        -0.5487542748451233,
+        -2.63431978225708,
+        -0.5607357025146484,
+        -2.1435391902923584,
+        -0.6932340264320374,
+        0.018225159496068954,
+        0.06938200443983078,
+        0.521144449710846
+      ],
+      [
+        -1.5716665983200073,
+        -1.6822508573532104,
+        0.6814653873443604,
+        0.038850054144859314,
+        -0.2796785235404968,
+        0.7232538461685181,
+        0.1962374448776245,
+        0.008065328001976013,
+        0.8089422583580017,
+        -0.03829491138458252,
+        0.013623629696667194,
+        0.3365393280982971,
+        -0.07450265437364578,
+        0.017885863780975342,
+        0.9586271643638611,
+        -0.23017618060112,
+        -0.0407082624733448,
+        0.6756982207298279,
+        -0.011619498021900654,
+        0.004039316903799772,
+        0.5732011795043945,
+        -0.5500652194023132,
+        0.3716382086277008,
+        0.3936295807361603,
+        -0.34403276443481445,
+        0.012122486717998981,
+        0.5724484324455261,
+        -0.08576078712940216,
+        0.04578283056616783,
+        0.45880401134490967,
+        -0.26148533821105957,
+        0.14884883165359497,
+        0.8358225226402283,
+        -0.31061968207359314,
+        0.05572012811899185,
+        0.563292920589447,
+        -0.02641027607023716,
+        0.06818082183599472,
+        0.48979705572128296,
+        1.0069056749343872,
+        -0.3729687035083771,
+        0.10506514459848404,
+        -0.30229654908180237,
+        -0.143685981631279,
+        -0.05555962771177292,
+        0.0849929228425026,
+        -0.059027161449193954,
+        0.37952637672424316,
+        -0.4555988311767578,
+        0.13637742400169373,
+        0.8111323714256287,
+        -2.9508821964263916,
+        0.06259849667549133,
+        -1.952202320098877,
+        -3.399379253387451,
+        0.6082465648651123,
+        -1.1187307834625244,
+        -0.8084438443183899,
+        0.12763115763664246,
+        0.03708997741341591,
+        0.424950510263443
+      ]
+    ],
+    "valid": [
+      true,
+      true
+    ]
+  },
+  "keypoints_xyz": {
+    "value": [
+      [
+        [
+          -0.07611797004938126,
+          0.07632715255022049,
+          0.5270209312438965
+        ],
+        [
+          -0.05598612129688263,
+          0.05537843331694603,
+          0.5002988576889038
+        ],
+        [
+          -0.027415728196501732,
+          0.044642433524131775,
+          0.4931248128414154
+        ],
+        [
+          -0.005987999029457569,
+          0.029231460765004158,
+          0.4932202100753784
+        ],
+        [
+          0.0223649013787508,
+          0.02087746188044548,
+          0.5036856532096863
+        ],
+        [
+          -0.0673108622431755,
+          -0.008619964122772217,
+          0.49982988834381104
+        ],
+        [
+          -0.07352893054485321,
+          -0.04049926996231079,
+          0.5039591789245605
+        ],
+        [
+          -0.0658312737941742,
+          -0.0598229356110096,
+          0.5109304785728455
+        ],
+        [
+          -0.05035945028066635,
+          -0.07666637748479843,
+          0.5142855048179626
+        ],
+        [
+          -0.07269588857889175,
+          -0.017038386315107346,
+          0.5241311192512512
+        ],
+        [
+          -0.0742730051279068,
+          -0.04738990589976311,
+          0.5344927310943604
+        ],
+        [
+          -0.0572035126388073,
+          -0.06275680661201477,
+          0.5397912859916687
+        ],
+        [
+          -0.035498518496751785,
+          -0.07394149899482727,
+          0.5428363680839539
+        ],
+        [
+          -0.0708310529589653,
+          -0.005964562296867371,
+          0.5488333702087402
+        ],
+        [
+          -0.06911695003509521,
+          -0.03534446284174919,
+          0.5542148351669312
+        ],
+        [
+          -0.05510498210787773,
+          -0.05470854416489601,
+          0.5614668130874634
+        ],
+        [
+          -0.0387374572455883,
+          -0.07277631759643555,
+          0.5658010244369507
+        ],
+        [
+          -0.06554902344942093,
+          0.006699219811707735,
+          0.5665743350982666
+        ],
+        [
+          -0.06155337393283844,
+          -0.012477517127990723,
+          0.5748735070228577
+        ],
+        [
+          -0.05666092783212662,
+          -0.029367581009864807,
+          0.582984209060669
+        ],
+        [
+          -0.05458196997642517,
+          -0.04718698188662529,
+          0.5913702249526978
+        ]
+      ],
+      [
+        [
+          0.22415322065353394,
+          0.043888334184885025,
+          0.4313177764415741
+        ],
+        [
+          0.192464217543602,
+          0.019894026219844818,
+          0.42485228180885315
+        ],
+        [
+          0.17659734189510345,
+          -0.007260959129780531,
+          0.43206289410591125
+        ],
+        [
+          0.17435339093208313,
+          -0.03473268076777458,
+          0.43610405921936035
+        ],
+        [
+          0.17270633578300476,
+          -0.06490150839090347,
+          0.4531082808971405
+        ],
+        [
+          0.2022707462310791,
+          -0.03959808871150017,
+          0.408617228269577
+        ],
+        [
+          0.19602951407432556,
+          -0.06806635111570358,
+          0.4227052628993988
+        ],
+        [
+          0.1870473176240921,
+          -0.06987693905830383,
+          0.44284194707870483
+        ],
+        [
+          0.17364628612995148,
+          -0.06511145830154419,
+          0.4610467255115509
+        ],
+        [
+          0.2241668999195099,
+          -0.049304164946079254,
+          0.4189453721046448
+        ],
+        [
+          0.2121434360742569,
+          -0.07372322678565979,
+          0.4386216402053833
+        ],
+        [
+          0.19883139431476593,
+          -0.07274052500724792,
+          0.45893439650535583
+        ],
+        [
+          0.18570484220981598,
+          -0.057242218405008316,
+          0.4769100844860077
+        ],
+        [
+          0.2425212562084198,
+          -0.04033420979976654,
+          0.4380026161670685
+        ],
+        [
+          0.22982728481292725,
+          -0.0640782043337822,
+          0.45134297013282776
+        ],
+        [
+          0.2114548236131668,
+          -0.06639374792575836,
+          0.470503032207489
+        ],
+        [
+          0.19330237805843353,
+          -0.06393705308437347,
+          0.4860520362854004
+        ],
+        [
+          0.2522706687450409,
+          -0.030700676143169403,
+          0.45644697546958923
+        ],
+        [
+          0.24726474285125732,
+          -0.050797536969184875,
+          0.4657925069332123
+        ],
+        [
+          0.23246033489704132,
+          -0.05895943567156792,
+          0.4770950973033905
+        ],
+        [
+          0.2170010209083557,
+          -0.06067588925361633,
+          0.4874862730503082
+        ]
+      ]
+    ],
+    "valid": [
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ],
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ]
+    ]
+  },
+  "pose_cocoa": {
+    "value": [
+      [
+        0.8562021255493164,
+        -0.5149327516555786,
+        -0.04198933020234108,
+        -0.007132611703127623
+      ],
+      [
+        -0.4952082633972168,
+        -0.7947998642921448,
+        -0.3508026599884033,
+        -0.016430659219622612
+      ],
+      [
+        0.1472664624452591,
+        0.3211517930030823,
+        -0.9355074763298035,
+        0.5426945090293884
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "points_cocoa": {
+    "value": [
+      [
+        -0.007132611703127623,
+        -0.016430659219622612,
+        0.5426945090293884
+      ],
+      [
+        0.0005524893058463931,
+        -0.09930726885795593,
+        0.49515679478645325
+      ],
+      [
+        -0.06900612264871597,
+        -0.05907611548900604,
+        0.4831927418708801
+      ],
+      [
+        -0.06285698711872101,
+        -0.007702780421823263,
+        0.6201932430267334
+      ],
+      [
+        0.006701621226966381,
+        -0.04793393239378929,
+        0.6321573257446289
+      ],
+      [
+        0.04859176650643349,
+        -0.025158535689115524,
+        0.46519580483436584
+      ],
+      [
+        -0.020966844633221626,
+        0.015072616748511791,
+        0.4532317519187927
+      ],
+      [
+        -0.01481771282851696,
+        0.06644594669342041,
+        0.590232253074646
+      ],
+      [
+        0.05474089831113815,
+        0.02621479704976082,
+        0.6021962761878967
+      ],
+      [
+        -0.03422681614756584,
+        -0.07919169217348099,
+        0.4891747832298279
+      ],
+      [
+        0.013812460005283356,
+        -0.005042959935963154,
+        0.4592137932777405
+      ],
+      [
+        0.019961591809988022,
+        0.046330373734235764,
+        0.5962142944335938
+      ],
+      [
+        -0.028077684342861176,
+        -0.027818357571959496,
+        0.6261752843856812
+      ],
+      [
+        0.024572128430008888,
+        -0.06223290041089058,
+        0.48017629981040955
+      ],
+      [
+        -0.044986482709646225,
+        -0.02200174890458584,
+        0.4682122468948364
+      ],
+      [
+        -0.03883735090494156,
+        0.029371583834290504,
+        0.6052127480506897
+      ],
+      [
+        0.030721260234713554,
+        -0.010859567672014236,
+        0.6171768307685852
+      ],
+      [
+        0.003627055324614048,
+        -0.07362060248851776,
+        0.5636570453643799
+      ],
+      [
+        -0.06593155860900879,
+        -0.03338944539427757,
+        0.5516930222511292
+      ],
+      [
+        -0.017892278730869293,
+        0.04075928404927254,
+        0.521731972694397
+      ],
+      [
+        0.05166633054614067,
+        0.0005281304474920034,
+        0.5336960554122925
+      ]
+    ],
+    "valid": [
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true
+    ]
+  }
+}

帧 438 / 584

原生 RGB(仅预览缩放)
RGB + 原生 3D 关键点投影(仅预览:keypoints_xyz #00e6ff, points_cocoa #ff48a4)
深度 Z,黑=无效,白≥3 m;不改源深度
原深度逐像素 valid:白=有效,黑=无效,不是深度值
原帧号、全部数值标注及有效性
{
+  "frame": {
+    "source_frame_id": 438,
+    "sync_id": "subject4/h1/7:438",
+    "source_locator": {
+      "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+      "member": "subject4/h1/7/cam4/rgb/000438.png",
+      "sha256": "7ac22829b251d78f8133fdc7610d8006cf77d1b90b8c14e324a6b000a7dfe9e5"
+    },
+    "component_sources": {
+      "hand_pose_mano": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/hand_pose_mano/000438.txt",
+        "sha256": "d586596f38c5e7d1e41e280e236eae164e0011319ded71b12b640b6d9c69cfe3"
+      },
+      "hand_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/hand_pose/000438.txt",
+        "sha256": "0c563270eef86dfb127d98480e9671e8e9f7762394f8e3a13da9c7133b3f3af9"
+      },
+      "depth": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/depth/000438.png",
+        "sha256": "d062e833dbe2d7c8dce43cfc11a4aac0ff309648995853564abc85cfc6657fd3"
+      },
+      "cam_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/cam_pose/000438.txt",
+        "sha256": "8b683af20f3acd8b5736a8c51f9cca8f872c23ce94d8f319aa7103cef8f0fe9f"
+      },
+      "obj_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/obj_pose/000438.txt",
+        "sha256": "92baf00b6edd999bdbd7e74cf91bd3952aaaeed9db349171b6f8b4f1d8409c8f"
+      },
+      "obj_pose_rt": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/obj_pose_rt/000438.txt",
+        "sha256": "6ef25fe8ce3b8e3a61d52f3602bdb6f05df0bfa23a64165d17b01269d257b05b"
+      },
+      "rgb": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/rgb/000438.png",
+        "sha256": "7ac22829b251d78f8133fdc7610d8006cf77d1b90b8c14e324a6b000a7dfe9e5"
+      }
+    },
+    "annotation_matches": {
+      "hand_pose_mano": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "hand_pose": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "depth": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "cam_pose": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose_rt": {
+        "source_frame_id": 438,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      }
+    },
+    "frame_index": 438,
+    "timestamp_ns": null,
+    "clock_domain": null
+  },
+  "rgb_valid": true,
+  "intrinsic": {
+    "value": [
+      [
+        636.6593017578125,
+        0.0,
+        635.2838745117188
+      ],
+      [
+        0.0,
+        636.251953125,
+        366.8740234375
+      ],
+      [
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "extrinsic": {
+    "value": [
+      [
+        0.9955894351005554,
+        0.09371787309646606,
+        -0.004344814922660589,
+        -0.037381332367658615
+      ],
+      [
+        -0.0938185453414917,
+        0.994526207447052,
+        -0.04599740356206894,
+        -0.0021001270506531
+      ],
+      [
+        1.0247972568322439e-05,
+        0.046201810240745544,
+        0.9989322423934937,
+        -0.03738684579730034
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "mano": {
+    "value": [
+      [
+        2.521770477294922,
+        -1.8380836248397827,
+        0.0946151614189148,
+        0.0441138930618763,
+        0.31131309270858765,
+        -0.00626513222232461,
+        -0.02036752924323082,
+        0.0451199971139431,
+        -0.34308093786239624,
+        -0.0009102236945182085,
+        0.02689209207892418,
+        -0.3802049458026886,
+        -0.015653541311621666,
+        0.17522288858890533,
+        -0.151083305478096,
+        -0.26585128903388977,
+        -0.005229040049016476,
+        -0.7646550536155701,
+        -0.02005547657608986,
+        0.021737094968557358,
+        -0.5219047665596008,
+        -0.16009902954101562,
+        -0.27070680260658264,
+        -0.22880232334136963,
+        -0.21499472856521606,
+        0.005724928807467222,
+        -0.30150121450424194,
+        -0.050526686012744904,
+        -0.038071416318416595,
+        -0.0952521562576294,
+        -0.03314047306776047,
+        -0.048541996628046036,
+        -0.22275325655937195,
+        -0.29545819759368896,
+        -0.0030866072047501802,
+        -0.5464324951171875,
+        -0.030524782836437225,
+        -0.06140469014644623,
+        -0.5275866389274597,
+        0.9019661545753479,
+        -0.023597352206707,
+        -0.28409048914909363,
+        -0.2718367874622345,
+        -0.13753437995910645,
+        -0.011629355140030384,
+        0.0581522062420845,
+        -0.013459517620503902,
+        -0.34280645847320557,
+        -0.2806254029273987,
+        1.476506233215332,
+        -0.6854744553565979,
+        0.16803301870822906,
+        -0.18744522333145142,
+        -0.5487542748451233,
+        -2.63431978225708,
+        -0.5607357025146484,
+        -2.1435391902923584,
+        -0.6932340264320374,
+        -0.029520420357584953,
+        0.07511100172996521,
+        0.4626691937446594
+      ],
+      [
+        -1.4663174152374268,
+        -0.9924806952476501,
+        1.563149333000183,
+        -0.010575031861662865,
+        -0.24173542857170105,
+        0.697502851486206,
+        0.20180197060108185,
+        0.0415135994553566,
+        0.4217185378074646,
+        -0.025461535900831223,
+        0.020387917757034302,
+        -0.013804709538817406,
+        -0.1217774748802185,
+        0.07403827458620071,
+        1.1567624807357788,
+        -0.20310288667678833,
+        0.00981416366994381,
+        0.3319188356399536,
+        -0.01451727282255888,
+        0.004075824748724699,
+        0.35964834690093994,
+        -0.7797415256500244,
+        0.6071902513504028,
+        0.8347394466400146,
+        -0.33239734172821045,
+        0.005324136465787888,
+        0.5375992059707642,
+        -0.056371986865997314,
+        0.008091513998806477,
+        0.37781718373298645,
+        -0.2753085494041443,
+        0.3322887122631073,
+        1.052750587463379,
+        -0.32745134830474854,
+        0.0330868624150753,
+        0.6154453158378601,
+        -0.03810780122876167,
+        0.03570462018251419,
+        0.6540924906730652,
+        0.8452440500259399,
+        -0.190989688038826,
+        0.08434190601110458,
+        -0.332694947719574,
+        0.25225186347961426,
+        -0.028766237199306488,
+        0.0437852218747139,
+        -0.002592346863821149,
+        0.3574236035346985,
+        -0.4555988311767578,
+        0.13637742400169373,
+        0.8111323714256287,
+        -2.9508821964263916,
+        0.06259849667549133,
+        -1.952202320098877,
+        -3.399379253387451,
+        0.6082465648651123,
+        -1.1187307834625244,
+        -0.8084438443183899,
+        0.08486741036176682,
+        0.005701745394617319,
+        0.467281311750412
+      ]
+    ],
+    "valid": [
+      true,
+      true
+    ]
+  },
+  "keypoints_xyz": {
+    "value": [
+      [
+        [
+          -0.12386354804039001,
+          0.08205614984035492,
+          0.46854567527770996
+        ],
+        [
+          -0.09890363365411758,
+          0.06442240625619888,
+          0.44356033205986023
+        ],
+        [
+          -0.07145710289478302,
+          0.05707967281341553,
+          0.43030259013175964
+        ],
+        [
+          -0.04759988188743591,
+          0.04829175025224686,
+          0.4232131540775299
+        ],
+        [
+          -0.01599363423883915,
+          0.04603683575987816,
+          0.419479101896286
+        ],
+        [
+          -0.0918625071644783,
+          0.00022503509535454214,
+          0.4508669376373291
+        ],
+        [
+          -0.08714086562395096,
+          -0.03062462992966175,
+          0.4607669413089752
+        ],
+        [
+          -0.07383616268634796,
+          -0.045152634382247925,
+          0.47041991353034973
+        ],
+        [
+          -0.05464128032326698,
+          -0.056797731667757034,
+          0.4760507345199585
+        ],
+        [
+          -0.09446529299020767,
+          -0.006344800349324942,
+          0.47617465257644653
+        ],
+        [
+          -0.08407486975193024,
+          -0.03320072218775749,
+          0.490382581949234
+        ],
+        [
+          -0.0616251677274704,
+          -0.03824487328529358,
+          0.49549639225006104
+        ],
+        [
+          -0.03712894022464752,
+          -0.037363190203905106,
+          0.4971914291381836
+        ],
+        [
+          -0.09556187689304352,
+          0.007721863221377134,
+          0.4993530511856079
+        ],
+        [
+          -0.08281715959310532,
+          -0.018317805603146553,
+          0.5067411065101624
+        ],
+        [
+          -0.059517454355955124,
+          -0.0250936858355999,
+          0.5126660466194153
+        ],
+        [
+          -0.03515131399035454,
+          -0.02818133682012558,
+          0.5145478248596191
+        ],
+        [
+          -0.09388329833745956,
+          0.023406455293297768,
+          0.5152963399887085
+        ],
+        [
+          -0.08296286314725876,
+          0.007133141625672579,
+          0.5235734581947327
+        ],
+        [
+          -0.06715208292007446,
+          -0.0024852228816598654,
+          0.5292743444442749
+        ],
+        [
+          -0.05222299322485924,
+          -0.012877504341304302,
+          0.5347709655761719
+        ]
+      ],
+      [
+        [
+          0.1813894659280777,
+          0.012500102631747723,
+          0.4736485779285431
+        ],
+        [
+          0.1562579721212387,
+          -0.004362180829048157,
+          0.5002153515815735
+        ],
+        [
+          0.1448802649974823,
+          -0.019209863618016243,
+          0.5265067219734192
+        ],
+        [
+          0.13587802648544312,
+          -0.03313149884343147,
+          0.5488944053649902
+        ],
+        [
+          0.1297340989112854,
+          -0.04182273894548416,
+          0.5820263028144836
+        ],
+        [
+          0.1629958152770996,
+          -0.06484820693731308,
+          0.5141831636428833
+        ],
+        [
+          0.16941678524017334,
+          -0.08186853677034378,
+          0.5409590601921082
+        ],
+        [
+          0.17445223033428192,
+          -0.080734983086586,
+          0.5624719858169556
+        ],
+        [
+          0.17497172951698303,
+          -0.08118393272161484,
+          0.5857483744621277
+        ],
+        [
+          0.18782246112823486,
+          -0.07272564619779587,
+          0.5128034949302673
+        ],
+        [
+          0.19131438434123993,
+          -0.07510361820459366,
+          0.546122670173645
+        ],
+        [
+          0.19166384637355804,
+          -0.06492346525192261,
+          0.5681912899017334
+        ],
+        [
+          0.19006158411502838,
+          -0.04576427489519119,
+          0.5876129269599915
+        ],
+        [
+          0.21236629784107208,
+          -0.05976603925228119,
+          0.5096145272254944
+        ],
+        [
+          0.20853444933891296,
+          -0.0650256797671318,
+          0.5389493107795715
+        ],
+        [
+          0.20476673543453217,
+          -0.04779135435819626,
+          0.5589192509651184
+        ],
+        [
+          0.20015428960323334,
+          -0.027131978422403336,
+          0.5700839161872864
+        ],
+        [
+          0.22970573604106903,
+          -0.04472871869802475,
+          0.5107429623603821
+        ],
+        [
+          0.2259441316127777,
+          -0.048049651086330414,
+          0.5329038500785828
+        ],
+        [
+          0.21743831038475037,
+          -0.038728032261133194,
+          0.548850417137146
+        ],
+        [
+          0.209330752491951,
+          -0.026499224826693535,
+          0.5609960556030273
+        ]
+      ]
+    ],
+    "valid": [
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ],
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ]
+    ]
+  },
+  "pose_cocoa": {
+    "value": [
+      [
+        0.9955143928527832,
+        -0.09402307868003845,
+        0.010567122139036655,
+        -0.03089960664510727
+      ],
+      [
+        -0.06821020692586899,
+        -0.7906008362770081,
+        -0.6085213422775269,
+        0.012366623617708683
+      ],
+      [
+        0.06556899845600128,
+        0.6050708889961243,
+        -0.793467104434967,
+        0.4706019461154938
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "points_cocoa": {
+    "value": [
+      [
+        -0.03089960664510727,
+        0.012366623617708683,
+        0.4706019461154938
+      ],
+      [
+        0.005926560144871473,
+        -0.07184009253978729,
+        0.4433899223804474
+      ],
+      [
+        -0.07494990527629852,
+        -0.06629863381385803,
+        0.4380630552768707
+      ],
+      [
+        -0.0764974057674408,
+        0.02281634323298931,
+        0.5542623996734619
+      ],
+      [
+        0.0043790568597614765,
+        0.0172748863697052,
+        0.5595893263816833
+      ],
+      [
+        0.014698191545903683,
+        0.0019169030711054802,
+        0.38694146275520325
+      ],
+      [
+        -0.06617826968431473,
+        0.0074583604000508785,
+        0.3816145658493042
+      ],
+      [
+        -0.0677257776260376,
+        0.09657333791255951,
+        0.4978139400482178
+      ],
+      [
+        0.013150688260793686,
+        0.09103187918663025,
+        0.5031408071517944
+      ],
+      [
+        -0.03451167047023773,
+        -0.06906936317682266,
+        0.44072648882865906
+      ],
+      [
+        -0.025740040466189384,
+        0.004687631502747536,
+        0.38427799940109253
+      ],
+      [
+        -0.027287542819976807,
+        0.09380260854959488,
+        0.5004773736000061
+      ],
+      [
+        -0.0360591746866703,
+        0.02004561573266983,
+        0.5569258332252502
+      ],
+      [
+        0.010312375612556934,
+        -0.03496159240603447,
+        0.4151656925678253
+      ],
+      [
+        -0.07056408375501633,
+        -0.02942013554275036,
+        0.40983879566192627
+      ],
+      [
+        -0.0721115916967392,
+        0.059694841504096985,
+        0.5260381698608398
+      ],
+      [
+        0.008764872327446938,
+        0.054153382778167725,
+        0.5313650369644165
+      ],
+      [
+        0.005152808502316475,
+        -0.027282601222395897,
+        0.5014896392822266
+      ],
+      [
+        -0.07572365552186966,
+        -0.021741144359111786,
+        0.4961627423763275
+      ],
+      [
+        -0.06695201992988586,
+        0.05201584845781326,
+        0.439714252948761
+      ],
+      [
+        0.013924440369009972,
+        0.046474389731884,
+        0.44504114985466003
+      ]
+    ],
+    "valid": [
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true
+    ]
+  }
+}

帧 583 / 584

原生 RGB(仅预览缩放)
RGB + 原生 3D 关键点投影(仅预览:keypoints_xyz #00e6ff, points_cocoa #ff48a4)
深度 Z,黑=无效,白≥3 m;不改源深度
原深度逐像素 valid:白=有效,黑=无效,不是深度值
原帧号、全部数值标注及有效性
{
+  "frame": {
+    "source_frame_id": 583,
+    "sync_id": "subject4/h1/7:583",
+    "source_locator": {
+      "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+      "member": "subject4/h1/7/cam4/rgb/000583.png",
+      "sha256": "8b998fa6f58fab0b03081b5ad3f05b0862d2da338b1425631299c36043c1ffc0"
+    },
+    "component_sources": {
+      "hand_pose_mano": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/hand_pose_mano/000583.txt",
+        "sha256": "cf8a2554cb5ad10cb9ddf073c4a4573c4f7483454b72c3d13dd844a3fda8a479"
+      },
+      "hand_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/hand_pose/000583.txt",
+        "sha256": "3e93995e023adb878abf3d28c0a4ef8ef828070e0345054a516117de41244feb"
+      },
+      "depth": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/depth/000583.png",
+        "sha256": "c3bf5ff1341878d3c02d80349a627a776ab470905648852cabe4fdda9734daca"
+      },
+      "cam_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/cam_pose/000583.txt",
+        "sha256": "f871321dafc3ea93723466ac8e146a6e0ed6a0a5b255628301c2e856591add17"
+      },
+      "obj_pose": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/obj_pose/000583.txt",
+        "sha256": "c81835e1bfd8efb91ab12b7c5ee0533a9777d89ccfcaea402802a131b613f447"
+      },
+      "obj_pose_rt": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/obj_pose_rt/000583.txt",
+        "sha256": "06defa73f596ba85599c34f26df8e2c508c5c3d9180c07254e9d6754a5450c5b"
+      },
+      "rgb": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/rgb/000583.png",
+        "sha256": "8b998fa6f58fab0b03081b5ad3f05b0862d2da338b1425631299c36043c1ffc0"
+      }
+    },
+    "annotation_matches": {
+      "hand_pose_mano": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "hand_pose": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "depth": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "cam_pose": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      },
+      "obj_pose_rt": {
+        "source_frame_id": 583,
+        "source_timestamp_ns": null,
+        "clock_domain": null,
+        "match_method": "index_map",
+        "delta_ns": null
+      }
+    },
+    "frame_index": 583,
+    "timestamp_ns": null,
+    "clock_domain": null
+  },
+  "rgb_valid": true,
+  "intrinsic": {
+    "value": [
+      [
+        636.6593017578125,
+        0.0,
+        635.2838745117188
+      ],
+      [
+        0.0,
+        636.251953125,
+        366.8740234375
+      ],
+      [
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "extrinsic": {
+    "value": [
+      [
+        0.999973714351654,
+        0.007230177987366915,
+        -0.0007398464367724955,
+        -0.004617605358362198
+      ],
+      [
+        -0.0072593060322105885,
+        0.9985576272010803,
+        -0.053198717534542084,
+        -0.013021164573729038
+      ],
+      [
+        0.00035413732985034585,
+        0.05320234224200249,
+        0.9985837936401367,
+        -0.0343993678689003
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "mano": {
+    "value": [
+      [
+        -2.0947842597961426,
+        2.062685489654541,
+        0.0223903339356184,
+        0.03340994939208031,
+        0.3228056728839874,
+        -0.07821039110422134,
+        0.00736130028963089,
+        0.044860951602458954,
+        -0.34319353103637695,
+        -0.0073201400227844715,
+        0.029256504029035568,
+        -0.2064988762140274,
+        -0.027639465406537056,
+        0.14684435725212097,
+        -0.37501099705696106,
+        -0.20725110173225403,
+        0.003951873164623976,
+        -0.45073044300079346,
+        -0.012203204445540905,
+        0.014346623793244362,
+        -0.27812620997428894,
+        -0.18587090075016022,
+        -0.2580273449420929,
+        -0.4124998152256012,
+        -0.3137627840042114,
+        0.006992853246629238,
+        -0.35082560777664185,
+        -0.045118238776922226,
+        -0.05261789634823799,
+        -0.16788744926452637,
+        -0.003028573701158166,
+        -0.08499280363321304,
+        -0.46834662556648254,
+        -0.24806950986385345,
+        0.0007639554096385837,
+        -0.23950041830539703,
+        -0.024439869448542595,
+        -0.04982245713472366,
+        -0.2905237078666687,
+        0.7547170519828796,
+        -0.04532362520694733,
+        -0.17603327333927155,
+        -0.32395726442337036,
+        -0.21300753951072693,
+        0.0027177261654287577,
+        0.04898405075073242,
+        0.0004385107895359397,
+        -0.2091580480337143,
+        -0.2806254029273987,
+        1.476506233215332,
+        -0.6854744553565979,
+        0.16803301870822906,
+        -0.18744522333145142,
+        -0.5487542748451233,
+        -2.63431978225708,
+        -0.5607357025146484,
+        -2.1435391902923584,
+        -0.6932340264320374,
+        0.010778646916151047,
+        0.10929322987794876,
+        0.3926072120666504
+      ],
+      [
+        -2.264763355255127,
+        -1.8242030143737793,
+        -0.1583261340856552,
+        0.035671260207891464,
+        -0.23242047429084778,
+        0.9175093173980713,
+        0.194064661860466,
+        -0.05034683272242546,
+        0.22226956486701965,
+        -0.04774567112326622,
+        -0.05082094669342041,
+        -0.05479954183101654,
+        -0.026752272620797157,
+        -0.05637355521321297,
+        1.0516794919967651,
+        -0.17926554381847382,
+        -0.017618492245674133,
+        0.14412200450897217,
+        0.011402745731174946,
+        0.000925535277929157,
+        0.04662485048174858,
+        -0.48833101987838745,
+        0.37762975692749023,
+        0.5960181355476379,
+        -0.13645552098751068,
+        -0.03331734985113144,
+        0.3506031930446625,
+        -0.06388898938894272,
+        -0.019688155502080917,
+        0.05134721100330353,
+        -0.12143892049789429,
+        0.09756811708211899,
+        0.8241648077964783,
+        -0.23145286738872528,
+        0.017975086346268654,
+        0.3451057970523834,
+        -0.025740794837474823,
+        0.021148517727851868,
+        0.2646710276603699,
+        1.092269778251648,
+        -0.44799330830574036,
+        0.15289244055747986,
+        -0.30898961424827576,
+        -0.09629514813423157,
+        -0.03233122080564499,
+        0.0844181478023529,
+        0.041561249643564224,
+        0.3536794185638428,
+        -0.4555988311767578,
+        0.13637742400169373,
+        0.8111323714256287,
+        -2.9508821964263916,
+        0.06259849667549133,
+        -1.952202320098877,
+        -3.399379253387451,
+        0.6082465648651123,
+        -1.1187307834625244,
+        -0.8084438443183899,
+        0.03800210729241371,
+        0.10018512606620789,
+        0.38732147216796875
+      ]
+    ],
+    "valid": [
+      true,
+      true
+    ]
+  },
+  "keypoints_xyz": {
+    "value": [
+      [
+        [
+          -0.08356447517871857,
+          0.11623837798833847,
+          0.39848366379737854
+        ],
+        [
+          -0.0618167407810688,
+          0.09784598648548126,
+          0.37115296721458435
+        ],
+        [
+          -0.03948783874511719,
+          0.08523906022310257,
+          0.3531118929386139
+        ],
+        [
+          -0.020882651209831238,
+          0.07253231108188629,
+          0.3393626809120178
+        ],
+        [
+          0.0059781973250210285,
+          0.060035958886146545,
+          0.32651713490486145
+        ],
+        [
+          -0.07341232150793076,
+          0.03435620293021202,
+          0.36348119378089905
+        ],
+        [
+          -0.0761336237192154,
+          0.0019001848995685577,
+          0.36682891845703125
+        ],
+        [
+          -0.06710241734981537,
+          -0.01682739332318306,
+          0.3738269507884979
+        ],
+        [
+          -0.05450978875160217,
+          -0.03587444871664047,
+          0.37792664766311646
+        ],
+        [
+          -0.08043553680181503,
+          0.02360215038061142,
+          0.38640373945236206
+        ],
+        [
+          -0.07245375961065292,
+          -0.0064484416507184505,
+          0.39442357420921326
+        ],
+        [
+          -0.054413460195064545,
+          -0.02049562893807888,
+          0.40015146136283875
+        ],
+        [
+          -0.034574270248413086,
+          -0.034746311604976654,
+          0.40523988008499146
+        ],
+        [
+          -0.08015187829732895,
+          0.03211480751633644,
+          0.41216734051704407
+        ],
+        [
+          -0.06907587498426437,
+          0.004378968384116888,
+          0.41393429040908813
+        ],
+        [
+          -0.05069040507078171,
+          -0.011458472348749638,
+          0.4198540449142456
+        ],
+        [
+          -0.03254395350813866,
+          -0.028191370889544487,
+          0.42331746220588684
+        ],
+        [
+          -0.07599005103111267,
+          0.042868684977293015,
+          0.4314039349555969
+        ],
+        [
+          -0.06748799979686737,
+          0.024103352800011635,
+          0.43671104311943054
+        ],
+        [
+          -0.052063629031181335,
+          0.013206027448177338,
+          0.4409925639629364
+        ],
+        [
+          -0.037182945758104324,
+          0.0026446788106113672,
+          0.4445194900035858
+        ]
+      ],
+      [
+        [
+          0.1345241665840149,
+          0.106983482837677,
+          0.39368876814842224
+        ],
+        [
+          0.11105052381753922,
+          0.0932416021823883,
+          0.36399248242378235
+        ],
+        [
+          0.08649033308029175,
+          0.07306331396102905,
+          0.35844478011131287
+        ],
+        [
+          0.07225172221660614,
+          0.04912960156798363,
+          0.3591526448726654
+        ],
+        [
+          0.047423355281353,
+          0.026000332087278366,
+          0.367118239402771
+        ],
+        [
+          0.10938389599323273,
+          0.031875886023044586,
+          0.35256755352020264
+        ],
+        [
+          0.08233276754617691,
+          0.014196661300957203,
+          0.354451447725296
+        ],
+        [
+          0.06180183216929436,
+          0.009536361321806908,
+          0.3612489700317383
+        ],
+        [
+          0.03965076059103012,
+          0.0029188860207796097,
+          0.36469119787216187
+        ],
+        [
+          0.11299750953912735,
+          0.01759401522576809,
+          0.3740917146205902
+        ],
+        [
+          0.08300460875034332,
+          0.0036259600892663,
+          0.3798649311065674
+        ],
+        [
+          0.05954132601618767,
+          0.0009618470794521272,
+          0.38562336564064026
+        ],
+        [
+          0.03295453265309334,
+          -0.0011692976113408804,
+          0.3925060033798218
+        ],
+        [
+          0.11430113762617111,
+          0.023276541382074356,
+          0.4014144241809845
+        ],
+        [
+          0.08990065008401871,
+          0.005741490516811609,
+          0.40154361724853516
+        ],
+        [
+          0.06366898119449615,
+          0.004598585423082113,
+          0.4060834050178528
+        ],
+        [
+          0.03960786759853363,
+          0.003171835793182254,
+          0.409438818693161
+        ],
+        [
+          0.11075717210769653,
+          0.03214240074157715,
+          0.4223162829875946
+        ],
+        [
+          0.09232800453901291,
+          0.018918516114354134,
+          0.4236491620540619
+        ],
+        [
+          0.07239358127117157,
+          0.014900664798915386,
+          0.42375150322914124
+        ],
+        [
+          0.05238761007785797,
+          0.010051753371953964,
+          0.4239138662815094
+        ]
+      ]
+    ],
+    "valid": [
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ],
+      [
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true,
+        true
+      ]
+    ]
+  },
+  "pose_cocoa": {
+    "value": [
+      [
+        0.8854988217353821,
+        -0.4555083215236664,
+        -0.09167595952749252,
+        -0.01019955798983574
+      ],
+      [
+        -0.44643670320510864,
+        -0.7793906927108765,
+        -0.4395965039730072,
+        0.02586475759744644
+      ],
+      [
+        0.12878794968128204,
+        0.4301896393299103,
+        -0.8935049176216125,
+        0.39088520407676697
+      ],
+      [
+        0.0,
+        0.0,
+        0.0,
+        1.0
+      ]
+    ],
+    "valid": true
+  },
+  "points_cocoa": {
+    "value": [
+      [
+        -0.01019955798983574,
+        0.02586475759744644,
+        0.39088520407676697
+      ],
+      [
+        -0.002190670231357217,
+        -0.06081366166472435,
+        0.3507586121559143
+      ],
+      [
+        -0.0741293728351593,
+        -0.02454475313425064,
+        0.3402957618236542
+      ],
+      [
+        -0.06070387363433838,
+        0.03983200713992119,
+        0.4711451828479767
+      ],
+      [
+        0.011234825477004051,
+        0.0035630962811410427,
+        0.4816080331802368
+      ],
+      [
+        0.0403047613799572,
+        0.01189750898629427,
+        0.31062522530555725
+      ],
+      [
+        -0.03163393959403038,
+        0.048166416585445404,
+        0.3001623749732971
+      ],
+      [
+        -0.018208445981144905,
+        0.11254318058490753,
+        0.43101179599761963
+      ],
+      [
+        0.053730256855487823,
+        0.07627426832914352,
+        0.44147464632987976
+      ],
+      [
+        -0.03816002234816551,
+        -0.042679209262132645,
+        0.34552720189094543
+      ],
+      [
+        0.00433540903031826,
+        0.0300319641828537,
+        0.305393785238266
+      ],
+      [
+        0.017760904505848885,
+        0.09440872073173523,
+        0.4362432360649109
+      ],
+      [
+        -0.02473452500998974,
+        0.021697551012039185,
+        0.47637662291526794
+      ],
+      [
+        0.01905704475939274,
+        -0.024458076804876328,
+        0.3306919038295746
+      ],
+      [
+        -0.05288165807723999,
+        0.011810832656919956,
+        0.32022908329963684
+      ],
+      [
+        -0.03945615887641907,
+        0.07618758827447891,
+        0.45107850432395935
+      ],
+      [
+        0.03248254209756851,
+        0.0399186834692955,
+        0.4615413546562195
+      ],
+      [
+        0.004522077739238739,
+        -0.028625283390283585,
+        0.41618332266807556
+      ],
+      [
+        -0.06741662323474884,
+        0.007643626071512699,
+        0.40572047233581543
+      ],
+      [
+        -0.024921193718910217,
+        0.08035479485988617,
+        0.3655870854854584
+      ],
+      [
+        0.04701750725507736,
+        0.04408589005470276,
+        0.3760499358177185
+      ]
+    ],
+    "valid": [
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true,
+      true
+    ]
+  }
+}

源网格

mesh_cocoa

源 OBJ 静态预览,不代表物体姿态投影
全部组件元数据
{
+  "schema_version": "hand-warehouse/1.1",
+  "dataset_id": "H2O",
+  "release_id": "shared-v1.1",
+  "sequence_id": "subject4_h1_7",
+  "camera_id": "cam4",
+  "sample_type": "video",
+  "num_frames": 584,
+  "hand_slots": [
+    "left",
+    "right"
+  ],
+  "sampling": {
+    "type": "dense",
+    "source_fps": null,
+    "frames_ref": "camera/frames.jsonl",
+    "selection": {
+      "max_frames": null,
+      "views": null
+    }
+  },
+  "camera": {
+    "model": "pinhole",
+    "schema_id": "camera/pinhole/v1",
+    "image_size": [
+      1280,
+      720
+    ]
+  },
+  "components": {
+    "rgb": {
+      "available": true,
+      "schema_id": "rgb/uint8/v1",
+      "data_ref": "observation/rgb.mkv",
+      "axes": [
+        "T",
+        "height",
+        "width",
+        "channel"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Verified source packet copy or lossless fixed-decoder RGB encoding"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl"
+      },
+      "storage": {
+        "profile": "mkv/ffv1_rgb/v1",
+        "codec": "ffv1",
+        "pixel_format": "bgr0",
+        "encoded_size": [
+          1280,
+          720
+        ],
+        "decoder": {
+          "name": "ffmpeg",
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "autorotate": false,
+          "color_space": "gbr",
+          "color_range": "pc",
+          "color_primaries": "unknown",
+          "color_transfer": "unknown",
+          "source_color_metadata": {
+            "color_space": "gbr",
+            "color_range": "pc",
+            "color_primaries": "unknown",
+            "color_transfer": "unknown"
+          }
+        },
+        "encoder_parameters": {
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "name": "ffv1",
+          "arguments": [
+            "-level",
+            "3",
+            "-pix_fmt",
+            "bgr0"
+          ],
+          "threads": 10
+        },
+        "source_lossy": false,
+        "storage_fps": 30,
+        "timebase_role": "index_only"
+      },
+      "valid_ref": "observation/rgb_valid.pt",
+      "valid_axes": [
+        "T"
+      ]
+    },
+    "intrinsic": {
+      "available": true,
+      "schema_id": "camera/pinhole/v1",
+      "data_ref": "camera/camera.pt",
+      "axes": [
+        "T",
+        "row",
+        "column"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/subject4_v1_1.tar.gz",
+        "member": "subject4/h1/7/cam4/cam_intrinsics.txt",
+        "sha256": "1160f040484b3a86512b02f8225ee5f051c8a96dbd1cfb15e41d14c7487126e3"
+      },
+      "valid_ref": "camera/camera.pt",
+      "valid_axes": [
+        "T"
+      ],
+      "data_key": [
+        "intrinsic",
+        "data"
+      ],
+      "valid_key": [
+        "intrinsic",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "extrinsic": {
+      "available": true,
+      "schema_id": "transform/se3/v1",
+      "data_ref": "camera/camera.pt",
+      "axes": [
+        "T",
+        "row",
+        "column"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources"
+      },
+      "valid_ref": "camera/camera.pt",
+      "valid_axes": [
+        "T"
+      ],
+      "convention": "T_camera_from_world",
+      "source_convention": "T_world_from_camera",
+      "data_key": [
+        "extrinsic",
+        "data"
+      ],
+      "valid_key": [
+        "extrinsic",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "mano": {
+      "available": true,
+      "schema_id": "mano/axis_angle61/v1",
+      "data_ref": "annotation/mano/mano.pt",
+      "axes": [
+        "T",
+        "hand",
+        "parameter"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources"
+      },
+      "valid_ref": "annotation/mano/mano.pt",
+      "valid_axes": [
+        "T",
+        "hand"
+      ],
+      "model_profile": {
+        "version": "sha256:eab78181e459e156559df334b103d825e00c8711d2eeffee1cc176fb42051f4f",
+        "flat_hand_mean": true,
+        "left_shapedirs_correction": "not_applied",
+        "models": {
+          "left": {
+            "file": "MANO_LEFT.pkl",
+            "sha256": "c4022f7083f2ca7c78b2b3d595abbab52debd32b09d372b16923a801f0ea6a30"
+          },
+          "right": {
+            "file": "MANO_RIGHT.pkl",
+            "sha256": "45d60aa3b27ef9107a7afd4e00808f307fd91111e1cfa35afd5c4a62de264767"
+          }
+        }
+      },
+      "valid_policy": {
+        "revision": "usable-annotation-2026-09-20",
+        "meaning": "annotation usable for supervision, not merely record presence",
+        "source_rule": "Per-hand hand_pose_mano flag equals 1; corresponding side model available",
+        "source_locator": {
+          "frames_ref": "camera/frames.jsonl",
+          "source_field": "component_sources"
+        },
+        "scope": [
+          "T",
+          "hand"
+        ],
+        "numerical_checks": "Schema shape, finite valid floats, SE(3) where applicable; malformed input aborts",
+        "official_qa": {
+          "status": "not_provided",
+          "reason": "No separate applicable official QA in selected source inputs"
+        },
+        "local_excluded_frame_indices": [],
+        "local_exclusion_reasons": {},
+        "visibility_independent": true
+      },
+      "data_key": [
+        "motion",
+        "data"
+      ],
+      "valid_key": [
+        "motion",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "keypoints_xyz": {
+      "available": true,
+      "schema_id": "keypoints/xyz/v1",
+      "data_ref": "annotation/keypoints/keypoints.pt",
+      "axes": [
+        "T",
+        "hand",
+        "keypoint",
+        "coordinate"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources"
+      },
+      "valid_ref": "annotation/keypoints/keypoints.pt",
+      "valid_axes": [
+        "T",
+        "hand",
+        "keypoint"
+      ],
+      "keypoint_schema": "mano21/v1",
+      "unit": "m",
+      "valid_policy": {
+        "revision": "usable-annotation-2026-09-20",
+        "meaning": "annotation usable for supervision, not merely record presence",
+        "source_rule": "Per-hand hand_pose flag equals 1, broadcast to that hand's 21 source points independently of MANO",
+        "source_locator": {
+          "frames_ref": "camera/frames.jsonl",
+          "source_field": "component_sources"
+        },
+        "scope": [
+          "T",
+          "hand",
+          "keypoint"
+        ],
+        "numerical_checks": "Schema shape, finite valid floats, SE(3) where applicable; malformed input aborts",
+        "official_qa": {
+          "status": "not_provided",
+          "reason": "No separate applicable official QA in selected source inputs"
+        },
+        "local_excluded_frame_indices": [],
+        "local_exclusion_reasons": {},
+        "visibility_independent": true
+      },
+      "data_key": [
+        "xyz",
+        "data"
+      ],
+      "valid_key": [
+        "xyz",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "pose_cocoa": {
+      "available": true,
+      "schema_id": "object/rigid/v1",
+      "data_ref": "annotation/object/cocoa/object.pt",
+      "axes": [
+        "T",
+        "row",
+        "column"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources"
+      },
+      "valid_ref": "annotation/object/cocoa/object.pt",
+      "valid_axes": [
+        "T"
+      ],
+      "convention": "T_camera_from_object",
+      "unit": "m",
+      "valid_policy": {
+        "revision": "usable-annotation-2026-09-20",
+        "meaning": "annotation usable for supervision, not merely record presence",
+        "source_rule": "Source obj_pose_rt class equals this nonzero object class",
+        "source_locator": {
+          "frames_ref": "camera/frames.jsonl",
+          "source_field": "component_sources"
+        },
+        "scope": [
+          "T"
+        ],
+        "numerical_checks": "Schema shape, finite valid floats, SE(3) where applicable; malformed input aborts",
+        "official_qa": {
+          "status": "not_provided",
+          "reason": "No separate applicable official QA in selected source inputs"
+        },
+        "local_excluded_frame_indices": [],
+        "local_exclusion_reasons": {},
+        "visibility_independent": true
+      },
+      "data_key": [
+        "pose",
+        "data"
+      ],
+      "valid_key": [
+        "pose",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "points_cocoa": {
+      "available": true,
+      "schema_id": "object_keypoints/camera/v1",
+      "data_ref": "annotation/object/cocoa/object.pt",
+      "axes": [
+        "T",
+        "keypoint",
+        "coordinate"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources"
+      },
+      "valid_ref": "annotation/object/cocoa/object.pt",
+      "valid_axes": [
+        "T",
+        "keypoint"
+      ],
+      "keypoint_schema": "H2O_official_object21",
+      "keypoint_names": [
+        "center",
+        "corner_0",
+        "corner_1",
+        "corner_2",
+        "corner_3",
+        "corner_4",
+        "corner_5",
+        "corner_6",
+        "corner_7",
+        "edge_midpoint_0",
+        "edge_midpoint_1",
+        "edge_midpoint_2",
+        "edge_midpoint_3",
+        "edge_midpoint_4",
+        "edge_midpoint_5",
+        "edge_midpoint_6",
+        "edge_midpoint_7",
+        "edge_midpoint_8",
+        "edge_midpoint_9",
+        "edge_midpoint_10",
+        "edge_midpoint_11"
+      ],
+      "source_order": "official obj_point_order.jpg: center, 8 corners, 12 edge midpoints",
+      "unit": "m",
+      "valid_policy": {
+        "revision": "usable-annotation-2026-09-20",
+        "meaning": "annotation usable for supervision, not merely record presence",
+        "source_rule": "Source obj_pose class equals this nonzero object class, broadcast to its 21 points",
+        "source_locator": {
+          "frames_ref": "camera/frames.jsonl",
+          "source_field": "component_sources"
+        },
+        "scope": [
+          "T",
+          "keypoint"
+        ],
+        "numerical_checks": "Schema shape, finite valid floats, SE(3) where applicable; malformed input aborts",
+        "official_qa": {
+          "status": "not_provided",
+          "reason": "No separate applicable official QA in selected source inputs"
+        },
+        "local_excluded_frame_indices": [],
+        "local_exclusion_reasons": {},
+        "visibility_independent": true
+      },
+      "data_key": [
+        "keypoints",
+        "xyz",
+        "data"
+      ],
+      "valid_key": [
+        "keypoints",
+        "xyz",
+        "valid"
+      ],
+      "storage": {
+        "profile": "pt/tensor_bundle/v1"
+      },
+      "valid_storage": {
+        "profile": "pt/tensor_bundle/v1"
+      }
+    },
+    "mesh_cocoa": {
+      "available": true,
+      "schema_id": "mesh/obj/v1",
+      "data_ref": "annotation/object/cocoa/assets/cocoa.obj",
+      "axes": [
+        "vertex"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/object.zip",
+        "member": "object/cocoa/cocoa.obj",
+        "texture_aliases": [
+          {
+            "file": "cocoa.png",
+            "sha256": "90dd612369a14e825d040e539f1f1028e5b6e46e598eb5a4c664034e3a49e91f",
+            "source": {
+              "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/object.zip",
+              "member": "object/cocoa/ovomaltine.png"
+            }
+          }
+        ]
+      },
+      "valid": true,
+      "unit": "m"
+    },
+    "depth": {
+      "available": true,
+      "schema_id": "depth/z_float32/v1",
+      "data_ref": "observation/depth.mkv",
+      "axes": [
+        "T",
+        "height",
+        "width"
+      ],
+      "provenance": {
+        "kind": "format_conversion",
+        "method": "Copy source annotation; normalize storage only"
+      },
+      "source_locator": {
+        "frames_ref": "camera/frames.jsonl",
+        "source_field": "component_sources.depth",
+        "definition": "https://github.com/taeinkwon/h2oplayer/blob/main/utils.py",
+        "conversion": "registered millimetre camera-Z to metres; no viewer range clipping"
+      },
+      "storage": {
+        "profile": "mkv/depth_float32_bits/v1",
+        "codec": "ffv1",
+        "pixel_format": "gray16le",
+        "encoded_size": [
+          2560,
+          720
+        ],
+        "decoder": {
+          "name": "ffmpeg",
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "autorotate": false,
+          "color_space": "unknown",
+          "color_range": "unknown",
+          "color_primaries": "unknown",
+          "color_transfer": "unknown"
+        },
+        "encoder_parameters": {
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "name": "ffv1",
+          "arguments": [],
+          "threads": 10
+        },
+        "source_lossy": false,
+        "storage_fps": 30,
+        "timebase_role": "index_only"
+      },
+      "valid_storage": {
+        "profile": "mkv/bool_ffv1/v1",
+        "codec": "ffv1",
+        "pixel_format": "gray",
+        "encoded_size": [
+          1280,
+          720
+        ],
+        "decoder": {
+          "name": "ffmpeg",
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "autorotate": false,
+          "color_space": "unknown",
+          "color_range": "unknown",
+          "color_primaries": "unknown",
+          "color_transfer": "unknown"
+        },
+        "encoder_parameters": {
+          "version": "ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers",
+          "name": "ffv1",
+          "arguments": [],
+          "threads": 10
+        },
+        "source_lossy": false,
+        "storage_fps": 30,
+        "timebase_role": "index_only"
+      },
+      "valid_ref": "observation/depth_valid.mkv",
+      "valid_axes": [
+        "T",
+        "height",
+        "width"
+      ],
+      "unit": "m",
+      "depth_type": "z",
+      "depth_origin": "measured",
+      "invalid_value": "NaN"
+    },
+    "segment": {
+      "available": false,
+      "reason": "H2O provides no native segmentation; rendering deferred to v2.0",
+      "status": "source_missing"
+    },
+    "relations": {
+      "available": false,
+      "reason": "No source contact/grasp annotation",
+      "status": "source_missing"
+    }
+  },
+  "split": "test",
+  "view_type": "ego",
+  "split_scheme": "official_action_split",
+  "split_source_locator": {
+    "file": "/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/label_split.zip",
+    "member": "label_split/action_test.txt",
+    "record": 41
+  }
+}
持久化 QC
{
+  "num_frames": 584,
+  "numeric_components": {
+    "intrinsic": {
+      "shape": [
+        584,
+        3,
+        3
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 584,
+      "valid_total": 584
+    },
+    "extrinsic": {
+      "shape": [
+        584,
+        4,
+        4
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 584,
+      "valid_total": 584
+    },
+    "mano": {
+      "shape": [
+        584,
+        2,
+        61
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 1168,
+      "valid_total": 1168
+    },
+    "keypoints_xyz": {
+      "shape": [
+        584,
+        2,
+        21,
+        3
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 24528,
+      "valid_total": 24528
+    },
+    "pose_cocoa": {
+      "shape": [
+        584,
+        4,
+        4
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 584,
+      "valid_total": 584
+    },
+    "points_cocoa": {
+      "shape": [
+        584,
+        21,
+        3
+      ],
+      "dtype": "torch.float32",
+      "valid_true": 12264,
+      "valid_total": 12264
+    }
+  },
+  "bundle_files": 4,
+  "scope": "v1.1 registry, keys, shapes, validity and timeline; not a media pixel comparison",
+  "selected_frames": [
+    0,
+    146,
+    292,
+    438,
+    583
+  ],
+  "preview_media": [
+    "rgb",
+    "depth",
+    "depth_valid"
+  ],
+  "decode_scope": "only selected frames emitted; sequential decoding may traverse earlier frames, no full-video pixel comparison"
+}
\ No newline at end of file diff --git a/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam4.report.json b/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam4.report.json new file mode 100644 index 0000000000000000000000000000000000000000..999cbbaf3ed69232540d35e3cef3000308e975a5 --- /dev/null +++ b/H2O/shared-v1.1/doc/validation/subject4_h1_7_cam4.report.json @@ -0,0 +1,81 @@ +{ + "num_frames": 584, + "numeric_components": { + "intrinsic": { + "shape": [ + 584, + 3, + 3 + ], + "dtype": "torch.float32", + "valid_true": 584, + "valid_total": 584 + }, + "extrinsic": { + "shape": [ + 584, + 4, + 4 + ], + "dtype": "torch.float32", + "valid_true": 584, + "valid_total": 584 + }, + "mano": { + "shape": [ + 584, + 2, + 61 + ], + "dtype": "torch.float32", + "valid_true": 1168, + "valid_total": 1168 + }, + "keypoints_xyz": { + "shape": [ + 584, + 2, + 21, + 3 + ], + "dtype": "torch.float32", + "valid_true": 24528, + "valid_total": 24528 + }, + "pose_cocoa": { + "shape": [ + 584, + 4, + 4 + ], + "dtype": "torch.float32", + "valid_true": 584, + "valid_total": 584 + }, + "points_cocoa": { + "shape": [ + 584, + 21, + 3 + ], + "dtype": "torch.float32", + "valid_true": 12264, + "valid_total": 12264 + } + }, + "bundle_files": 4, + "scope": "v1.1 registry, keys, shapes, validity and timeline; not a media pixel comparison", + "selected_frames": [ + 0, + 146, + 292, + 438, + 583 + ], + "preview_media": [ + "rgb", + "depth", + "depth_valid" + ], + "decode_scope": "only selected frames emitted; sequential decoding may traverse earlier frames, no full-video pixel comparison" +} diff --git a/H2O/shared-v1.1/script/h2o_v1_1/README.md b/H2O/shared-v1.1/script/h2o_v1_1/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d5510eff32672b914e441a6cd3f8b31e7840c34f --- /dev/null +++ b/H2O/shared-v1.1/script/h2o_v1_1/README.md @@ -0,0 +1,90 @@ +# H2O v1.0 → v1.1 — gated migration pilot + +This is a storage-only migration of the audited H2O release, not a raw reconverter. +It supports the six native numeric component types actually present: intrinsic, +extrinsic, MANO, hand XYZ, object pose and object XYZ. Unsupported fields, +attributes, object IDs and orphan tensors fail closed. + +- `warehouse.py`: CPU/weights-only cached bundle reader; exact contiguous-byte + comparison including NaN payloads/signed zero; registry, references, timeline, + shapes and validity validation. All five camera roles are checked. +- `pilot.py`: selects complete sequences covering subjects, splits, eight object + classes, historical validity combinations, frame-length extremes and the + registered H.264 fallback. Read-only HF requests compare every pilot source + file against a fixed commit. Source files are hashed once, not per frame. + Unchanged media/validity/assets are hardlinked into an isolated pilot on the + same filesystem; never edit these hardlinks. Only new bundles/metadata are written. +- `render.py`: directly reads new bundles and samples native RGB, depth and + depth-valid; shows native XYZ projected for preview only, all numeric values, + validity, cameras, MANO, object pose/points/assets and provenance. Source-missing + UV/segmentation/contact remain missing. FFmpeg emits only selected frames; + sequential decoding can still traverse earlier frames. No media re-encoding + or full-video pixel equality check is done during migration. +- `spec/`: exact supplied v1.1 documents. Published `doc/CONTRACT.md` repairs the + original draft-relative semantic link to the bundled `V1_0_SEMANTICS.md`. + +Run on 101 under tmux `Data`, using the project environment: + +```bash +ROOT=/home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe/H2O +W="$ROOT/tmp/migration-v1.1-pilot-20261010" +mkdir -p "$W" +.venv/bin/python scripts/h2o_v1_1/pilot.py \ + --source "$ROOT/shared-v1.0" --out "$W/shared-v1.1" \ + --source-revision 2d78ce6422a5db77f6d64c2fb88770ab6e55ae0d --workers 4 +.venv/bin/python "$W/shared-v1.1/script/h2o_v1_1/render.py" \ + "$W/shared-v1.1" --workers 4 +``` + +`PILOT_JOURNAL.json` stays outside the pilot release. It records fixed source +revision, raw/source tree OIDs, tool fingerprints, exact changed/deletion paths, +source/unchanged/new file hashes and numerical comparisons. Original v1.0 +scripts/schema and selected build receipts are retained as history, not relabelled +as v1.1 approval. Pilot HTML and registry checks are not human approval. + +The pilot CLI has no upload/delete/full-run switch. The separately gated +`full.py` now implements the user-approved local full migration; HF publication +remains behind the post-full human review gate. No changes are made to local or remote raw, existing v1.0, other datasets, +or the project's concurrently edited global contract/schema. + +Tests: `.venv/bin/python -m unittest discover -s tests -p test_h2o_v1_1.py -v`. + + +## User-approved full migration (October 10, 2026) + +`full.py` acquires a dataset lock, checks same-user consumers, records the fixed HF +source and exact tool/inventory fingerprints, and enters maintenance. Each view +first passes the pilot writer and exact checks in private staging; original +numerical tensors/metadata are fsynced hardlink backups outside the release. +New bundles then metadata are atomically installed, and only the recorded old +numerical paths are removed. Prepared checkpoints recover partial installs; +completed checkpoints rehash inputs/output and compare rollback tensors on resume. + +Run from a frozen copy of this directory under `H2O/tmp`, not code being edited: + +```bash +python full.py --source /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe/H2O/shared-v1.0 \ + --work /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe/H2O/tmp/migration-v1.1-full-20261010 \ + --source-revision 2d78ce6422a5db77f6d64c2fb88770ab6e55ae0d \ + --pilot-summary /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe/H2O/tmp/migration-v1.1-pilot-20261010/shared-v1.1/doc/validation/PILOT_FINAL_CHECK.json \ + --human-pilot-approved --workers 4 +``` + +The final pass rehashes all changed bundles/metadata and checks their complete +numeric bytes against backups. Unchanged media were already hashed against the +fixed HF source; inode/size/mtime are rechecked under maintenance rather than +reading the entire media corpus a second time. Resume does perform fresh hashes +for completed views. Root historical docs/scripts are also preserved and checked. + +`RUN.json` is live progress/ETA; `checkpoints/` is recovery state; +`PUBLISH_MANIFEST.json` records exact publishable paths, sizes and SHA256s outside +the release. All 184 sequences, 920 views and 571,645 view-frame entries must pass. +Post-full HTML uses seeded complete sequences covering every subject/object/split +and codec fallback. Human review must pass before the separate local rename +(`--finalize-after-review`); neither mode writes to HF or modifies raw. + +During migration the `shared-v1.0` name can contain maintained v1.1 views. Do not +train, convert or publish from it. Backups and checkpoints are retained, never +deleted to make space. The remote v1.0 remains available until a later authorized +publication. Source `doc/history-v1.0` and `script/v1_0_snapshot` are historical, +not falsely relabelled v1.1 validation or conversion tools. diff --git a/H2O/shared-v1.1/script/h2o_v1_1/full.py b/H2O/shared-v1.1/script/h2o_v1_1/full.py new file mode 100644 index 0000000000000000000000000000000000000000..ce55726ca5e82226bb3af1150879aaace3bb5bdf --- /dev/null +++ b/H2O/shared-v1.1/script/h2o_v1_1/full.py @@ -0,0 +1,701 @@ +#!/usr/bin/env python3 +"""Locked, recoverable in-place H2O v1.1 migration; no HF write operations.""" +import argparse +import ctypes +from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait +from contextlib import contextmanager +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import multiprocessing +import os +from pathlib import Path +import random +import shutil +import subprocess +import sys +import time +import urllib.request + +if __package__: + from .pilot import BASE_DOC_HASHES, PREFIX, REPO, migrate_view, tree, verify_source_file, write_json, stamp +else: + from pilot import BASE_DOC_HASHES, PREFIX, REPO, migrate_view, tree, verify_source_file, write_json, stamp +if __package__: + from .warehouse import Reader, exact, layout, resolve, sha256, validate_view, exact_metadata +else: + from warehouse import Reader, exact, layout, resolve, sha256, validate_view, exact_metadata + +HERE = Path(__file__).resolve().parent +MARKER = 'MIGRATION_MAINTENANCE.json' + + +def sync_dir(path): + fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(fd) + finally: + os.close(fd) + + +def durable_json(path, value): + write_json(path, value) + with Path(path).open('rb') as f: + os.fsync(f.fileno()) + sync_dir(Path(path).parent) + sync_dir(Path(path).parent.parent) + + +@contextmanager +def lock(path): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('a+') as stream: + try: + fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as exc: + raise RuntimeError(f'another migrator holds lock: {path}') from exc + try: + yield + finally: + fcntl.flock(stream, fcntl.LOCK_UN) + + +def tools(): + return {p.relative_to(HERE).as_posix(): sha256(p) for p in sorted(HERE.rglob('*')) + if p.is_file() and '__pycache__' not in p.parts and p.suffix != '.pyc'} + + +def checked_id(view): + parts = Path(view).parts + if len(parts) != 3 or parts[0] != 'data' or any(x in ('', '.', '..') or '\\' in x for x in parts): + raise ValueError(f'invalid view ID: {view}') + return parts[1:] + + +def paths(ctx, view): + seq, cam = checked_id(view) + work = Path(ctx['work']) + source = Path(ctx['source']) / view + stage, backup = work / 'staged' / view, work / 'backups' / view + if any(p.is_symlink() for p in (source, source.parent, source.parent.parent)) or not source.resolve().is_relative_to(Path(ctx['source']).resolve()): + raise ValueError('source view escapes the release') + if not stage.resolve().is_relative_to(work) or not backup.resolve().is_relative_to(work): + raise ValueError('staging/backup path escapes work directory') + return (source, stage, backup, work / 'checkpoints' / seq / (cam + '.json')) + + +def view_files(view): + found = set() + for root, directories, files in os.walk(view, followlinks=False): + for name in directories + files: + if (Path(root) / name).is_symlink(): + raise ValueError('symlinks are not permitted inside a migration view') + found.update((Path(root) / name).relative_to(view).as_posix() for name in files) + return found + + +def checked_hash(path, expected): + if path.is_symlink() or not path.is_file() or sha256(path) != expected: + raise ValueError(f'missing/modified recovery artifact: {path}') + + +def verify_done(ctx, record, rehash_unchanged=True): + source, _, backup, _ = paths(ctx, record['view']) + if record['context'] != ctx: + raise ValueError('checkpoint input/tool fingerprint mismatch') + expected = set(record['unchanged_sha256']) | set(record['changed_sha256']) + if view_files(source) != expected: + raise ValueError('completed view file set mismatch') + for ref, digest in record['changed_sha256'].items(): + checked_hash(resolve(source, ref), digest) + for ref,digest in record['unchanged_sha256'].items(): + path = resolve(source, ref) + if rehash_unchanged: + checked_hash(path, digest) + elif list(stamp(path)) != record['unchanged_stamp'][ref]: + raise ValueError(f'unchanged file modified since fixed-HF hash check: {path}') + for ref in ['metainfo.json', *record['removed_numeric_paths']]: + checked_hash(resolve(backup, ref), record['source_sha256'][ref]) + validate_view(source, ctx['schema']) + old = json.loads((backup / 'metainfo.json').read_text()) + new = json.loads((source / 'metainfo.json').read_text()) + exact_metadata(old, new) + old_reader, new_reader = Reader(backup), Reader(source) + for name, c in old['components'].items(): + if c.get('available') and c['data_ref'].endswith('.pt'): + for kind in ('data', 'valid'): + exact(old_reader.field(c, kind), new_reader.field(new['components'][name], kind)) + return record + + +def install_file(stage, dest, digest): + if dest.exists(): + checked_hash(dest, digest) + return + checked_hash(stage, digest) + dest.parent.mkdir(parents=True, exist_ok=True) + with stage.open('rb') as f: + os.fsync(f.fileno()) + os.replace(stage, dest) + sync_dir(dest.parent) + + +def complete_prepared(ctx, record): + source, stage, backup, checkpoint = paths(ctx, record['view']) + if record['context'] != ctx: + raise ValueError('prepared checkpoint input/tool fingerprint mismatch') + old = json.loads((backup / 'metainfo.json').read_text()) + numeric = {c[k] for c in old['components'].values() if c.get('available') and c['data_ref'].endswith('.pt') + for k in ('data_ref', 'valid_ref')} + if numeric != set(record['removed_numeric_paths']): + raise ValueError('unsafe numerical deletion manifest') + for ref in ['metainfo.json', *sorted(numeric)]: + checked_hash(resolve(backup, ref), record['source_sha256'][ref]) + for ref in record['new_bundle_paths']: + if ref in numeric: + raise ValueError('new bundle collides with an old numerical file') + install_file(stage / ref, source / ref, record['changed_sha256'][ref]) + current_hash = sha256(source / 'metainfo.json') + expected_hash = record['changed_sha256']['metainfo.json'] + if current_hash != expected_hash: + if current_hash != record['source_sha256']['metainfo.json']: + raise ValueError('metadata changed outside migration') + checked_hash(stage / 'metainfo.json', expected_hash) + with (stage / 'metainfo.json').open('rb') as f: + os.fsync(f.fileno()) + os.replace(stage / 'metainfo.json', source / 'metainfo.json') + sync_dir(source) + new = json.loads((source / 'metainfo.json').read_text()) + exact_metadata(old, new) + old_reader, new_reader = Reader(backup), Reader(source) + for name, c in old['components'].items(): + if c.get('available') and c['data_ref'].endswith('.pt'): + for kind in ('data', 'valid'): + exact(old_reader.field(c, kind), new_reader.field(new['components'][name], kind)) + # Only exact manifest entries can be removed; independent media/JSONL valid survives. + parents = set() + for ref in sorted(numeric): + path = source / ref + if path.exists(): + checked_hash(resolve(source, ref), record['source_sha256'][ref]) + path.unlink() + parents.add(path.parent) + for parent in parents: + sync_dir(parent) + validation = validate_view(source, ctx['schema']) + if view_files(source) != set(record['unchanged_sha256']) | set(record['changed_sha256']): + raise ValueError('installed view file set mismatch') + for ref in record['unchanged_sha256']: + if list(stamp(source / ref)) != record['unchanged_stamp'][ref]: + raise ValueError('unchanged file changed during view commit') + record.update(phase='complete', validation=validation) + durable_json(checkpoint, record) + if stage.exists(): + if not stage.resolve().is_relative_to(Path(ctx['work']) / 'staged'): + raise ValueError('unsafe staging cleanup') + shutil.rmtree(stage) # Owned hardlinks only; original media bytes are never changed. + return record + + +def worker(task): + import torch + torch.set_num_threads(1) + if torch.get_num_interop_threads() != 1: + torch.set_num_interop_threads(1) + ctx, view, inventory = task + source, stage, backup, checkpoint = paths(ctx, view) + with lock(Path(ctx['work']) / 'view-locks' / (view.replace('/', '__') + '.lock')): + if checkpoint.exists(): + record = json.loads(checkpoint.read_text()) + if record['phase'] == 'complete': + result = verify_done(ctx, record) + if stage.exists(): + shutil.rmtree(stage) + return result + if record['phase'] == 'prepared': + return complete_prepared(ctx, record) + raise ValueError('unknown checkpoint phase') + view_files(source) + # An uncommitted stage may be discarded only after confirming the source is v1.0. + meta = json.loads((source / 'metainfo.json').read_text()) + if meta['schema_version'] != 'hand-warehouse/1.0': + raise ValueError('migrated view has no recoverable checkpoint') + for candidate in (stage, stage.with_name('.tmp-' + stage.name)): + if candidate.exists(): + if not candidate.resolve().is_relative_to(Path(ctx['work']) / 'staged'): + raise ValueError('unsafe incomplete-stage cleanup') + shutil.rmtree(candidate) + record = migrate_view((str(source), str(stage), ctx['schema'], inventory)) + for ref in ['metainfo.json', *record['removed_numeric_paths']]: + dest = backup / ref + dest.parent.mkdir(parents=True, exist_ok=True) + if not dest.exists(): + os.link(resolve(source, ref), dest) + checked_hash(dest, record['source_sha256'][ref]) + for directory, _, _ in os.walk(backup, topdown=False): + sync_dir(directory) + for directory in (backup.parent, backup.parent.parent, backup.parent.parent.parent): + sync_dir(directory) + record.update(phase='prepared', context=ctx) + durable_json(checkpoint, record) + sync_dir(Path(ctx['work'])) + return complete_prepared(ctx, record) + + + +def audit_worker(task): + import torch + torch.set_num_threads(1) + ctx, view, _ = task + checkpoint = paths(ctx, view)[-1] + record = json.loads(checkpoint.read_text()) + if record['phase'] != 'complete': + raise ValueError('final audit requires a completed checkpoint') + return verify_done(ctx, record, rehash_unchanged=False) + +def current_remote(revision): + fixed = tree(revision, 'H2O') + with urllib.request.urlopen('https://huggingface.co/api/datasets/' + REPO + '?expand=sha', timeout=90) as response: + head = json.load(response)['sha'] + live = tree(head, 'H2O') + for name in ('raw', 'shared-v1.0'): + path = 'H2O/' + name + if fixed[path]['oid'] != live[path]['oid']: + raise ValueError(f'HF {path} changed since source revision; investigate before migration') + return {'head': head, 'raw_tree_oid': fixed['H2O/raw']['oid'], + 'source_tree_oid': fixed[PREFIX]['oid']} + + + +def check_consumers(source): + executable = shutil.which('lsof') + if not executable: + raise RuntimeError('lsof required to check active dataset readers before maintenance') + result = subprocess.run([executable, '-u', str(os.getuid()), '-F', 'pn'], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=60) + if result.returncode not in (0, 1): + raise RuntimeError('could not check dataset readers with lsof') + readers, pid = set(), None + prefix = str(source / 'data') + '/' + for line in result.stdout.splitlines(): + if line.startswith('p'): + pid = line[1:] + elif line.startswith('n' + prefix) and not Path(line[1:]).is_dir(): + readers.add(pid) + if readers: + raise RuntimeError('close active readers/converters before migration; PIDs: ' + ','.join(sorted(readers))) + + +def prepare(source, work, revision, approval): + for name, expected in BASE_DOC_HASHES.items(): + checked_hash(source / 'doc' / name, expected) + approved = json.loads(approval.read_text()) + if (not approved.get('passed') or approved['source_revision'] != revision + or approved.get('views') != 50 or approved.get('numeric_components') != 300): + raise ValueError('approved pilot must have passed automated checks on the same fixed source') + check_consumers(source) + remote = current_remote(revision) + marker = source / MARKER + if marker.exists(): + raise ValueError('unregistered source maintenance marker') + root_hashes = {} + for folder in ('doc', 'script'): + prefix = PREFIX + '/' + entries = tree(revision, prefix + folder, recursive=True) + expected_files = {k.removeprefix(prefix):v for k,v in entries.items() if v['type'] == 'file'} + actual = {folder + '/' + f.relative_to(source / folder).as_posix() + for f in (source / folder).rglob('*') if f.is_file() and f.suffix != '.pyc'} + if actual != set(expected_files): + raise ValueError('root document/script file set differs from fixed HF') + for ref,entry in expected_files.items(): + root_hashes[ref] = verify_source_file(resolve(source, ref), entry) + work.mkdir(parents=True, exist_ok=True) + if source.stat().st_dev != work.stat().st_dev: + raise ValueError('source, work and rollback backups must share a filesystem') + (work / 'inventory').mkdir(exist_ok=True) + for name in ('data', 'doc', 'script'): + if (source / name).is_symlink(): + raise ValueError('source release directories must not be symlinks') + seqs = sorted(p.name for p in (source / 'data').iterdir() if p.is_dir()) + if len(seqs) != 184: + raise ValueError('full H2O migration requires exactly 184 sequences') + for seq in seqs: + views = sorted((source / 'data' / seq).iterdir()) + if [p.name for p in views] != [f'cam{i}' for i in range(5)] or any(not p.is_dir() or not (p / 'metainfo.json').is_file() for p in views): + raise ValueError('full H2O migration requires five complete cameras per sequence') + plan = {'source': str(source), 'source_revision': revision, 'sequences': seqs, + 'tool_sha256': tools(), 'remote_baseline': remote, 'root_source_sha256': root_hashes, 'pilot_summary_sha256': sha256(approval), + 'human_pilot_approval': {'date': '2026-10-10', 'scope': 'user reviewed index.html; individual page coverage unspecified', + 'authorization': '我看了index.html没有问题。试点通过,开始全量'}, 'views': 920} + durable_json(work / 'PLAN.json', plan) + durable_json(work / 'RUN.json', {'phase': 'preparing_inventory', 'completed_views': 0, + 'created_utc': datetime.now(timezone.utc).isoformat()}) + return plan + + +def prepare_inventory(plan, work): + index_path = work / 'INVENTORY_INDEX.json' + index = json.loads(index_path.read_text()) if index_path.exists() else {} + for i, seq in enumerate(plan['sequences']): + path = work / 'inventory' / (seq + '.json') + if seq in index: + checked_hash(path, index[seq]) + else: + rows = tree(plan['source_revision'], PREFIX + '/data/' + seq, recursive=True) + files = {k.removeprefix(PREFIX + '/'): v for k, v in rows.items() if v['type'] == 'file'} + durable_json(path, {'revision': plan['source_revision'], 'files': files}) + index[seq] = sha256(path) + durable_json(index_path, index) + if (i + 1) % 50 == 0: + print('FULL_INVENTORY', i + 1, '/', len(plan['sequences']), flush=True) + if set(index) != set(plan['sequences']): + raise ValueError('inventory sequence set mismatch') + return index + + +def tasks(plan, work, index): + ctx = {'source': plan['source'], 'work': str(work), 'schema': str(HERE / 'spec/schema.json'), + 'source_revision': plan['source_revision'], 'tool_sha256': plan['tool_sha256']} + for seq in plan['sequences']: + path = work / 'inventory' / (seq + '.json') + checked_hash(path, index[seq]) + inventory = json.loads(path.read_text()) + if inventory['revision'] != plan['source_revision']: + raise ValueError('inventory revision mismatch') + for cam in sorted((Path(plan['source']) / 'data' / seq).iterdir()): + if not cam.is_dir(): + raise ValueError('unexpected sequence entry') + view = 'data/' + seq + '/' + cam.name + prefix = view + '/' + files = {k.removeprefix(prefix): v for k, v in inventory['files'].items() if k.startswith(prefix)} + yield (ctx | {'inventory_sha256': index[seq]}, view, files) + + +def bounded_pool(jobs, workers, on_result, worker_fn=worker): + iterator = iter(jobs) + pool = ProcessPoolExecutor(max_workers=workers, mp_context=multiprocessing.get_context('spawn')) + active = {} + try: + for _ in range(workers): + task = next(iterator, None) + if task is not None: + active[pool.submit(worker_fn, task)] = task[1] + while active: + done, _ = wait(active, return_when=FIRST_COMPLETED) + # Check all finished futures before scheduling any new work after a failure. + results = [(f, f.result()) for f in done] + for future, result in results: + del active[future] + on_result(result) + task = next(iterator, None) + if task is not None: + active[pool.submit(worker_fn, task)] = task[1] + finally: + for future in active: + future.cancel() + pool.shutdown(wait=True, cancel_futures=True) + + +def post_sample(source, seed): + rng = random.Random(seed) + candidates = [] + for seq in sorted((source / 'data').iterdir()): + meta = json.loads((seq / 'cam0/metainfo.json').read_text()) + features = {'subject:' + seq.name.split('_')[0], 'split:' + meta['split']} + features |= {'object:' + name.removeprefix('pose_') for name,c in meta['components'].items() + if name.startswith('pose_') and c.get('available')} + if seq.name == 'subject1_k2_6': + features.add('rgb:h264_fallback') + candidates.append((seq.name, features)) + rng.shuffle(candidates) + remaining = set().union(*(features for _,features in candidates)) + chosen = [] + while remaining: + name, features = max((item for item in candidates if item[0] not in chosen), + key=lambda item: len(item[1] & remaining)) + chosen.append(name) + remaining -= features + return {'sequences': sorted(chosen), 'seed': seed, + 'scope': 'seeded representative complete sequences covering subjects, splits, all object classes and codec fallback; all five cameras'} + + +def install_documents(source, work, plan, summary): + # Root doc/script switches are recoverable two-step renames under maintenance. + pending = work / 'new-doc' + history = work / 'old-doc' + doc_installed = (source / 'doc/history-v1.0/schema.json').is_file() + if doc_installed and sha256(source / 'doc/schema.json') != sha256(HERE / 'spec/schema.json'): + raise ValueError('unexpected existing documentation history') + if not doc_installed and not history.exists() and not (pending / 'history-v1.0').exists(): + if pending.exists(): + shutil.rmtree(pending) + if not pending.exists(): + pending.mkdir() + for name in ('schema.json', 'MIGRATION.md'): + shutil.copyfile(HERE / 'spec' / name, pending / name) + original_contract = (source / 'doc/CONTRACT.md').read_bytes() + (pending / 'V1_0_SEMANTICS.md').write_bytes(original_contract) + contract = (HERE / 'spec/CONTRACT.md').read_text().replace('../hand-warehouse-1.0/CONTRACT.md', 'V1_0_SEMANTICS.md') + contract = '\n'.join('状态:H2O v1.1 配套注册表与读写工具已适配;本地全量自动验收完成后仍须人工复查,HF 尚未发布。' if line.startswith('状态:合同草案') else line for line in contract.splitlines()) + (pending / 'CONTRACT.md').write_text('> H2O v1.1 本地全量迁移;当前等待人工复查,尚未正式发布。\n\n' + contract) + pilot_doc = Path(plan['pilot_root']) / 'doc/RAW_TO_SHARED.md' + mapping = pilot_doc.read_text().replace('试点未修改源发布或 HF。', '本次仅原地调整 shared 数值存储,不修改 raw,不重编码媒体。') + mapping = mapping.replace('(迁移试点)', '(本地全量迁移)').replace('当前为 v1.1 存储迁移试点。', '当前为 v1.1 本地全量存储迁移。').replace('全量迁移和发布仍待人工批准。', '全量自动检查完成;全量后人工复查和 HF 发布尚待批准。') + (pending / 'RAW_TO_SHARED.md').write_text(mapping + '\n\n全量入口:script/h2o_v1_1/full.py。原 v1.0 文档及构建记录保留于 history-v1.0/;旧转换实现及配套规范在 script/v1_0_snapshot/。\n') + for f in pending.rglob('*'): + if f.is_file(): + with f.open('rb') as stream: + os.fsync(stream.fileno()) + sync_dir(pending) + os.replace(source / 'doc', history) + sync_dir(source) + sync_dir(work) + if history.exists() and not (pending / 'history-v1.0').exists() and pending.exists(): + os.replace(history, pending / 'history-v1.0') + sync_dir(pending) + sync_dir(work) + if pending.exists(): + if (source / 'doc').exists(): + raise ValueError('refuse to overwrite unexpected doc directory') + os.replace(pending, source / 'doc') + sync_dir(source) + if not (source / 'doc/history-v1.0/schema.json').is_file(): + raise ValueError('original documentation history missing') + old_script, new_script = work / 'old-script', work / 'new-script' + if not old_script.exists(): + if new_script.exists(): + shutil.rmtree(new_script) + if not new_script.exists(): + new_script.mkdir() + shutil.copytree(HERE, new_script / 'h2o_v1_1', ignore=shutil.ignore_patterns('__pycache__', '*.pyc')) + shutil.copytree(source / 'script', new_script / 'v1_0_snapshot/script', ignore=shutil.ignore_patterns('__pycache__', '*.pyc')) + (new_script / 'v1_0_snapshot/doc').mkdir() + for name in BASE_DOC_HASHES: + shutil.copyfile(source / 'doc/history-v1.0' / name, new_script / 'v1_0_snapshot/doc' / name) + for f in new_script.rglob('*'): + if f.is_file(): + with f.open('rb') as stream: + os.fsync(stream.fileno()) + for directory, _, _ in os.walk(new_script, topdown=False): + sync_dir(directory) + os.replace(source / 'script', old_script) + sync_dir(source) + sync_dir(work) + if new_script.exists(): + if (source / 'script').exists(): + raise ValueError('refuse to overwrite unexpected script directory') + os.replace(new_script, source / 'script') + sync_dir(source) + for ref,digest in plan.get('root_source_sha256', {}).items(): + folder,relative = ref.split('/',1) + path = (source / 'doc/history-v1.0' / relative if folder == 'doc' else + source / 'script/v1_0_snapshot/script' / relative) + checked_hash(path, digest) + durable_json(source / 'doc/FULL_MIGRATION_SUMMARY.json', summary) + + + + +def publish_manifest(source, work, plan, state): + """Reuse the already-checked media digest; do not read 644 GB a second time.""" + files = {} + for seq in plan['sequences']: + for cam in range(5): + record = json.loads((work / 'checkpoints' / seq / f'cam{cam}.json').read_text()) + if record['phase'] != 'complete': + raise ValueError('release manifest requires all completed views') + for ref,digest in (record['unchanged_sha256'] | record['changed_sha256']).items(): + key = record['view'] + '/' + ref + if key in files: + raise ValueError('duplicate release path') + files[key] = {'sha256':digest, 'size':(source / key).stat().st_size} + for folder in ('doc','script'): + for path in sorted((source / folder).rglob('*')): + if path.is_file() and path.suffix != '.pyc' and '__pycache__' not in path.parts: + if path.is_symlink(): + raise ValueError('symlinks cannot be published') + files[path.relative_to(source).as_posix()] = {'sha256':sha256(path), 'size':path.stat().st_size} + actual = {p.relative_to(source).as_posix() for p in source.rglob('*') if p.is_file() + and p.name != MARKER and p.suffix != '.pyc' and '__pycache__' not in p.parts} + if actual != set(files): + raise ValueError('release manifest file set mismatch') + durable_json(work / 'PUBLISH_MANIFEST.json', {'release_id':'shared-v1.1', + 'source_revision':plan['source_revision'], 'raw_tree_oid':plan['remote_baseline']['raw_tree_oid'], + 'phase':state['phase'], 'files':files, 'file_count':len(files), + 'excluded_runtime_files':['*.pyc','__pycache__',MARKER], + 'scope':'data hashes verified against fixed HF / exact new bundles; docs and code freshly hashed; publication not performed'}) + +def rename_no_replace(source, target): + # Linux renameat2 keeps the no-overwrite rule atomic, even for an empty target. + fn = ctypes.CDLL(None, use_errno=True).renameat2 + fn.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint] + fn.restype = ctypes.c_int + if fn(-100, os.fsencode(source), -100, os.fsencode(target), 1) != 0: + code = ctypes.get_errno() + raise OSError(code, os.strerror(code), str(target)) + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--source', type=Path, required=True) + p.add_argument('--work', type=Path, required=True) + p.add_argument('--source-revision', required=True) + p.add_argument('--pilot-summary', type=Path, required=True) + p.add_argument('--workers', type=int, default=4) + p.add_argument('--human-pilot-approved', action='store_true') + p.add_argument('--finalize-after-review', action='store_true') + args = p.parse_args(argv) + if not args.human_pilot_approved and not args.finalize_after_review: + p.error('explicit --human-pilot-approved required before full migration') + source, work = args.source.resolve(), args.work.resolve() + if (source.name != 'shared-v1.0' or source.parent.name != 'H2O' + or not work.is_relative_to(source.parent / 'tmp') or work == source.parent / 'tmp'): + p.error('require H2O/shared-v1.0 and a dedicated work directory under H2O/tmp') + if not 1 <= args.workers <= 8: + p.error('1–8 view workers; one Torch thread per worker') + target = source.with_name('shared-v1.1') + recovering_rename = (args.finalize_after_review and not source.exists() and target.is_dir() + and (work / 'RUN.json').is_file() + and json.loads((work / 'RUN.json').read_text())['phase'] in + ('finalizing_local', 'local_finalized_not_uploaded')) + if (not source.is_dir() or target.exists()) and not recovering_rename: + p.error('source missing or target shared-v1.1 already exists; do not overwrite/merge') + if shutil.disk_usage(source.parent).free < 20 * 1024**3: + p.error('need at least 20 GiB free for bundles, checkpoints and rollback') + if work.exists() and not (work / 'PLAN.json').exists(): + p.error('existing unregistered work directory; refuse to overwrite') + for key in ('OMP_NUM_THREADS', 'MKL_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'NUMEXPR_NUM_THREADS', 'HAND_WAREHOUSE_FFMPEG_THREADS'): + os.environ[key] = '1' + with lock(source.parent / 'tmp/H2O_V1_1.lock'): + if (work / 'PLAN.json').exists(): + plan = json.loads((work / 'PLAN.json').read_text()) + if plan['source'] != str(source) or plan['source_revision'] != args.source_revision or plan['tool_sha256'] != tools(): + raise ValueError('resume source/tool fingerprint mismatch') + else: + plan = prepare(source, work, args.source_revision, args.pilot_summary.resolve()) + plan['pilot_root'] = str(args.pilot_summary.resolve().parents[2]) + durable_json(work / 'PLAN.json', plan) + state = json.loads((work / 'RUN.json').read_text()) + if state['phase'] == 'local_finalized_not_uploaded': + final_marker = target / MARKER + if final_marker.exists(): + if json.loads(final_marker.read_text())['work'] != str(work): + raise ValueError('foreign maintenance marker on final target') + final_marker.unlink(); sync_dir(target) + print('LOCAL_FINALIZED', state['final_root'], 'HF publication not performed', flush=True) + return + marker = (target if recovering_rename else source) / MARKER + if recovering_rename and not marker.is_file(): + raise ValueError('renamed target lacks its owned recovery marker') + if marker.exists() and json.loads(marker.read_text())['work'] != str(work): + raise ValueError('another work directory owns maintenance state') + durable_json(marker, {'work': str(work), 'phase': state['phase'], 'source_revision': args.source_revision, + 'notice': 'maintenance: no training/conversion/upload; HTML review only'}) + if args.finalize_after_review: + if state['phase'] not in ('awaiting_full_human_review', 'finalizing_local'): + raise ValueError('finalize requires completed full checks and separate human approval') + if source.exists(): + check_consumers(source) + manifest = json.loads((work / 'PUBLISH_MANIFEST.json').read_text()) + for ref,entry in manifest['files'].items(): + if not ref.startswith('data/'): + checked_hash(resolve(source, ref), entry['sha256']) + index = json.loads((work / 'INVENTORY_INDEX.json').read_text()) + bounded_pool(tasks(plan, work, index), args.workers, lambda _:None, audit_worker) + state['phase'] = 'finalizing_local' + durable_json(work / 'RUN.json', state) + rename_no_replace(source, target) + elif not marker.is_file() or json.loads(marker.read_text())['work'] != str(work): + raise ValueError('renamed target is not owned by this maintenance operation') + sync_dir(source.parent) + state.update(phase='local_finalized_not_uploaded', final_root=str(target)) + state['human_full_approval'] = {'authorization':'--finalize-after-review', 'recorded_utc':datetime.now(timezone.utc).isoformat()} + state['index_html'] = str(source.with_name('shared-v1.1') / 'doc/validation/index.html') + summary_path = source.with_name('shared-v1.1') / 'doc/validation/FULL_MIGRATION_SUMMARY.json' + summary = json.loads(summary_path.read_text()) + durable_json(summary_path, summary | state) + final_root = source.with_name('shared-v1.1') + durable_json(final_root / 'doc/FULL_MIGRATION_SUMMARY.json', summary | state) + publish_manifest(final_root, work, plan, state) + durable_json(work / 'RUN.json', state) + (final_root / MARKER).unlink() + sync_dir(final_root) + print('LOCAL_FINALIZED', state['final_root'], 'HF upload still requires separate authorization', flush=True) + return + if state['phase'] == 'awaiting_full_human_review': + print('AWAITING_FULL_HUMAN_REVIEW', source / 'doc/validation/index.html', flush=True) + return + try: + started = time.monotonic() + if state.get('inventory_index_sha256'): + checked_hash(work / 'INVENTORY_INDEX.json', state['inventory_index_sha256']) + index = prepare_inventory(plan, work) + state.update(phase='migrating', completed_views=0, workers=args.workers, + inventory_index_sha256=sha256(work / 'INVENTORY_INDEX.json')) + durable_json(work / 'RUN.json', state) + durable_json(marker, {'work': str(work), 'phase': 'migrating', 'source_revision': args.source_revision, + 'notice': 'maintenance: no training/conversion/upload; HTML review only'}) + totals = {'num_frames': 0, 'source_files': 0, 'target_files': 0} + def progress(record): + state['completed_views'] += 1 + for k in totals: + totals[k] += record[k] + if state['completed_views'] % 10 == 0: + state.update(totals, elapsed_seconds=time.monotonic() - started) + durable_json(work / 'RUN.json', state) + state['estimated_remaining_seconds'] = state['elapsed_seconds'] * (920-state['completed_views']) / state['completed_views'] + durable_json(work / 'RUN.json', state) + print('FULL_PROGRESS', state['completed_views'], '/ 920', round(state['elapsed_seconds'], 1), 'seconds', 'ETA', round(state['estimated_remaining_seconds']), flush=True) + bounded_pool(tasks(plan, work, index), args.workers, progress) + if state['completed_views'] != 920 or totals['num_frames'] != 571645: + raise ValueError('full view/frame coverage mismatch') + state.update(phase='final_verification', **totals, elapsed_seconds=time.monotonic() - started) + durable_json(work / 'RUN.json', state) + # Second pass checks current output hashes, all keys and rollback numerical bytes. + verified = 0 + def verified_progress(_): + nonlocal verified + verified += 1 + if verified % 100 == 0: + print('FULL_VERIFIED', verified, '/ 920', flush=True) + bounded_pool(tasks(plan, work, index), args.workers, verified_progress, audit_worker) + if verified != 920: + raise ValueError('final verification incomplete') + summary = state | {'phase': 'full_numeric_passed_pending_post_sample', + 'source_revision': args.source_revision, 'raw_tree_oid': plan['remote_baseline']['raw_tree_oid'], + 'all_numeric_bytes_exact': True, 'all_source_data_files_match_fixed_hf': True, + 'all_changed_file_hashes_verified': True, 'unchanged_file_fingerprints_stable': True, + 'media_verification': 'one encoded-file hash pass against fixed HF; unchanged inode/size/mtime rechecked under maintenance; no all-video pixel comparison', 'backup_root': str(work / 'backups'), + 'saved_data_files': totals['source_files'] - totals['target_files'], + 'scope': '184 sequences, 920 cameras, 571645 view-frame entries (114329 synchronized frames); human post-full review and HF publication pending'} + state['phase'] = 'installing_documents' + durable_json(work / 'RUN.json', state) + install_documents(source, work, plan, summary) + sampled = post_sample(source, args.source_revision + ':post-full:2026-10-10') + durable_json(work / 'POST_FULL_SAMPLE.json', sampled) + state['phase'] = 'rendering_post_full_sample' + durable_json(work / 'RUN.json', state) + subprocess.run([sys.executable, str(source / 'script/h2o_v1_1/render.py'), str(source), + '--workers', str(args.workers), '--sequences-file', str(work / 'POST_FULL_SAMPLE.json')], check=True) + current = current_remote(args.source_revision) + if current['raw_tree_oid'] != plan['remote_baseline']['raw_tree_oid']: + raise ValueError('HF raw tree changed') + state.update(phase='awaiting_full_human_review', elapsed_seconds=time.monotonic() - started, + index_html=str(source / 'doc/validation/index.html'), hf_writes=False) + durable_json(work / 'RUN.json', state) + durable_json(source / 'doc/validation/FULL_MIGRATION_SUMMARY.json', summary | state) + durable_json(source / 'doc/FULL_MIGRATION_SUMMARY.json', summary | state) + publish_manifest(source, work, plan, state) + durable_json(marker, {'work': str(work), 'phase': state['phase'], 'notice': 'full local checks passed; await human post-full review before rename/upload'}) + print('FULL_LOCAL_DONE_AWAITING_REVIEW', state['index_html'], flush=True) + except Exception as exc: + state.update(failed_phase=state['phase'], phase='failed', error=repr(exc)) + durable_json(work / 'RUN.json', state) + print('FULL_FAILED_RECOVERABLE', repr(exc), 'work', work, flush=True) + raise + + +if __name__ == '__main__': + main() diff --git a/H2O/shared-v1.1/script/h2o_v1_1/pilot.py b/H2O/shared-v1.1/script/h2o_v1_1/pilot.py new file mode 100644 index 0000000000000000000000000000000000000000..370f8f6b6140830dc2136cfd8f62fd8a2d7d47da --- /dev/null +++ b/H2O/shared-v1.1/script/h2o_v1_1/pilot.py @@ -0,0 +1,344 @@ +#!/usr/bin/env python3 +"""Read-only-source H2O v1.1 pilot; HF is read-only, full migration is gated.""" +import argparse +from concurrent.futures import ProcessPoolExecutor, as_completed +from datetime import datetime, timezone +import hashlib +import fcntl +import json +import multiprocessing +import os +from pathlib import Path +import re +import shutil +import time +import urllib.parse +import urllib.request +import urllib.error + +if __package__: + from .warehouse import PROFILE, Reader, exact, layout, resolve, sha256, validate_view, exact_metadata +else: + from warehouse import PROFILE, Reader, exact, layout, resolve, sha256, validate_view, exact_metadata + +REPO = 'ParityLab/Hand-Datasets-Raw' +PREFIX = 'H2O/shared-v1.0' +BASE_DOC_HASHES = { + 'CONTRACT.md': '8c0a0caa3d66a3984278dea36a5f18e925f2b878fb926f6b9ef41b76a4f37784', + 'schema.json': '4b60ce367de7703ca07b7f016a844fc457da0e1040bbda1f0dd9486cc34bd5d2', +} + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(path.name + '.tmp') + tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + '\n') + os.replace(tmp, path) + + +def tree(revision, folder, recursive=False): + if not re.fullmatch(r'[0-9a-f]{40}', revision): + raise ValueError('source revision must be a fixed commit SHA') + url = 'https://huggingface.co/api/datasets/' + REPO + '/tree/' + revision + '/' + urllib.parse.quote(folder, safe='/') + url += '?recursive=' + str(recursive).lower() + '&limit=1000' + result = {} + while url: + if urllib.parse.urlsplit(url).hostname != 'huggingface.co': + raise ValueError('untrusted pagination URL') + for attempt in range(5): + try: + response = urllib.request.urlopen(url, timeout=90) + break + except (urllib.error.URLError, TimeoutError) as exc: + if isinstance(exc, urllib.error.HTTPError) and exc.code not in (429,500,502,503,504): + raise + if attempt == 4: + raise + retry = exc.headers.get('Retry-After', '') if isinstance(exc, urllib.error.HTTPError) else '' + delay = min(60, int(retry)) if retry.isdigit() else min(30, 2**attempt) + print('HF_READ_RETRY', attempt+1, 'delay', delay, flush=True) + time.sleep(delay) + with response: + for row in json.load(response): + if row['path'] in result: + raise ValueError('duplicate HF inventory path') + result[row['path']] = row + link = response.headers.get('Link', '') + match = re.search(r'<([^>]+)>;\s*rel="next"', link) + url = match[1] if match else None + return result + + +def stamp(path): + s = path.stat() + return s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns + + +def verify_source_file(path, entry): + before = stamp(path) + if path.is_symlink() or before[2] != entry['size']: + raise ValueError(f'source size/symlink mismatch: {path}') + sha = hashlib.sha256() + git = hashlib.sha1(f'blob {entry["size"]}\0'.encode()) + with path.open('rb') as stream: + while chunk := stream.read(4 * 1024 * 1024): + sha.update(chunk) + if not entry.get('lfs'): + git.update(chunk) + expected = entry['lfs'].get('oid', entry['lfs'].get('sha256')) if entry.get('lfs') else entry['oid'] + digest = sha.hexdigest() if entry.get('lfs') else git.hexdigest() + if digest != expected or stamp(path) != before: + raise ValueError(f'local source differs from fixed HF commit or changed during read: {path}') + return sha.hexdigest() + + +def select_sequences(source): + candidates = {} + for seq in sorted((source / 'data').iterdir()): + views = sorted(seq.iterdir()) + if [v.name for v in views] != [f'cam{i}' for i in range(5)] or any(not v.is_dir() for v in views): + raise ValueError(f'expected five complete camera views: {seq}') + meta = json.loads((views[0] / 'metainfo.json').read_text()) + features = {'subject:' + seq.name.split('_')[0], 'split:' + meta['split']} + features |= {'object:' + n.removeprefix('pose_') for n,c in meta['components'].items() + if n.startswith('pose_') and c.get('available')} + receipt = source / 'doc' / (seq.name + '.build.json') + if receipt.is_file(): + annotations = json.loads(receipt.read_text())['views'] + for view in annotations.values(): + for n,c in view.get('annotation_validity', {}).items(): + features.add('valid:' + n.split('_', 1)[0] + ':' + + ('mixed' if c.get('valid_count', 0) and c.get('invalid_count', 0) else + 'invalid' if c.get('invalid_count', 0) else 'valid')) + if seq.name == 'subject1_k2_6': + features.add('rgb:h264_fallback') + candidates[seq.name] = (features, meta['num_frames']) + if not candidates: + raise ValueError('empty dataset') + remaining = set().union(*(f for f,_ in candidates.values())) + chosen = [] + while remaining: + name = max((n for n in candidates if n not in chosen), + key=lambda n: (len(candidates[n][0] & remaining), n)) + chosen.append(name) + remaining -= candidates[name][0] + for name in (min(candidates, key=lambda n: candidates[n][1]), max(candidates, key=lambda n: candidates[n][1])): + if name not in chosen: + chosen.append(name) + return sorted(chosen), sorted(set().union(*(candidates[n][0] for n in chosen))) + + +def migrate_view(task): + import torch + torch.set_num_threads(1) + if torch.get_num_interop_threads() != 1: + torch.set_num_interop_threads(1) + source, target, schema_path, inventory = task + source, target = Path(source), Path(target) + started = time.monotonic() + original = json.loads((source / 'metainfo.json').read_text()) + if original['schema_version'] != 'hand-warehouse/1.0' or original['release_id'] != 'shared-v1.0': + raise ValueError('source must be the unmigrated v1.0 release') + if original.get('dataset_id') != 'H2O' or original['camera_id'] != source.name or target.name != source.name: + raise ValueError('H2O camera metadata/path mismatch') + meta = json.loads(json.dumps(original)) + reader, bundles, replaced, source_hashes = Reader(source), {}, set(), {} + actual = {p.relative_to(source).as_posix(): p for p in source.rglob('*') if p.is_file()} + if any(p.is_symlink() for p in source.rglob('*')): + raise ValueError('source symlinks are not permitted') + before = {ref: stamp(path) for ref,path in actual.items()} + verify_started = time.monotonic() + if set(actual) != set(inventory): + raise ValueError(f'local vs HF source file set mismatch: {source}') + print('VERIFY_VIEW', '/'.join(source.parts[-2:]), flush=True) + for ref, path in actual.items(): + source_hashes[ref] = verify_source_file(path, inventory[ref]) + verify_seconds = time.monotonic() - verify_started + pack_started = time.monotonic() + for name, c in meta['components'].items(): + if not c.get('available') or not c['data_ref'].endswith('.pt'): + continue + ref, keys = layout(name, c) + data, valid = reader.field(c), reader.field(c, 'valid') + if valid.dtype != torch.bool: + raise ValueError('source validity must be bool') + replaced.update((c['data_ref'], c['valid_ref'])) + node = bundles.setdefault(ref, {}) + for key in keys[:-1]: + node = node.setdefault(key, {}) + if keys[-1] in node: + raise ValueError('duplicate numeric bundle field') + node[keys[-1]] = {'data': data, 'valid': valid} + c.update(data_ref=ref, data_key=keys + ['data'], valid_ref=ref, valid_key=keys + ['valid'], + storage={'profile': PROFILE}, valid_storage={'profile': PROFILE}) + if target.exists(): + raise ValueError(f'target already exists: {target}') + staging = target.with_name('.tmp-' + target.name) + staging.mkdir(parents=True, exist_ok=False) + unchanged = {} + for ref, path in actual.items(): + if ref in replaced or ref == 'metainfo.json': + continue + dest = staging / ref + dest.parent.mkdir(parents=True, exist_ok=True) + os.link(path, dest) # Pilot only: unchanged files share storage; never write these links. + if not os.path.samefile(path, dest) or stamp(path) != before[ref]: + raise ValueError(f'unchanged file mismatch: {ref}') + unchanged[ref] = source_hashes[ref] + for ref, bundle in bundles.items(): + dest = staging / ref + dest.parent.mkdir(parents=True, exist_ok=True) + tmp = dest.with_name(dest.name + '.tmp') + torch.save(bundle, tmp) + os.replace(tmp, dest) + meta.update(schema_version='hand-warehouse/1.1', release_id='shared-v1.1') + write_json(staging / 'metainfo.json', meta) + validation = validate_view(staging, schema_path) + saved = Reader(staging) + for name, old in original['components'].items(): + if old.get('available') and old['data_ref'].endswith('.pt'): + for kind in ('data', 'valid'): + exact(reader.field(old, kind), saved.field(meta['components'][name], kind)) + elif old != meta['components'][name]: + raise ValueError('non-numerical component metadata changed') + exact_metadata(original, meta) + output_hashes = {p.relative_to(staging).as_posix(): sha256(p) + for p in staging.rglob('*') if p.is_file() and p.relative_to(staging).as_posix() not in unchanged} + if any(stamp(path) != before[ref] for ref,path in actual.items()): + raise ValueError('source changed during migration; retain private staging for investigation') + os.replace(staging, target) + return {'view': '/'.join(target.parts[-3:]), 'num_frames': meta['num_frames'], + 'seconds': time.monotonic() - started, 'verify_seconds': verify_seconds, + 'pack_seconds': time.monotonic() - pack_started, + 'source_bytes': sum(s[2] for s in before.values()), 'source_sha256': source_hashes, + 'unchanged_sha256': unchanged, + 'unchanged_stamp': {ref:list(before[ref]) for ref in unchanged}, 'changed_sha256': output_hashes, + 'removed_numeric_paths': sorted(replaced), 'new_bundle_paths': sorted(bundles), + 'source_files': len(actual), 'target_files': len(unchanged) + len(output_hashes), + 'numeric_bytes_exact': True, 'source_matches_fixed_hf': True, 'validation': validation} + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--source', required=True, type=Path) + p.add_argument('--out', required=True, type=Path) + p.add_argument('--source-revision', required=True) + p.add_argument('--workers', type=int, default=4) + args = p.parse_args(argv) + source, out = args.source.resolve(), args.out.resolve() + if not 1 <= args.workers <= 8: + p.error('pilot supports 1–8 workers, one Torch thread per worker') + if out.exists() or out.is_relative_to(source) or source.is_relative_to(out): + p.error('pilot output must be a new directory outside the source release') + if source.stat().st_dev != out.parent.stat().st_dev: + p.error('pilot must be on the same filesystem; unchanged media are hardlinked, not copied') + for name, expected in BASE_DOC_HASHES.items(): + if sha256(source / 'doc' / name) != expected: + raise ValueError('source contract/schema differ from the verified fixed HF version') + lock = (out.parent / 'h2o-v1.1-pilot.lock').open('a') + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + chosen, coverage = select_sequences(source) + print('PILOT_SELECTION', json.dumps({'sequences':chosen, 'views':5*len(chosen), 'coverage':coverage}), flush=True) + started = time.monotonic() + baseline = tree(args.source_revision, 'H2O') + if 'H2O/shared-v1.1' in baseline: + raise ValueError('pinned source already has shared-v1.1; investigate before proceeding') + raw_oid = baseline['H2O/raw']['oid'] + remote = tree(args.source_revision, PREFIX + '/script', recursive=True) + remote.update({k:v for k,v in tree(args.source_revision, PREFIX + '/doc').items() + if k.rsplit('/',1)[-1] in (*BASE_DOC_HASHES, 'RAW_TO_SHARED.md')}) + baseline_hashes = {} + for key,entry in remote.items(): + if entry['type'] == 'file': + ref = key.removeprefix(PREFIX + '/') + baseline_hashes[ref] = verify_source_file(resolve(source, ref), entry) + actual_scripts = {'script/' + f.relative_to(source / 'script').as_posix() + for f in (source / 'script').rglob('*') if f.is_file() and f.suffix != '.pyc'} + if actual_scripts != {ref for ref in baseline_hashes if ref.startswith('script/')}: + raise ValueError('local source scripts do not match fixed HF file set') + out.mkdir() + doc, scripts = out / 'doc', out / 'script' + doc.mkdir() + scripts.mkdir() + here = Path(__file__).resolve().parent + shutil.copytree(here, scripts / 'h2o_v1_1', ignore=shutil.ignore_patterns('__pycache__', '*.pyc')) + shutil.copytree(source / 'script', scripts / 'v1_0_snapshot/script', ignore=shutil.ignore_patterns('__pycache__', '*.pyc')) + (scripts / 'v1_0_snapshot/doc').mkdir() + for name in BASE_DOC_HASHES: + shutil.copyfile(source / 'doc' / name, scripts / 'v1_0_snapshot/doc' / name) + for ref,digest in baseline_hashes.items(): + if ref.startswith('script/') and sha256(scripts / 'v1_0_snapshot' / ref) != digest: + raise ValueError('historical script changed while snapshotting') + for name in ('schema.json', 'MIGRATION.md'): + shutil.copyfile(here / 'spec' / name, doc / name) + contract = (here / 'spec/CONTRACT.md').read_text().replace('../hand-warehouse-1.0/CONTRACT.md', 'V1_0_SEMANTICS.md') + (doc / 'CONTRACT.md').write_text('> H2O v1.1 试点,未正式发布;历史语义基线随本目录提供。\n\n' + contract) + shutil.copyfile(source / 'doc/CONTRACT.md', doc / 'V1_0_SEMANTICS.md') + mapping = source / 'doc/RAW_TO_SHARED.md' + text = mapping.read_text() if mapping.exists() else '# H2O raw → shared\n\n原转换实现见 script/v1_0_snapshot/script。\n' + (doc / 'RAW_TO_SHARED.md').write_text(text + '\n\n## v1.1 纯存储迁移\n\n' + '原始 RGB、深度及逐像素 valid、帧索引、MANO、左右手、split 和物体身份保持不变。' + '不重新编码视频,不合成源缺失的 UV、分割或接触。\n\n' + '| v1.0 文件 | v1.1 文件与字典条目 |\n|---|---|\n' + '| camera/intrinsic.pt + valid | camera/camera.pt → intrinsic/{data,valid} |\n' + '| camera/extrinsic.pt + valid | camera/camera.pt → extrinsic/{data,valid} |\n' + '| mano/motion.pt + valid | mano/mano.pt → motion/{data,valid} |\n' + '| keypoints/xyz.pt + valid | keypoints/keypoints.pt → xyz/{data,valid} |\n' + '| object//pose.pt + valid | object//object.pt → pose/{data,valid} |\n' + '| object//keypoints/xyz.pt + valid | object//object.pt → keypoints/xyz/{data,valid} |\n\n' + '媒体/JSONL 的独立 valid 保留。没有新增缺失组件。迁移实现见 script/h2o_v1_1/pilot.py;' + '试点未修改源发布或 HF。原始构建记录与旧验收属于 v1.0,不冒充 v1.1 验收。\n') + history = doc / 'history-v1.0' + history.mkdir() + for seq in chosen: + shutil.copyfile(source / 'doc' / (seq + '.build.json'), history / (seq + '.build.json')) + journal = {'phase': 'preparing', 'created_utc': datetime.now(timezone.utc).isoformat(), + 'source': str(source), 'out': str(out), 'source_revision': args.source_revision, + 'raw_tree_oid': raw_oid, 'source_tree_oid': baseline[PREFIX]['oid'], + 'baseline_doc_script_sha256': baseline_hashes, 'workers': args.workers, 'sequences': chosen, 'coverage': coverage, + 'tool_sha256': {str(f.relative_to(here)): sha256(f) for f in here.rglob('*') if f.is_file() and f.suffix != '.pyc'}, + 'views': [], 'scope': 'pilot only; full migration, HF writes and human approval not performed'} + journal_path = out.parent / 'PILOT_JOURNAL.json' + write_json(journal_path, journal) + try: + tasks = [] + for seq in chosen: + inventory = tree(args.source_revision, PREFIX + '/data/' + seq, recursive=True) + entries = {k: v for k, v in inventory.items() if v['type'] == 'file'} + for view in sorted((source / 'data' / seq).iterdir()): + prefix = PREFIX + '/data/' + seq + '/' + view.name + '/' + refs = {k.removeprefix(prefix): v for k, v in entries.items() if k.startswith(prefix)} + tasks.append((str(view), str(out / 'data' / seq / view.name), str(doc / 'schema.json'), refs)) + journal['phase'] = 'migrating_pilot' + write_json(journal_path, journal) + for key in ('OMP_NUM_THREADS', 'MKL_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + with ProcessPoolExecutor(max_workers=args.workers, mp_context=multiprocessing.get_context('spawn')) as pool: + futures = [pool.submit(migrate_view, task) for task in tasks] + for future in as_completed(futures): + result = future.result() + journal['views'].append(result) + write_json(journal_path, journal) + print('PILOT_VIEW', result['view'], 'seconds', round(result['seconds'], 2), flush=True) + journal['views'].sort(key=lambda v: v['view']) + journal['phase'] = 'numeric_pilot_passed_awaiting_html_and_human_review' + journal['wall_seconds'] = time.monotonic() - started + journal['source_files'] = sum(v['source_files'] for v in journal['views']) + journal['target_files'] = sum(v['target_files'] for v in journal['views']) + journal['saved_data_files'] = journal['source_files'] - journal['target_files'] + journal['view_frames'] = sum(v['num_frames'] for v in journal['views']) + journal['source_bytes_checked'] = sum(v['source_bytes'] for v in journal['views']) + journal['verify_worker_seconds'] = sum(v['verify_seconds'] for v in journal['views']) + journal['pack_worker_seconds'] = sum(v['pack_seconds'] for v in journal['views']) + write_json(journal_path, journal) + write_json(doc / 'PILOT_MIGRATION_REPORT.json', journal) + print('PILOT_NUMERIC_DONE', json.dumps({k:journal[k] for k in ('wall_seconds','saved_data_files','view_frames','source_bytes_checked','phase')}), flush=True) + except Exception as exc: + journal.update(phase='failed', error=repr(exc)) + write_json(journal_path, journal) + raise + + +if __name__ == '__main__': + main() diff --git a/H2O/shared-v1.1/script/h2o_v1_1/render.py b/H2O/shared-v1.1/script/h2o_v1_1/render.py new file mode 100644 index 0000000000000000000000000000000000000000..04d1ecc0ab1f56802d94179d8675c5eadd6ce0c2 --- /dev/null +++ b/H2O/shared-v1.1/script/h2o_v1_1/render.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Render stored H2O RGB-D, native camera-space hands/objects, and OBJ assets for review.""" +import argparse +import html +import json +from concurrent.futures import ProcessPoolExecutor +import multiprocessing +import os +import subprocess +import sys +import time +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw +import torch + +if __package__: + from .warehouse import Reader, validate_view +else: + from warehouse import Reader, validate_view + +# Historical helpers decode native media and draw assets; do not invoke the v1.0 validator. +helpers = Path(__file__).resolve().parents[1] / 'v1_0_snapshot/script' +if not helpers.is_dir(): + helpers = Path(__file__).resolve().parents[1] / 'h2o_production/scripts' +sys.path.insert(0, str(helpers)) +from render_hoi4d_validation import mesh_preview, picture +from warehouse_v1_0 import decode_args, unpack_depth + + +def snapshot(video, fmt, shape, dtype, indices): + indices = sorted(indices) + if not indices or indices[0] < 0: + raise ValueError('nonempty nonnegative frame indices required') + expression = '+'.join(f'eq(n\\,{i})' for i in indices) + cmd = decode_args(video, fmt) + ['-vf', 'select=' + expression, + '-frames:v', str(len(indices)), 'pipe:1'] + result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) + frame_bytes = int(np.prod(shape)) * np.dtype(dtype).itemsize + if len(result.stdout) != frame_bytes * len(indices): + raise ValueError(f'missing/truncated selected frames: {video}') + values = np.frombuffer(result.stdout, dtype=dtype).reshape(len(indices), *shape) + return dict(zip(indices, values, strict=True)) + + +def render(view, destination): + meta = json.loads((view / 'metainfo.json').read_text()) + if meta['dataset_id'] != 'H2O': + raise ValueError('H2O view required') + n = meta['num_frames'] + height, width = reversed(meta['camera']['image_size']) + parts = meta['components'] + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + assert len(frames) == n + selected = {0, n // 4, n // 2, 3 * n // 4, n - 1} + reader = Reader(view) + numeric = {} + for name, item in parts.items(): + if item.get('data_ref', '').endswith('.pt') and item.get('available'): + values = reader.field(item).numpy() + valid = reader.field(item, 'valid').numpy() + if values is not None: + numeric[name] = (values, valid) + if valid is not None: + indices = np.flatnonzero(valid.reshape(n, -1).any(axis=1)) + if len(indices): + selected.add(int(indices[0])) + invalid = np.flatnonzero(~valid.reshape(n, -1).all(axis=1)) + if len(invalid): + selected.add(int(invalid[0])) + selected = set(sorted(selected)[:12]) | {n - 1} + rgb = snapshot(view / parts['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected) + depth = snapshot(view / parts['depth']['data_ref'], 'gray16le', (height, 2 * width), ' 0: + u, v = intrinsic[i, 0, 0] * xyz[0] / xyz[2] + intrinsic[i, 0, 2], intrinsic[i, 1, 1] * xyz[1] / xyz[2] + intrinsic[i, 1, 2] + if 0 <= u < width and 0 <= v < height: + draw.ellipse((u-4, v-4, u+4, v+4), fill=color) + legend.append(name + ' ' + color) + panels = ['
' + picture(Image.fromarray(rgb[i])) + '
原生 RGB(仅预览缩放)
', '
' + picture(photo) + '
RGB + 原生 3D 关键点投影(仅预览:' + html.escape(', '.join(legend) or '当前帧无可投影点') + ')
'] + if i in depth: + z = unpack_depth(depth[i]) + luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8) + panels.append('
' + picture(Image.fromarray(luminance)) + '
深度 Z,黑=无效,白≥3 m;不改源深度
') + if i in depth_valid: + good = depth_valid[i] + if not np.isin(good, [0, 1]).all(): + raise ValueError('depth validity must be 0/1') + panels.append('
' + picture(Image.fromarray(good * 255)) + '
原深度逐像素 valid:白=有效,黑=无效,不是深度值
') + details = {'frame': frames[i], 'rgb_valid': bool(reader.field(parts['rgb'], 'valid')[i])} + for name, (values, valid) in numeric.items(): + details[name] = {'value': values[i].tolist(), 'valid': None if valid is None else valid[i].tolist()} + pages.append('

帧 ' + str(i) + ' / ' + str(n) + '

' + ''.join(panels) + '
原帧号、全部数值标注及有效性
' + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '
') + assets = [] + for name, item in parts.items(): + if item.get('available') and item.get('data_ref', '').lower().endswith('.obj'): + assets.append('

' + html.escape(name) + '

' + mesh_preview(view / item['data_ref']) + '
源 OBJ 静态预览,不代表物体姿态投影
') + report = validate_view(view, view.parents[2] / 'doc/schema.json') + report['selected_frames'] = sorted(selected) + report['preview_media'] = ['rgb', 'depth', 'depth_valid'] + report['decode_scope'] = 'only selected frames emitted; sequential decoding may traverse earlier frames, no full-video pixel comparison' + destination.mkdir(parents=True, exist_ok=True) + title = view.parent.name + '_' + view.name + style = 'body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;background:#f5f7fa;color:#18232f}section,details{background:white;padding:1rem;margin:1rem 0;border-radius:8px}.panels{display:flex;flex-wrap:wrap}img{max-width:100%}pre{white-space:pre-wrap;overflow:auto;font-size:12px}' + page = '' + html.escape(title) + '

' + html.escape(title) + '

直接读取 v1.1 bundle;预览只作人工核查。手/物体点来自源 3D 标注,仅为显示投影到 RGB;未生成新 UV、分割或接触标注。

' + ''.join(pages) + '

源网格

' + ''.join(assets) + '
全部组件元数据
' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '
持久化 QC
' + html.escape(json.dumps(report, ensure_ascii=False, indent=2)) + '
' + (destination / (title + '.html')).write_text(page) + (destination / (title + '.report.json')).write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') + return destination / (title + '.html') + + + +def render_task(task): + torch.set_num_threads(1) + if torch.get_num_interop_threads() != 1: + torch.set_num_interop_threads(1) + view, dest = map(Path, task) + render(view, dest) + print('HTML_VIEW', view.parent.name, view.name, flush=True) + return json.loads((dest / (view.parent.name + '_' + view.name + '.report.json')).read_text()) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('root', type=Path) + parser.add_argument('--workers', type=int, default=4) + parser.add_argument('--sequences-file', type=Path) + args = parser.parse_args() + if not 1 <= args.workers <= 8: + parser.error('1–8 workers required') + root = args.root.resolve() + dest = root / 'doc/validation' + dest.mkdir(exist_ok=True) + if args.sequences_file: + sequences = json.loads(args.sequences_file.read_text())['sequences'] + if len(sequences) != len(set(sequences)) or any(not isinstance(n,str) or n in ('', '.', '..') or '/' in n or '\\' in n for n in sequences): + raise ValueError('unsafe or duplicate selected sequence') + views = sorted(p.parent for seq in sequences for p in (root / 'data' / seq).glob('*/metainfo.json')) + if len(views) != len(sequences) * 5: + raise ValueError('selected sequences must include all five cameras') + else: + views = sorted(p.parent for p in (root / 'data').glob('*/*/metainfo.json')) + if not views: + raise ValueError('no views to render') + for key in ('OMP_NUM_THREADS', 'MKL_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + os.environ['HAND_WAREHOUSE_FFMPEG_THREADS'] = '10' + start = time.monotonic() + with ProcessPoolExecutor(max_workers=args.workers, mp_context=multiprocessing.get_context('spawn')) as pool: + reports = list(pool.map(render_task, [(str(v), str(dest)) for v in views])) + label = '全量后抽样' if args.sequences_file else '试点' + summary = {'review_kind': label, 'views': len(views), 'sequences': len({v.parent for v in views}), + 'wall_seconds': time.monotonic() - start, 'reports': reports, + 'scope': 'all selected sequence cameras; sampled frames and all numeric fields read from new bundles; manual approval pending'} + (dest / 'V1_1_VALIDATION.json').write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n') + links = sorted(p.name for p in dest.glob('*.html') if p.name != 'index.html') + (dest / 'index.html').write_text('H2O v1.1 review

H2O v1.1 ' + label + '全部相机验收

数值按字节一致;媒体不重新编码。RGB、深度/深度 valid、相机、MANO、手/物体点、位姿、网格和来源均可查看;源没有 UV、分割或接触,不补造。

合同 · 字段映射 · 迁移报告 · 可视化报告

') + print('PILOT_HTML_DONE', len(views), 'views', round(summary['wall_seconds'], 2), 'seconds', dest / 'index.html', flush=True) + + +if __name__ == '__main__': + main() diff --git a/H2O/shared-v1.1/script/h2o_v1_1/spec/CONTRACT.md b/H2O/shared-v1.1/script/h2o_v1_1/spec/CONTRACT.md new file mode 100644 index 0000000000000000000000000000000000000000..c237e8d95df74f237ec4be1b0a3b0ac06a0ca935 --- /dev/null +++ b/H2O/shared-v1.1/script/h2o_v1_1/spec/CONTRACT.md @@ -0,0 +1,161 @@ +# 手物数据仓库统一约定 v1.1:张量合并存储 + +格式版本:`hand-warehouse/1.1`。张量存储约定:`pt/tensor_bundle/v1`。 + +状态:合同草案,2026-10-09。本版规定新的文件布局与读取方式,配套 [schema.json](schema.json) 注册表已更新;尚未迁移现有数据,也未适配生产转换器、读取器或可执行校验器。不能仅修改现有 metainfo 的版本号就宣称符合本版。 + +本版以 [v1.0 合同](../hand-warehouse-1.0/CONTRACT.md) 为语义基础:任务范围、两层序列/相机组织、数据类型、单位、坐标系、时间对齐、左右手顺序、官方划分、view_type、来源、可用监督规则、媒体无损编码和验收要求均保留。下文仅替代数值张量组件的独立 Tensor 文件、对应 `*_valid.pt` 及文件引用规定;这些旧文件名仅用于识别对应逻辑字段。媒体和 JSONL 组件的有效性文件及引用保持 v1.0,不纳入合并。未明确改变的语义继续执行 v1.0。 + +本版按用户约定作为 v1.0 的小版本存储修订,后续所有数据集逐步迁移到 v1.1。数值字段与 valid 语义不变,但 `.pt` 物理结构和引用方式改变,旧读取器不能未经适配直接读取新字典。各数据集在原 `shared-v1.0` 目录内逐步升级,完整验收后将目录更名为 `shared-v1.1`,不长期保留两套发布树。最终 `metainfo.schema_version=hand-warehouse/1.1`、`release_id=shared-v1.1`;尚未迁移的数据集仍使用原目录和版本。升级与发布流程见 [MIGRATION.md](MIGRATION.md)。实施前须按配套 v1.1 注册表完成读写/校验工具;不得将 v1.0 的 schema.json 改个版本号作为已完成适配的证明。正式发布时须提供完整合同与匹配注册表,不依赖本地草案目录中的相对链接。 + +## 1. 合并边界 + +1. 数值张量与对应有效性必须在同一个 `.pt` 文件、同一个字段字典内保存:`{"data": Tensor, "valid": BoolTensor}`。这些数值张量组件不再生成独立的 `*_valid.pt`;媒体和 JSONL 的有效性文件不受此规则影响。 +2. 按组件合并经常一起读取的小张量:相机内参、外参、畸变放在一个 `camera.pt`;MANO 参数与整手可见性放在一个 `mano.pt`;手关键点的二维、三维与可见性放在一个 `keypoints.pt`。 +3. 每个物体的数值字段及全部部件数值字段合并为一个 `object.pt`。不同物体、不同相机、不同序列不合成一个全局大文件,以保留按需下载和读取能力。 +4. RGB、深度、栅格 mask 继续使用原无损媒体格式,不把解码后的大数组或媒体字节塞进 `.pt`。它们的有效性文件保持原文件名、Tensor/媒体格式、形状和引用方式,不包装为字典。 +5. `metainfo.json`、`camera/frames.jsonl`、实例映射、物体身份/运动学定义与网格资产保留原格式。此次不把 JSON、JSONL、OBJ、纹理全部打进一个字典。 + +合并只改变存储方式,不改变采样、帧数、张量内容或有效性判定。不为减少字段数而将多个组件的 valid 合成一个公共 valid。 + +## 2. 目录 + +```text +/shared-v1.1/ + doc/ # 完整合同、匹配 schema、字段映射、验收报告 + script/ # 转换、读取和校验代码 + data/// + metainfo.json + observation/ + rgb.mkv + rgb_valid.pt # 原独立 bool Tensor,保持不变 + depth.mkv + depth_valid.mkv # 逐像素有效性,保留压缩媒体格式 + camera/ + frames.jsonl + camera.pt # intrinsic、extrinsic、distortion + annotation/ + mano/mano.pt # motion、visibility + keypoints/keypoints.pt # uv、xyz、visibility、whole_hand_visibility + object// + metainfo.json + articulation.json # 仅关节/部件结构实际存在时 + object.pt # 位姿、可见性、几何点、关节、部件数值 + assets/ # 原网格、材质、纹理及依赖 + segment/ + mask.mkv # 或 polygons.jsonl,按所选表示 + instances.jsonl # 仅需要实例/区域编码映射时 + mask_valid.pt # 原帧级 bool Tensor,保持不变 + contact/ + relations.jsonl + relations_valid.pt # 原帧级 bool Tensor,保持不变 + __/ + contact.pt # vertex_region、vertex_distance +``` + +只创建实际提供的组件和字段。以上不是每个数据集必须填满的模板;缺失内参、MANO、深度等不能通过占位文件伪装为已提供。序列/相机的两层结构不变,物体与模态目录属于相机内部组件。 + +## 3. 字典结构与有效性 + +本次合并的数值组件 `.pt` 根对象为字符串键的 Python `dict`,内部仅允许嵌套字符串键字典和 CPU `torch.Tensor`,不保存自定义类、模型、NumPy 对象或任意可执行对象。元信息、schema、单位和来源放在 metainfo,不在每个张量条目中重复保存。读取使用 `torch.load(path, map_location="cpu", weights_only=True)`。第 4 节保留的独立有效性 `.pt` 根对象仍为 CPU bool Tensor,不适用字典结构要求。 + +例如,`camera/camera.pt` 的逻辑结构为: + +```python +{ + "intrinsic": {"data": K, "valid": K_valid}, + "extrinsic": {"data": T_camera_from_world, "valid": extrinsic_valid}, + "distortion": {"data": distortion, "valid": distortion_valid}, +} +``` + +以上变量均为 Tensor。未提供的字段整个省略;例如无世界系外参时不保存 `extrinsic`,不填单位矩阵。没有单独畸变向量的模型不创建 `distortion`:Fisheye624 仍使用既定 `[T,15]` 内参参数布局。 + +数值字段统一为 `data` 与 `valid` 两个叶子。源属性原先显式声明全已知 `valid=true` 时,迁移可按该属性的有效性形状展开为全 true 的 bool Tensor;这是已有有效性声明的等价表示,不是根据数值或姿态推测有效性。有效性必须为 bool Tensor,不能用 Python `True` 代替字段内的 Tensor。静态数值字段同样配套 valid,形状采用其语义定义的标量或逐元素有效性;静态网格等外部资产仍可在 metainfo 中声明标量 valid。 + +valid 的形状不要求与 data 完全相同,但必须与该字段定义一致。例如 MANO 为 `[T,2,61]` / `[T,2]`,内参为 `[T,3,3]` / `[T]`,关键点为 `[T,2,K,3]` / `[T,2,K]`。按 schema 将 valid 扩展到相应数值维度,不允许依靠碰巧可广播推断语义。 + +浮点默认 float32,无效浮点位置仍为 NaN;bool 和整数沿用该组件的占位/保留值规则,不因没有 NaN 而视为有效。valid 表达可用监督,不只是“值有限”或“记录存在”;适用官方 QA 与已经确认的排除规则继续保留。不能用 `isfinite(data)` 重建 valid,不能因为迁移而把 false 改成 true。 + +不同字段的 valid 独立保存和解释。visibility 的 valid 不复用姿态 valid;内参 valid 不代替外参 valid。既有相机模型要求内参与单独畸变向量共用有效性时,在两个字段内保存相同 bool 值并校验一致,而不改变该模型的联合标定规则。 + +## 4. 固定分组与字段名 + +下表中的键路径用 `/` 展示字典层级;它不是文件系统路径。数值字段均在列出的键下继续存储 `data`、`valid`。 + +| 文件 | 数值字段键 | 内容 | +|---|---|---| +| `camera/camera.pt` | `intrinsic`、`extrinsic`、`distortion` | 逐帧标定;形状、参数顺序与相机模型定义不变 | +| `annotation/mano/mano.pt` | `motion`、`visibility` | MANO `[T,2,61]` 与源整手可见性;各有独立有效性 | +| `annotation/keypoints/keypoints.pt` | `uv`、`xyz`、`visibility`、`whole_hand_visibility` | 手关键点及源可见性;整手与逐点可见性不混用 | +| `annotation/object//object.pt` | `pose`、`visibility`、`dimensions`、`joint_state` | 该物体的数值标注 | +| 同上 | `keypoints/xyz`、`keypoints/template_xyz` | 相机系逐帧点或物体系静态模板点 | +| 同上 | `parts//pose`、`parts//dimensions`、`parts//keypoints/xyz`、`parts//keypoints/template_xyz` | 部件数值字段,部件身份仍由 articulation 登记 | +| 同上 | `meshes//vertex_part_ids` | `[V] int64` 顶点部件标签,valid 为 `[V]`,未知 -1 对应 false;每个 mesh 单独绑定拓扑 | +| `annotation/contact/__/contact.pt` | `vertex_region`、`vertex_distance` | 已登记拓扑上的接触区域/距离与同形有效性 | + +顶点部件标签使用注册类型 `object/vertex_part_ids/v1`。物体的 mesh_id、part_id 必须在 metainfo/运动学定义中可解析;不同拓扑不能误用同一顶点数组。未提供的可见性、关节值或模板点不生成空字段。 + +**媒体和 JSONL 的有效性保持原样,不参与字典合并:** + +| 数据本体 | 有效性文件 | 存储形式 | +|---|---|---| +| `observation/rgb.mkv` | `observation/rgb_valid.pt` | 独立 CPU bool Tensor `[T]` | +| `annotation/segment/mask.mkv` 或 `polygons.jsonl` | 原 `valid_ref` 指定的文件,通常为 `annotation/segment/mask_valid.pt` | 独立 CPU bool Tensor `[T]`;沿用原路径 | +| `annotation/contact/relations.jsonl` | `annotation/contact/relations_valid.pt` | 独立 CPU bool Tensor `[T]` | +| `observation/depth.mkv` | `observation/depth_valid.mkv` | 原逐像素 bool 无损视频 `[T,H,W]` | + +不新建仅包装上述 valid 的 observation.pt、segment.pt 或关系级 contact.pt。现有媒体/JSONL 的 `valid_ref`、`valid_axes` 及适用的 `valid_storage` 保持原定义;深度编码、NaN 位串还原与像素有效性规则不变。实体对的接触区域/距离是数值张量,仍按上表合并到各实体对的 contact.pt。 + +## 5. metainfo 的文件与字典键引用 + +文件定位与字典内部定位分开登记,不在文件名中拼接自定义分隔符: + +| 字段 | 定义 | +|---|---| +| `data_ref` | 相对当前相机视图根目录的 POSIX 文件路径 | +| `data_key` | 非空字符串列表,按顺序访问 `.pt` 嵌套字典,最终必须得到 data Tensor | +| `valid_ref` | 有效性所在文件;合并的数值字段必须与 data_ref 相同,媒体/JSONL 保留独立有效性文件 | +| `valid_key` | 非空字符串列表,最终必须得到 bool Tensor | +| `storage.profile` / `valid_storage.profile` | 合并字典采用 `pt/tensor_bundle/v1`;媒体及其独立有效性保持原配置,不将独立 bool Tensor 声明为 bundle | + +数值字段必须显式登记 data_key 与 valid_key。例如内参登记: + +```json +{ + "available": true, + "schema_id": "camera/pinhole/v1", + "data_ref": "camera/camera.pt", + "data_key": ["intrinsic", "data"], + "axes": ["T", "row", "column"], + "valid_ref": "camera/camera.pt", + "valid_key": ["intrinsic", "valid"], + "valid_axes": ["T"], + "storage": {"profile": "pt/tensor_bundle/v1"}, + "valid_storage": {"profile": "pt/tensor_bundle/v1"} +} +``` + +这是引用结构片段,实际组件仍须补齐 provenance、source_locator 等必填内容。MANO 的 schema_id 仍可为 `mano/axis_angle61/v1`:它描述解码后的数值语义,不因为物理文件合并而改动。顶层 schema_version 与 storage.profile 标识新的存储方式。 + +媒体和 JSONL 的 data_ref 不设置 data_key;RGB 的 valid_ref 仍为 `observation/rgb_valid.pt`,不设置 valid_key。分割、关系和深度的有效性同样保持原引用方式,不新增任何字典键字段。只有引用合并字典时才使用 data_key/valid_key。 + +同样规则适用于 attributes 中的可见性等数值字段。相机模型已有的 `distortion_ref` 改为指向 `camera/camera.pt`,新增 `distortion_key=["distortion", "data"]`;对应有效性由同组件的 `distortion_valid_ref` 与 `distortion_valid_key=["distortion", "valid"]` 登记。带 `_key` 的引用必须指向匹配的 bundle 文件,不能指向目录或媒体。 + +读取器按文件路径缓存已加载字典,再按 key 取字段。同一 camera.pt 的三个字段不应触发三次反序列化。按组件下载时取所需 bundle 的整个文件;本约定不承诺 `.pt` 内单个键的远端局部下载。组件合并会增加最小下载粒度,这是减少文件数的明确取舍。 + +## 6. 迁移与验收 + +各数据集分别迁移:先适配工具并做代表性完整序列验证,再迁移全量并核对结果,最后按授权更新远端发布;一个数据集完成不代表其他数据集已完成。迁移状态和输入/输出固定版本逐数据集登记。 + +本地先在既有 `shared-v1.0` 内完成受控升级,校验完成后更名为 `shared-v1.1`。暂存、回滚、锁、旧文件清理、版本更新及 HF 路径切换遵循 [MIGRATION.md](MIGRATION.md);不复制完整媒体、不改 raw、不重新编码。多文件原地更新期间须保持维护状态,不能让读取任务使用半迁移视图。 + +每次迁移必须检查: + +1. 所有组件、属性及其字典键可解析;无越界文件引用、缺失键或未登记字段;已合并的数值组件不得遗留旧独立 `*_valid.pt`。媒体/JSONL 的原独立有效性文件必须保留,不得误删或重打包。 +2. 每个迁移前后的数值字段 dtype、shape、逐元素值、NaN 位置以及 bool valid 完全一致。数值张量还应按统一连续字节视图比较,确认没有更改 NaN 位串等内容;不能用近似容差代替单纯重打包的一致性。 +3. T、帧映射、相机方向、手槽、split、来源和 valid_policy 不变。固定标定仍按既有 `[T,...]` 规则保存;本次不额外改成单份静态标定加广播。 +4. 媒体与其他未修改文件按原可信摘要核对。新 `.pt` 的文件 SHA256 通常改变,必须重新生成发布清单;新文件指纹不等于转换语义正确性的证明。 +5. 用新读取器运行代表性完整序列及所有相机,检查 RGB、相机与实际存在的标注是否正确关联;报告明确“重打包数值一致”与“人工视觉验收”的不同范围。 + +只有完成匹配注册表、读写工具及上述验收后才能生产/发布 v1.1。上传仍须单独得到授权;本文档更新本身不启动数据迁移或上传;被替代旧文件的清理属于后续迁移发布步骤,必须遵守MIGRATION.md 中先验收、安全切换和固定提交核验要求。 diff --git a/H2O/shared-v1.1/script/h2o_v1_1/spec/MIGRATION.md b/H2O/shared-v1.1/script/h2o_v1_1/spec/MIGRATION.md new file mode 100644 index 0000000000000000000000000000000000000000..b867163fccbc578f22eb6be8181f866bfecb6813 --- /dev/null +++ b/H2O/shared-v1.1/script/h2o_v1_1/spec/MIGRATION.md @@ -0,0 +1,68 @@ +# 数据集 v1.0 → v1.1 升级规范 + +日期:2026-10-09。目标格式:`hand-warehouse/1.1`。字段与字典布局见 [CONTRACT.md](CONTRACT.md)。 + +## 1. 升级单位与最终布局 + +以一个完整数据集为单位逐步升级。每个数据集在既有目录内完成数值文件重组、工具适配与验证,完成后将目录由 `shared-v1.0` 更名为 `shared-v1.1`。最终使用: + +```text +/ + raw/ # 保持原样 + shared-v1.1/ + data/ + doc/ + script/ +``` + +这是对“发布目录永久保持 shared-v1.0”安排的修订:不长期保留两套发布树,也不复制一整套媒体再制作新版本。尚未升级的数据集继续使用自己的 `shared-v1.0`;不同数据集处于不同版本是正常的。 + +完成后视图元数据统一为 `schema_version=hand-warehouse/1.1`、`release_id=shared-v1.1`。目录名与元数据版本均须正确,不能只更名而不改变内容。发布记录保留旧版本的固定提交以便追溯。 + +## 2. 变更范围 + +- 合并相机、MANO、关键点、物体、实体对接触等数值张量及各自 valid;具体分组遵循合同。 +- 保持媒体及其独立有效性文件不变,包括 RGB、深度、mask 和相应 valid。JSONL、资产按合同保留;不重新编码媒体,不改 raw。 +- 不改变张量 dtype、shape、数值、NaN 位串、valid、帧映射、T、单位、坐标系、左右手、划分及监督策略。 +- 更新匹配的 schema、读取/转换/校验脚本、metainfo 引用、发布清单和正式文档。不得仅替换版本字符串冒充工具适配。 +- 删除已经完整合并且验收通过的旧数值文件与对应独立 valid;不得按 `*_valid.pt` 通配删除,媒体/JSONL 有效性不在清理范围。 + +## 3. 启动与登记 + +启动前核对项目并行上限、实际进程、锁和空间。取得数据集迁移锁并暂停该目录的转换、发布和读取任务;多文件原地更新不是整体原子操作,不得让消费者读取半迁移视图。 + +在发布树外的 `tmp/` 为每个数据集登记:源 schema/release、源 HF 固定提交、源文件清单及摘要、目标版本、工具摘要、变更/删除的精确路径清单、checkpoint、阶段、错误和验收结果。原始数据长期保留。 + +准备可恢复的基线:保存即将被替换的小型元数据和脚本,以及旧数值文件的临时备份或已核验可恢复的远端固定版本。不复制未变化的大型媒体。空间预算包含临时新文件和回滚所需文件;空间不足时停止新增工作,不删 raw 腾空间。 + +## 4. 原地升级 + +1. 先选代表性完整序列及全部相机,在 `tmp/` 验证新写入器、读取器和引用;覆盖实际存在的组件与有效性组合。遵循项目人工验收要求后再全量。 +2. 全量按完整视图处理。读取旧数值及 valid,写临时字典,重新读取并逐字段精确比较;不得用近似误差判断纯重打包的一致性。 +3. 验证通过后在同一文件系统原子替换单个文件,再更新该视图 metainfo。只有新字段与引用完整可读、且回滚依据可用,才能移除该视图被替代的旧文件。 +4. 每个视图保存完成 checkpoint;续跑必须核对输入和工具版本、产物摘要及当前引用,不能只依据文件存在而跳过。整个数据集完成前保持维护状态。 +5. 完成全部视图后校验完整路径集合、无重复/缺失、所有键引用、全部数值一致性和未变文件摘要,并更新正式文档及脚本。生成直接读取新格式的随机完整序列报告,按项目流程人工确认。 + +失败时停止该数据集迁移,保留 checkpoint 和回滚材料,不伪装完成,不自动删除整棵目录或从 raw 重做转换。 + +## 5. 本地最终更名 + +全量验收通过后,在维护状态下统一设置最终 `release_id=shared-v1.1`,更新当前使用的配置、入口、清单和链接,然后将原目录重命名为 `shared-v1.1`。 + +重命名前核对源/目标绝对路径均位于该数据集根目录;目标目录必须不存在,不合并、不覆盖已有同名目录。同一文件系统内执行目录重命名,避免复制全部媒体。更名后再次解析相对引用并检查脚本默认路径,最后解除本地维护状态。 + +历史报告中说明当时版本的文字与固定摘要作为历史证据保留,不批量篡改;当前入口须明确报告所属版本,并链接本次迁移验收结果。 + +## 6. HF 发布与路径更换 + +本地目录重命名不等于 HF 路径已经更换。远端须在得到发布授权后,基于旧的固定提交执行受控更新;发布前再次核对源 HEAD 和相关文件内容,冲突时停止调查。 + +优先复用仓库已有内容,以平台实际支持且经过验证的服务端复制/提交操作,将未变化媒体映射到 `shared-v1.1`;仅新的字典、元数据、文档和脚本需要提供新内容。不承诺路径更换必然零网络传输或零耗时;先验证实际行为,不盲目重新上传全套媒体。 + +理想情况下,在一个提交中添加目标路径并删除旧路径,使默认分支完整切换。若文件数或 API 限制不允许,使用经过验证的临时分支准备与核验,完成后受控切换;若只能分批更新默认分支,必须明确维护状态,旧版本保留到目标完整核验通过,不提前删除唯一完整的旧树。短暂的核验用路径并存不代表长期发布两套版本。 + +最终必须在同一固定提交上验证:目标 `shared-v1.1` 的文件集合、大小与内容摘要全部匹配清单,所有引用有效;旧 `shared-v1.0` 路径已移除;raw 未变化。服务端更换路径仍须执行这些核验,不能用“文件名已改”替代。 + +完成后更新数据集登记与下载示例,记录最终提交,清理本次临时文件并通知一次,再安排下一个数据集。旧提交历史保留历史版本;本流程减少当前发布树的重复文件,不承诺清除 HF 历史存储。 + +本文仅规定后续实施流程,编写本文不等于已经启动迁移、修改数据或获得新的发布授权。 diff --git a/H2O/shared-v1.1/script/h2o_v1_1/spec/schema.json b/H2O/shared-v1.1/script/h2o_v1_1/spec/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..087342ba7440c3b656e342d1b954bd90a5878af1 --- /dev/null +++ b/H2O/shared-v1.1/script/h2o_v1_1/spec/schema.json @@ -0,0 +1,1590 @@ +{ + "schema_version": "hand-warehouse/1.1", + "validity_revision": "usable-annotation-2026-09-20", + "annotation_validity": { + "meaning": "annotation usable for supervision, not merely record presence", + "formula": "source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass AND NOT explicitly_reviewed_local_exclusion", + "without_official_qa": "omit QA term; declare source rules; do not fabricate QA", + "policy_field": "components..valid_policy", + "visibility_is_independent": true, + "invalid_float_value": "NaN", + "hot3d": "broadcast per-camera frame manual QA conservatively to hand/object labels and pose-derived visibility; retain RGB and source calibration; keep native QA in raw and review report", + "hot3d_visibility": "native visibility_ratio[%] already ranges from 0 to 1; do not divide by 100" + }, + "hand_slots": [ + "left", + "right" + ], + "view_metadata": { + "required_fields": [ + "schema_version", + "dataset_id", + "release_id", + "sequence_id", + "camera_id", + "sample_type", + "num_frames", + "hand_slots", + "sampling", + "camera", + "components", + "split", + "view_type" + ], + "view_type_values": [ + "ego", + "exo", + "unknown" + ], + "view_type_policy": "required per camera view; use ego or exo whenever the source data or capture setup establishes the viewpoint; use unknown only when no trustworthy source determines it; never omit or guess", + "schema_version": "hand-warehouse/1.1", + "release_id": "shared-v1.1" + }, + "keypoints": { + "mano21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map": null, + "note": "adapter maps official MANO joint and fingertip convention" + }, + "rhd21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map_per_hand": [ + 0, + 4, + 3, + 2, + 1, + 8, + 7, + 6, + 5, + 12, + 11, + 10, + 9, + 16, + 15, + 14, + 13, + 20, + 19, + 18, + 17 + ] + } + }, + "camera": { + "opencv_fisheye4": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "k3", + "k4" + ], + "projection": "theta=atan(r); theta_d=theta*(1+k1*theta^2+k2*theta^4+k3*theta^6+k4*theta^8); source ReInterHand" + }, + "pinhole": { + "K": [ + 3, + 3 + ] + }, + "fisheye624": { + "parameters": [ + "f", + "cx", + "cy", + "k0", + "k1", + "k2", + "k3", + "k4", + "k5", + "p0", + "p1", + "s0", + "s1", + "s2", + "s3" + ] + }, + "rational8": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "p1", + "p2", + "k3", + "k4", + "k5", + "k6" + ] + } + }, + "segmentation": { + "segment/uint16_labels/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "polygons.jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "note": "Registry for hand-warehouse/1.1. Read CONTRACT.md and MIGRATION.md. This is a declarative registry, not a JSON Schema document or executable validator. Runtime readers/converters/validators still require adaptation.", + "components": { + "mano/axis_angle61/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 61 + ], + "valid_shape": [ + "T", + 2 + ], + "unit": "m", + "angle_unit": "rad", + "coordinate_frame": "camera", + "layout": { + "pose_axis_angle": [ + 0, + 48 + ], + "shape": [ + 48, + 58 + ], + "translation": [ + 58, + 61 + ] + }, + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool", + "required_metadata": [ + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ] + }, + "keypoints/uv/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 2 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "pixel", + "required_metadata": [ + "keypoint_schema", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "keypoints/xyz/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 3 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "m", + "required_metadata": [ + "keypoint_schema", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "depth/z_float32/v1": { + "storage": "mkv", + "dtype": "float32", + "shape": [ + "T", + "H", + "W" + ], + "valid_shape": [ + "T", + "H", + "W" + ], + "unit": "m", + "depth_type": "z", + "pixel_grid": "current_rgb", + "coordinate_frame": "current_rgb_camera", + "valid_storage": "mkv", + "allowed_storage_profiles": [ + "mkv/depth_float32_bits/v1" + ], + "allowed_valid_storage_profiles": [ + "mkv/bool_ffv1/v1" + ], + "required_metadata": [ + "storage", + "valid_storage", + "depth_origin" + ], + "depth_origin_values": [ + "measured", + "rendered", + "unknown" + ] + }, + "transform/se3/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "object/rigid/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "camera/pinhole/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool", + "required_metadata": [ + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ] + }, + "camera/rational8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool", + "required_metadata": [ + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage", + "distortion_ref", + "distortion_key", + "distortion_valid_ref", + "distortion_valid_key" + ] + }, + "camera/opencv_fisheye4/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool", + "required_metadata": [ + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage", + "distortion_ref", + "distortion_key", + "distortion_valid_ref", + "distortion_valid_key" + ] + }, + "camera/fisheye624/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 15 + ], + "valid_shape": [ + "T" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool", + "required_metadata": [ + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ] + }, + "camera/distortion8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 8 + ], + "valid_shape": [ + "T" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool", + "required_metadata": [ + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ] + }, + "camera/fisheye4_distortion/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4 + ], + "valid_shape": [ + "T" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool", + "required_metadata": [ + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ] + }, + "object/joint_state/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "J" + ], + "valid_shape": [ + "T", + "J" + ], + "required_metadata": [ + "joint_order", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "unit_rule": "revolute radians; prismatic metres; mixed types declared per joint", + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "object_keypoints/camera/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "K", + 3 + ], + "valid_shape": [ + "T", + "K" + ], + "unit": "m", + "coordinate_frame": "camera", + "required_metadata": [ + "keypoint_schema", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "object/dimensions/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "dimensions_semantics", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "axis_order": [ + "length", + "width", + "height" + ], + "scale_rule": "do not apply to mesh without source-supported size/scale relation", + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "object_keypoints/template/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "K", + 3 + ], + "valid_shape": [ + "K" + ], + "unit": "m", + "coordinate_frame": "object", + "static": true, + "required_metadata": [ + "keypoint_schema", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "mesh/obj/v1": { + "storage": "obj", + "unit": "m", + "static": true, + "valid_shape": [], + "dependencies": "MTL and textures retained under owning object" + }, + "rgb/uint8/v1": { + "storage": "mkv", + "dtype": "uint8", + "shape": [ + "T", + "H", + "W", + 3 + ], + "valid_shape": [ + "T" + ], + "color_order": "RGB", + "allowed_storage_profiles": [ + "mkv/mjpeg_copy/v1", + "mkv/source_copy/v1", + "mkv/h264_rgb_lossless/v1", + "mkv/ffv1_rgb/v1" + ], + "required_metadata": [ + "storage" + ] + }, + "contact/relations/v1": { + "storage": "jsonl", + "valid_shape": [ + "T" + ], + "frame_keys": [ + "frame_index", + "relations" + ], + "absence_semantics": "no record is not a negative contact annotation" + }, + "contact/vertex_region/v1": { + "storage": "pt", + "dtype": "bool", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "pilot_status": "defined_not_empirically_validated", + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "contact/vertex_distance/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "unit": "m", + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id", + "distance_definition", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "pilot_status": "defined_not_empirically_validated", + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt", + "tensor_container": "dict", + "valid_dtype": "bool" + }, + "object/articulated/v1": { + "storage": "json", + "required_keys": [ + "parts", + "joints" + ], + "part_keys": [ + "part_id", + "parent_id", + "has_model", + "mesh_ref" + ], + "hierarchy_semantics": "declare mechanical articulation or semantic containment; containment alone does not imply joints", + "acyclic": true + }, + "segment/uint16_labels/v1": { + "storage": "mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "object/vertex_part_ids/v1": { + "storage": "pt", + "tensor_container": "dict", + "dtype": "int64", + "shape": [ + "V" + ], + "valid_shape": [ + "V" + ], + "valid_dtype": "bool", + "static": true, + "unknown_value": -1, + "valid_rule": "data != -1; every valid integer resolves in part_id_mapping", + "required_metadata": [ + "mesh_ref", + "topology_id", + "part_id_mapping", + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "allowed_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "allowed_valid_storage_profiles": [ + "pt/tensor_bundle/v1" + ], + "valid_storage": "pt" + } + }, + "storage_revision": "lossless-video-2026-09-18", + "sampling": { + "image": { + "single": { + "T": 1 + }, + "independent": { + "T": ">=2", + "required_frame_fields": [ + "sample_id", + "source_locator" + ], + "temporal_relationship": false + }, + "source_fps": null + }, + "video": { + "sampling_types": [ + "dense", + "sparse" + ] + } + }, + "storage_profiles": { + "mkv/mjpeg_copy/v1": { + "container": "matroska", + "codec": "mjpeg", + "method": "stream_copy_from_source_jpeg", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "source_jpeg_packet_sha256_exact", + "all_packet_count_order_and_dimensions_exact", + "deterministic_decoded_rgb_sample_exact", + "pilot_and_final_selected_whole_sequences_decoded_rgb_exact" + ], + "validation_policy": { + "id": "jpeg-packets-all-rgb-sample16/v1", + "sample_count_per_view": 16, + "short_views": "all_frames_if_T_less_than_16", + "fixed_indices": "0,T-1,T//4,T//2,3*T//4, deduplicated", + "remaining_indices": "sample without replacement to min(T,16) using Python random.Random(seed)", + "seed": "first 8 bytes of SHA256(sequence_id/camera_id/20260920), big-endian integer", + "report": "policy, exact selected frame indices, seed, separate packet and pixel coverage", + "legacy_all_frame_pixel_proofs": "still accepted; preserve historical evidence" + } + }, + "mkv/source_copy/v1": { + "container": "matroska", + "codec": "source_codec_declared_in_metadata", + "method": "stream_copy_only", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "no_reencoding", + "all_decoded_rgb_frames_exact", + "presentation_frame_order_exact" + ] + }, + "mkv/h264_rgb_lossless/v1": { + "container": "matroska", + "codec": "h264", + "encoder": "libx264rgb", + "crf": 0, + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "gop": "declared_in_encoder_parameters", + "validation": [ + "all_decoded_rgb_frames_exact" + ], + "forbidden": [ + "lossy_rate_control", + "rgb_to_yuv420_subsampling" + ] + }, + "mkv/ffv1_rgb/v1": { + "container": "matroska", + "codec": "ffv1", + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "validation": [ + "all_decoded_rgb_frames_exact" + ] + }, + "mkv/depth_float32_bits/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray16le", + "logical_dtype": "float32", + "logical_shape": [ + "T", + "H", + "W" + ], + "encoded_shape": [ + "T", + "H", + "2*W" + ], + "packing": "IEEE754 little-endian float32 bits; low uint16 in first W columns, high uint16 in last W columns", + "decode": "reinterpret_float32(uint32(low) | (uint32(high) << 16))", + "validation": [ + "all_float32_bits_exact_including_nan" + ] + }, + "mkv/bool_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray", + "logical_dtype": "bool", + "stored_values": [ + 0, + 1 + ], + "validation": [ + "all_bool_values_exact" + ] + }, + "mkv/uint16_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_formats": [ + "gray", + "gray16le" + ], + "logical_dtype": "uint16", + "gray_condition": "all values <=255; decode by exact uint8-to-uint16 promotion", + "validation": [ + "all_integer_values_exact" + ] + }, + "pt/tensor_bundle/v1": { + "container": "pytorch_pt", + "root_type": "dict", + "dictionary_key_type": "nonempty_string", + "allowed_value_types": [ + "dict", + "CPU torch.Tensor" + ], + "tensor_entry": { + "required_keys": [ + "data", + "valid" + ], + "additional_keys": false, + "data_type": "CPU torch.Tensor", + "valid_type": "CPU torch.Tensor", + "valid_dtype": "bool" + }, + "metadata_location": "metainfo.json; do not duplicate strings, paths or custom objects inside bundles", + "missing_entry": "omit entire entry; never fabricate absent modalities", + "load": { + "map_location": "cpu", + "weights_only": true + }, + "valid_shape_rule": "Use the specific component or attribute valid_shape; do not infer broadcasting or share validity across independent fields.", + "validation": [ + "registered layout and key resolution", + "CPU tensors only", + "schema dtype and shape", + "independent bool validity", + "frame alignment unchanged", + "invalid floating positions NaN", + "pure migration exact data bytes and validity equality" + ], + "not_applicable_to": [ + "media payloads", + "media standalone validity tensors", + "JSONL standalone validity tensors" + ] + } + }, + "video_metadata": { + "required": [ + "profile", + "codec", + "pixel_format", + "encoded_size", + "decoder", + "encoder_parameters", + "source_lossy" + ], + "source_lossy_values": [ + true, + false, + "unknown" + ], + "timebase_role": "index_only", + "lossless_reference": "source compressed packets or fixed-decoder source pixels; depth uses normalized standard float32 bits", + "selection": "choose smaller complete candidate only after exact roundtrip validation" + }, + "tensor_storage_revision": "tensor-bundle-2026-10-09", + "release_layout": { + "directory": "shared-v1.1", + "release_id": "shared-v1.1", + "migration": "Upgrade each dataset in place under shared-v1.0 during maintenance, validate completely, then rename to shared-v1.1; do not retain duplicate published trees. See MIGRATION.md." + }, + "tensor_attributes": { + "visibility": { + "storage_profile": "pt/tensor_bundle/v1", + "allowed_dtypes": [ + "bool", + "float32" + ], + "visibility_types": [ + "boolean", + "ratio" + ], + "ratio_range": [ + 0, + 1 + ], + "scopes": { + "whole_hand": { + "shape": [ + "T", + 2 + ], + "valid_shape": [ + "T", + 2 + ] + }, + "hand_keypoint": { + "shape": [ + "T", + 2, + "K" + ], + "valid_shape": [ + "T", + 2, + "K" + ] + }, + "object": { + "shape": [ + "T" + ], + "valid_shape": [ + "T" + ] + } + }, + "required_metadata": [ + "data_ref", + "data_key", + "axes", + "dtype", + "visibility_type", + "meaning", + "valid_ref", + "valid_key", + "valid_axes", + "storage", + "valid_storage", + "provenance", + "source_locator" + ], + "valid_dtype": "bool", + "unknown": "valid=false; ratio data NaN; boolean data is not interpretable without valid", + "all_known": "explicit all-true bool tensor; do not infer from pose validity", + "note": "No source visibility means omit. Expand explicitly declared all-known scalar validity during migration without changing semantics." + } + }, + "tensor_bundles": { + "camera": { + "path": "camera/camera.pt", + "entries": { + "intrinsic": { + "schema_ids": [ + "camera/pinhole/v1", + "camera/rational8/v1", + "camera/opencv_fisheye4/v1", + "camera/fisheye624/v1" + ] + }, + "extrinsic": { + "schema_ids": [ + "transform/se3/v1" + ] + }, + "distortion": { + "schema_ids": [ + "camera/distortion8/v1", + "camera/fisheye4_distortion/v1" + ] + } + } + }, + "mano": { + "path": "annotation/mano/mano.pt", + "entries": { + "motion": { + "schema_ids": [ + "mano/axis_angle61/v1" + ] + }, + "visibility": { + "attribute_id": "visibility", + "scope": "whole_hand" + } + } + }, + "keypoints": { + "path": "annotation/keypoints/keypoints.pt", + "entries": { + "uv": { + "schema_ids": [ + "keypoints/uv/v1" + ] + }, + "xyz": { + "schema_ids": [ + "keypoints/xyz/v1" + ] + }, + "visibility": { + "attribute_id": "visibility", + "scope": "hand_keypoint" + }, + "whole_hand_visibility": { + "attribute_id": "visibility", + "scope": "whole_hand" + } + } + }, + "object": { + "path": "annotation/object//object.pt", + "entries": { + "pose": { + "schema_ids": [ + "object/rigid/v1" + ] + }, + "visibility": { + "attribute_id": "visibility", + "scope": "object" + }, + "dimensions": { + "schema_ids": [ + "object/dimensions/v1" + ] + }, + "joint_state": { + "schema_ids": [ + "object/joint_state/v1" + ] + }, + "keypoints/xyz": { + "schema_ids": [ + "object_keypoints/camera/v1" + ] + }, + "keypoints/template_xyz": { + "schema_ids": [ + "object_keypoints/template/v1" + ] + }, + "parts//pose": { + "schema_ids": [ + "transform/se3/v1" + ], + "convention": "T_camera_from_part" + }, + "parts//dimensions": { + "schema_ids": [ + "object/dimensions/v1" + ] + }, + "parts//keypoints/xyz": { + "schema_ids": [ + "object_keypoints/camera/v1" + ] + }, + "parts//keypoints/template_xyz": { + "schema_ids": [ + "object_keypoints/template/v1" + ], + "coordinate_frame": "part" + }, + "meshes//vertex_part_ids": { + "schema_ids": [ + "object/vertex_part_ids/v1" + ] + } + } + }, + "contact_pair": { + "path": "annotation/contact/__/contact.pt", + "entries": { + "vertex_region": { + "schema_ids": [ + "contact/vertex_region/v1" + ] + }, + "vertex_distance": { + "schema_ids": [ + "contact/vertex_distance/v1" + ] + } + } + } + }, + "bundle_layout_rules": { + "entry_path_syntax": "Slash-separated dictionary keys in this registry only; serialize references as string arrays. Angle-bracket placeholders resolve to registered IDs, not literal keys.", + "entry_leaves": [ + "data", + "valid" + ], + "additional_entries": false, + "all_entries_optional": true, + "omit_empty_bundles": true, + "identifiers": "object/part/mesh and contact entity IDs must resolve in metadata; reject empty, dot, dot-dot or slash-containing IDs", + "per_view": true, + "no_cross_object_or_camera_merge": true, + "numeric_field_valid_ref_equals_data_ref": true, + "attributes_must_be_registered": true + }, + "reference_rules": { + "file_paths": { + "base": "current camera view root", + "format": "relative POSIX", + "reject": [ + "absolute paths", + "parent traversal", + "external URLs", + "unresolved placeholders" + ] + }, + "dictionary_keys": { + "type": "array", + "item_type": "nonempty_string", + "min_items": 1, + "traversal": "literal nested dictionary lookup; never eval; no automatic flattening", + "data_terminal": "data", + "valid_terminal": "valid", + "target_type": "CPU torch.Tensor" + }, + "bundle_component": { + "required": [ + "data_ref", + "data_key", + "valid_ref", + "valid_key", + "storage", + "valid_storage" + ], + "same_file": true, + "same_entry_prefix": true, + "storage_profile": "pt/tensor_bundle/v1", + "valid_storage_profile": "pt/tensor_bundle/v1" + }, + "media_jsonl": { + "forbidden": [ + "data_key", + "valid_key" + ], + "preserve_original_valid_ref": true, + "standalone_valid_pt_root": "CPU bool torch.Tensor; not dict", + "do_not_label_standalone_valid_as_bundle": true + }, + "camera_distortion": { + "models": { + "rational8": "camera/distortion8/v1", + "opencv_fisheye4": "camera/fisheye4_distortion/v1" + }, + "required": [ + "distortion_ref", + "distortion_key", + "distortion_valid_ref", + "distortion_valid_key" + ], + "distortion_ref": "camera/camera.pt", + "distortion_key": [ + "distortion", + "data" + ], + "distortion_valid_ref": "camera/camera.pt", + "distortion_valid_key": [ + "distortion", + "valid" + ], + "valid_equals_intrinsic_valid": true, + "models_without_separate_distortion": [ + "pinhole", + "fisheye624" + ] + }, + "reader_cache": "Cache bundle by resolved file path; loading different fields must not repeatedly deserialize the file." + }, + "standalone_validity": { + "rgb": { + "data_ref": "observation/rgb.mkv", + "valid_ref": "observation/rgb_valid.pt", + "dtype": "bool", + "shape": [ + "T" + ], + "container": "pt", + "root_type": "CPU Tensor" + }, + "segment": { + "data_refs": [ + "annotation/segment/mask.mkv", + "annotation/segment/polygons.jsonl" + ], + "valid_ref": "preserve source release reference; normally annotation/segment/mask_valid.pt", + "dtype": "bool", + "shape": [ + "T" + ], + "container": "pt", + "root_type": "CPU Tensor" + }, + "relations": { + "data_ref": "annotation/contact/relations.jsonl", + "valid_ref": "annotation/contact/relations_valid.pt", + "dtype": "bool", + "shape": [ + "T" + ], + "container": "pt", + "root_type": "CPU Tensor" + }, + "depth": { + "data_ref": "observation/depth.mkv", + "valid_ref": "observation/depth_valid.mkv", + "dtype": "bool", + "shape": [ + "T", + "H", + "W" + ], + "profile": "mkv/bool_ffv1/v1" + } + } +} diff --git a/H2O/shared-v1.1/script/h2o_v1_1/warehouse.py b/H2O/shared-v1.1/script/h2o_v1_1/warehouse.py new file mode 100644 index 0000000000000000000000000000000000000000..ce543b8c06440f110c03b941a6ee3adde922f13c --- /dev/null +++ b/H2O/shared-v1.1/script/h2o_v1_1/warehouse.py @@ -0,0 +1,201 @@ +"""H2O v1.1 bundle reading and registry validation; no media re-encoding.""" +import hashlib +import json +from pathlib import Path, PurePosixPath + +import torch + +PROFILE = 'pt/tensor_bundle/v1' + + +def sha256(path): + with Path(path).open('rb') as stream: + return hashlib.file_digest(stream, 'sha256').hexdigest() + + +def resolve(root, ref): + if not isinstance(ref, str) or not ref or '\\' in ref: + raise ValueError(f'invalid file reference: {ref!r}') + path = PurePosixPath(ref) + if path.is_absolute() or '..' in path.parts or ':' in ref: + raise ValueError(f'escaping file reference: {ref}') + root = Path(root).resolve() + result = root / path + if not result.resolve().is_relative_to(root) or not result.is_file() or result.is_symlink(): + raise ValueError(f'missing/escaping file reference: {ref}') + return result + + +def layout(name, component): + """Fail closed on fields outside the audited H2O v1.0 release.""" + fixed = { + 'intrinsic': ('camera/pinhole/v1', 'camera/camera.pt', ['intrinsic']), + 'extrinsic': ('transform/se3/v1', 'camera/camera.pt', ['extrinsic']), + 'mano': ('mano/axis_angle61/v1', 'annotation/mano/mano.pt', ['motion']), + 'keypoints_xyz': ('keypoints/xyz/v1', 'annotation/keypoints/keypoints.pt', ['xyz']), + } + expected = fixed.get(name) + for prefix, schema_id, keys in [('pose_', 'object/rigid/v1', ['pose']), + ('points_', 'object_keypoints/camera/v1', ['keypoints', 'xyz'])]: + if name.startswith(prefix): + oid = name.removeprefix(prefix) + if oid not in {'book', 'espresso', 'lotion', 'spray', 'milk', 'cocoa', 'chips', 'cappuccino'}: + raise ValueError(f'unknown H2O object identity: {oid}') + expected = (schema_id, f'annotation/object/{oid}/object.pt', keys) + if expected is None or component['schema_id'] != expected[0]: + raise ValueError(f'unsupported H2O numeric component: {name}') + if component.get('attributes'): + raise ValueError(f'{name}: new numerical attributes need explicit migration support') + return expected[1:] + + +class Reader: + def __init__(self, view): + self.view = Path(view) + self.cache = {} + + def field(self, component, kind='data'): + path = resolve(self.view, component[kind + '_ref']) + if path not in self.cache: + self.cache[path] = torch.load(path, map_location='cpu', weights_only=True) + value = self.cache[path] + keys = component.get(kind + '_key') + if keys is not None: + if not isinstance(keys, list) or not keys or any(not isinstance(k, str) or not k for k in keys): + raise ValueError('dictionary keys must be a nonempty list of nonempty strings') + for key in keys: + if type(value) is not dict or key not in value: + raise ValueError(f'missing dictionary key: {keys}') + value = value[key] + if not isinstance(value, torch.Tensor) or value.device.type != 'cpu': + raise ValueError('reference must resolve to a CPU Tensor') + return value + + +def exact(left, right): + if left.dtype != right.dtype or left.shape != right.shape: + raise ValueError('tensor dtype/shape changed') + a = left.detach().contiguous().reshape(-1).view(torch.uint8) + b = right.detach().contiguous().reshape(-1).view(torch.uint8) + if not torch.equal(a, b): + raise ValueError('tensor bytes changed (including NaN payload or signed zero)') + + + +def exact_metadata(old, new): + allowed = {'data_ref', 'valid_ref', 'data_key', 'valid_key', 'storage', 'valid_storage'} + expected = json.loads(json.dumps(new)) + expected.update(schema_version=old['schema_version'], release_id=old['release_id']) + for name, component in old['components'].items(): + target = new['components'][name] + if component.get('available') and component['data_ref'].endswith('.pt'): + if ({k:v for k,v in component.items() if k not in allowed} != + {k:v for k,v in target.items() if k not in allowed}): + raise ValueError(f'{name}: numerical semantics metadata changed') + elif component != target: + raise ValueError(f'{name}: nonnumerical component metadata changed') + expected['components'][name] = component + if expected != old: + raise ValueError('view semantics metadata changed') + +def check_shape(value, shape, n): + if value.ndim != len(shape) or any( + (wanted == 'T' and actual != n) or (isinstance(wanted, int) and actual != wanted) + for actual, wanted in zip(value.shape, shape, strict=True) + ): + raise ValueError(f'tensor shape {tuple(value.shape)} differs from schema {shape}') + + +def validate_view(view, schema_path): + view = Path(view) + meta = json.loads((view / 'metainfo.json').read_text()) + schema = json.loads(Path(schema_path).read_text()) + if schema['schema_version'] != 'hand-warehouse/1.1' or meta['schema_version'] != schema['schema_version']: + raise ValueError('v1.1 schema required') + if any(k not in meta for k in schema['view_metadata']['required_fields']): + raise ValueError('required view metadata missing') + if (meta['dataset_id'] != 'H2O' or meta['release_id'] != 'shared-v1.1' + or meta['camera_id'] not in [f'cam{i}' for i in range(5)] + or meta['view_type'] != ('ego' if meta['camera_id'] == 'cam4' else 'exo')): + raise ValueError('H2O release/camera/view_type mismatch') + if meta['hand_slots'] != ['left', 'right'] or type(meta['num_frames']) is not int or meta['num_frames'] <= 0: + raise ValueError('hand slots/timeline mismatch') + n = meta['num_frames'] + rows = [json.loads(line) for line in resolve(view, meta['sampling']['frames_ref']).read_text().splitlines()] + if len(rows) != n or [r['frame_index'] for r in rows] != list(range(n)): + raise ValueError('frame mapping incomplete or reordered') + reader, entries, report = Reader(view), {}, {} + for name, c in meta['components'].items(): + if not c.get('available'): + if not c.get('reason'): + raise ValueError(f'{name}: unavailable component needs a reason') + continue + definition = schema['components'][c['schema_id']] + if c.get('attributes'): + raise ValueError(f'{name}: unaudited attributes are not supported') + for required in ['axes', 'provenance', 'source_locator', *definition.get('required_metadata', [])]: + if required not in c: + raise ValueError(f'{name}: missing {required}') + resolve(view, c['data_ref']) + if c.get('valid_ref'): + resolve(view, c['valid_ref']) + for profile_field, allowed in [('storage', 'allowed_storage_profiles'), ('valid_storage', 'allowed_valid_storage_profiles')]: + if allowed in definition and c.get(profile_field, {}).get('profile') not in definition[allowed]: + raise ValueError(f'{name}: unregistered {profile_field} profile') + if definition['storage'] == 'pt': + ref, key = layout(name, c) + if (c['data_ref'] != ref or c['valid_ref'] != ref or c['data_key'] != key + ['data'] + or c['valid_key'] != key + ['valid']): + raise ValueError(f'{name}: noncanonical bundle reference') + entries.setdefault(ref, set()).add(tuple(key)) + data, valid = reader.field(c), reader.field(c, 'valid') + check_shape(data, definition['shape'], n) + check_shape(valid, definition['valid_shape'], n) + if 'K' in definition['shape'] and data.shape[definition['shape'].index('K')] != 21: + raise ValueError(f'{name}: H2O keypoint count must remain 21') + if len(c['axes']) != data.ndim or c.get('valid_axes') != c['axes'][:valid.ndim]: + raise ValueError(f'{name}: axis declaration mismatch') + if c['data_ref'].startswith('annotation/') and not c.get('valid_policy', {}).get('source_rule'): + raise ValueError(f'{name}: source validity policy missing') + if data.dtype != getattr(torch, definition['dtype']) or valid.dtype != torch.bool: + raise ValueError(f'{name}: incorrect tensor dtype') + if data.shape[:valid.ndim] != valid.shape or not torch.isfinite(data[valid]).all() or not torch.isnan(data[~valid]).all(): + raise ValueError(f'{name}: invalid finite/NaN/valid semantics') + if name.startswith(('pose_', 'points_')): + oid = name.split('_', 1)[1] + identity = json.loads(resolve(view, f'annotation/object/{oid}/metainfo.json').read_text()) + if identity['object_id'] != oid: + raise ValueError('unresolved object identity') + report[name] = {'shape': list(data.shape), 'dtype': str(data.dtype), + 'valid_true': int(valid.sum()), 'valid_total': valid.numel()} + else: + if 'data_key' in c or 'valid_key' in c: + raise ValueError(f'{name}: media/JSONL must not use bundle keys') + if c.get('valid_ref', '').endswith('.pt'): + valid = reader.field(c, 'valid') + if valid.dtype != torch.bool or tuple(valid.shape) != (n,): + raise ValueError(f'{name}: standalone validity must remain bool [T]') + for ref, registered in entries.items(): + bundle = reader.cache[resolve(view, ref)] + def visit(node, prefix=()): + if type(node) is not dict or not node: + raise ValueError('bundle must contain nonempty string-key dictionaries') + if set(node) == {'data', 'valid'}: + if prefix not in registered or any(not isinstance(v, torch.Tensor) or v.device.type != 'cpu' for v in node.values()): + raise ValueError('unregistered bundle field or non-CPU tensor') + return {prefix} + found = set() + for key, value in node.items(): + if not isinstance(key, str) or not key: + raise ValueError('invalid bundle key') + found |= visit(value, prefix + (key,)) + return found + if visit(bundle) != registered: + raise ValueError('registered bundle entries missing') + referenced_pt = {c[k] for c in meta['components'].values() if c.get('available') + for k in ('data_ref', 'valid_ref') if c.get(k, '').endswith('.pt')} + if {p.relative_to(view).as_posix() for p in view.rglob('*.pt')} != referenced_pt: + raise ValueError('orphan PT file or obsolete standalone numeric validity') + return {'num_frames': n, 'numeric_components': report, 'bundle_files': len(entries), + 'scope': 'v1.1 registry, keys, shapes, validity and timeline; not a media pixel comparison'} + diff --git a/H2O/shared-v1.1/script/provenance/operations/publish_h2o_v1_1.py b/H2O/shared-v1.1/script/provenance/operations/publish_h2o_v1_1.py new file mode 100644 index 0000000000000000000000000000000000000000..166980dee03e1978ffc0754fe01be907375127dd --- /dev/null +++ b/H2O/shared-v1.1/script/provenance/operations/publish_h2o_v1_1.py @@ -0,0 +1,234 @@ +#!/usr/bin/env python3 +"""Publish only H2O via a verified private PR; never squash repository history.""" +import argparse +from contextlib import contextmanager +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import time + +from huggingface_hub import HfApi, CommitOperationAdd, CommitOperationCopy, CommitOperationDelete, hf_hub_download + +REPO = 'ParityLab/Hand-Datasets-Raw' +OLD, NEW = 'H2O/shared-v1.0', 'H2O/shared-v1.1' + + +def sha(path): + with Path(path).open('rb') as f: + return hashlib.file_digest(f, 'sha256').hexdigest() + + +def write_json(path, value): + tmp = path.with_suffix(path.suffix + '.tmp') + tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + '\n') + with tmp.open('rb') as f: os.fsync(f.fileno()) + os.replace(tmp, path) + + +def safe(root, ref): + p = PurePosixPath(ref) + if not ref or p.is_absolute() or '..' in p.parts or '\\' in ref or ':' in ref: + raise ValueError('unsafe release reference') + path = root / ref + if not path.is_file() or path.is_symlink() or not path.resolve().is_relative_to(root.resolve()): + raise ValueError('missing/escaping release file') + return path + + +def strip_h2o_attributes(data): + prefixes = (b'H2O/shared-v1.0/', b'"H2O/shared-v1.0/', b'H2O/shared-v1.1/', b'"H2O/shared-v1.1/') + return b''.join(line for line in data.splitlines(keepends=True) if not line.startswith(prefixes)) + + +def remote_files(api, revision, prefix): + return {r.path.removeprefix(prefix + '/'): r for r in + api.list_repo_tree(REPO, path_in_repo=prefix, recursive=True, revision=revision, repo_type='dataset') + if getattr(r, 'size', None) is not None} + + +def matches(row, expected): + if row.size != expected['size']: return False + if row.lfs: return row.lfs.sha256 == expected['sha256'] + return row.blob_id == expected.get('git_sha1') + + +def trees(api, revision, prefix=None): + return {r.path: getattr(r, 'tree_id', None) or getattr(r, 'blob_id', None) + for r in api.list_repo_tree(REPO, path_in_repo=prefix, revision=revision, repo_type='dataset')} + + +def outside_h2o(values): + return {k:v for k,v in values.items() if k not in ('H2O', '.gitattributes')} + + +def source_rows(api, work, revision): + plan = json.loads((work / 'PLAN.json').read_text()) + hashes = dict(plan['root_source_sha256']) + rows = {} + for seq in plan['sequences']: + inventory = json.loads((work / 'inventory' / (seq + '.json')).read_text())['files'] + rows.update(inventory) + for cam in range(5): + record = json.loads((work / 'checkpoints' / seq / f'cam{cam}.json').read_text()) + hashes.update({record['view'] + '/' + k:v for k,v in record['source_sha256'].items()}) + for folder in ('doc', 'script'): + for ref,row in remote_files(api, revision, OLD + '/' + folder).items(): + rows[folder + '/' + ref] = {'size':row.size,'oid':row.blob_id, + 'lfs':{'oid':row.lfs.sha256} if row.lfs else None} + by_content = {} + for ref,row in sorted(rows.items()): + by_content.setdefault((hashes[ref], row['size']), (ref,row)) + return by_content + + +def build_plan(root, work, api, manifest): + sources = source_rows(api, work, manifest['source_revision']) + files = {} + for ref,entry in sorted(manifest['files'].items()): + path = safe(root, ref) + if path.stat().st_size != entry['size']: raise ValueError(f'local size changed: {ref}') + source = sources.get((entry['sha256'],entry['size'])) + item = dict(entry) + if source: + src,row = source + if row.get('lfs'): + item.update(kind='copy', source=OLD + '/' + src) + else: + item.update(kind='add', git_sha1=row['oid']) + else: + if path.suffix == '.mkv': raise ValueError('refuse to upload/re-encode an unmatched media file') + h = hashlib.sha1(f'blob {entry["size"]}\0'.encode()) + with path.open('rb') as f: + while chunk := f.read(4*1024*1024): h.update(chunk) + item.update(kind='add', git_sha1=h.hexdigest()) + files[ref] = item + return {'source_revision':manifest['source_revision'], 'raw_tree_oid':manifest['raw_tree_oid'], + 'manifest_sha256':sha(work/'PUBLISH_MANIFEST.json'), 'files':files, + 'copy_files':sum(e['kind']=='copy' for e in files.values()), + 'local_upload_bytes':sum(e['size'] for e in files.values() if e['kind']=='add')} + + +def operations(root, plan, refs): + result = [] + for ref in refs: + e = plan['files'][ref] + if e['kind']=='copy': + result.append(CommitOperationCopy(e['source'],NEW+'/'+ref,src_revision=plan['source_revision'])) + else: + path = safe(root,ref) + if sha(path)!=e['sha256']: raise ValueError(f'local content changed: {ref}') + result.append(CommitOperationAdd(NEW+'/'+ref,path)) + return result + + +def batches(refs, files): + batch, size = [],0 + for ref in refs: + n = files[ref]['size'] if files[ref]['kind']=='add' else 0 + if batch and (len(batch)>=100 or size+n>48*1024**2): + yield batch;batch=[];size=0 + batch.append(ref);size+=n + if batch: yield batch + + +def verify_release(api, revision, plan): + actual = remote_files(api,revision,NEW) + if set(actual)!=set(plan['files']): raise ValueError('remote release file set mismatch') + for ref,e in plan['files'].items(): + if not matches(actual[ref],e): raise ValueError(f'remote size/content mismatch: {ref}') + h2o=trees(api,revision,'H2O') + if OLD in h2o or h2o.get('H2O/raw')!=plan['raw_tree_oid']: + raise ValueError('old tree still present or raw tree changed') + return h2o[NEW] + + +def main(): + p=argparse.ArgumentParser(description=__doc__) + p.add_argument('--root',type=Path,required=True) + p.add_argument('--work',type=Path,required=True) + args=p.parse_args();root=args.root.resolve();work=args.work.resolve() + if root.name!='shared-v1.1' or root.parent.name!='H2O' or not work.is_relative_to(root.parent/'tmp'): + p.error('H2O final root and dedicated existing work required') + manifest=json.loads((work/'PUBLISH_MANIFEST.json').read_text()) + state=json.loads((work/'RUN.json').read_text()) + if state['phase']!='local_finalized_not_uploaded' or state['completed_views']!=920: + p.error('completed local release and post-full approval required') + actual={q.relative_to(root).as_posix() for q in root.rglob('*') if q.is_file() and q.suffix!='.pyc' and '__pycache__' not in q.parts} + if actual!=set(manifest['files']): raise ValueError('local release file set drift') + api=HfApi();api.auth_check(REPO,repo_type='dataset',write=True) + log_path=work/'HF_PUBLICATION.json' + lock=(work/'HF_PUBLICATION.lock').open('a') + fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + plan_path=work/'HF_PUBLICATION_PLAN.json' + if plan_path.exists(): + plan=json.loads(plan_path.read_text()) + if plan['manifest_sha256']!=sha(work/'PUBLISH_MANIFEST.json'): raise ValueError('publication manifest changed') + else: + plan=build_plan(root,work,api,manifest);write_json(plan_path,plan) + print('PUBLISH_PLAN',len(plan['files']),'files',plan['copy_files'],'server copies',plan['local_upload_bytes'],'upload bytes',flush=True) + run=json.loads(log_path.read_text()) if log_path.exists() else {'phase':'preparing','created_utc':datetime.now(timezone.utc).isoformat()} + try: + head=api.repo_info(REPO,repo_type='dataset').sha + live=trees(api,head,'H2O');fixed=trees(api,plan['source_revision'],'H2O') + if NEW in live: + final=verify_release(api,head,plan) + run.update(phase='published_verified',final_commit=head,target_tree_oid=final) + write_json(log_path,run);print('PUBLISHED_VERIFIED',head,flush=True);return + if live.get(OLD)!=fixed.get(OLD) or live.get('H2O/raw')!=plan['raw_tree_oid']: + raise ValueError('H2O source/raw changed; do not overwrite') + if 'pr' not in run: + attrs=Path(hf_hub_download(REPO,'.gitattributes',repo_type='dataset',revision=head)).read_bytes() + trimmed=work/'H2O_CLEAN_GITATTRIBUTES';trimmed.write_bytes(strip_h2o_attributes(attrs)) + proof=['data/subject1_k2_6/cam0/observation/rgb.mkv','data/subject1_h1_0/cam0/observation/depth.mkv'] + run.update(base_commit=head,base_root=trees(api,head),phase='creating_private_pr',proof_files=proof) + write_json(log_path,run) + commit=api.create_commit(REPO,repo_type='dataset',revision='main',parent_commit=head,create_pr=True, + operations=[CommitOperationDelete(OLD,is_folder=True),CommitOperationAdd('.gitattributes',trimmed)]+operations(root,plan,proof), + commit_message='Prepare H2O shared-v1.1 migration (private PR)',num_threads=4) + run.update(pr=int(commit.pr_url.rstrip('/').split('/')[-1]),revision=commit.pr_revision,head=commit.oid,phase='staging') + write_json(log_path,run) + print('PRIVATE_PR',run['pr'],run['revision'],flush=True) + branch_head=api.repo_info(REPO,repo_type='dataset',revision=run['revision']).sha + existing=remote_files(api,branch_head,NEW) + for ref,row in existing.items(): + if ref not in plan['files'] or not matches(row,plan['files'][ref]): raise ValueError('private branch content drift') + missing=[ref for ref in plan['files'] if ref not in existing] + done=len(existing) + for batch in batches(missing,plan['files']): + commit=api.create_commit(REPO,repo_type='dataset',revision=run['revision'],parent_commit=branch_head, + operations=operations(root,plan,batch),commit_message=f'Stage H2O shared-v1.1 {done+len(batch)}/{len(plan["files"])}',num_threads=4) + branch_head=commit.oid;done+=len(batch) + run.update(head=branch_head,staged_files=done,phase='staging');write_json(log_path,run) + print('STAGED',done,'/',len(plan['files']),branch_head,flush=True) + tree_id=verify_release(api,branch_head,plan) + if outside_h2o(trees(api,branch_head))!=outside_h2o(run['base_root']): raise ValueError('private PR changes other datasets') + before=api.repo_info(REPO,repo_type='dataset').sha + current=trees(api,before,'H2O') + if current.get(OLD)!=fixed.get(OLD) or current.get('H2O/raw')!=plan['raw_tree_oid'] or NEW in current: + raise ValueError('H2O changed during staging; merge halted') + attrs_live=Path(hf_hub_download(REPO,'.gitattributes',repo_type='dataset',revision=before)).read_bytes() + attrs_branch=Path(hf_hub_download(REPO,'.gitattributes',repo_type='dataset',revision=branch_head)).read_bytes() + if strip_h2o_attributes(attrs_live)!=strip_h2o_attributes(attrs_branch): + raise ValueError('non-H2O LFS tracking changed; merge halted for review') + before_root=trees(api,before) + run.update(phase='verified_before_merge',verified_branch_commit=branch_head,premerge_head=before,target_tree_oid=tree_id) + write_json(log_path,run) + discussion=api.get_discussion_details(REPO,run['pr'],repo_type='dataset') + if discussion.status=='draft': api.change_discussion_status(REPO,run['pr'],'open',repo_type='dataset') + api.merge_pull_request(REPO,run['pr'],repo_type='dataset',comment='All H2O release paths, sizes and content digests verified. Raw unchanged. No repository history squash.') + final=api.repo_info(REPO,repo_type='dataset').sha + final_tree=verify_release(api,final,plan) + if outside_h2o(trees(api,final))!=outside_h2o(before_root): raise ValueError('other dataset roots changed across merge; investigate') + run.update(phase='published_verified',final_commit=final,target_tree_oid=final_tree,files=len(plan['files']),raw_unchanged=True) + write_json(log_path,run);print('PUBLISHED_VERIFIED',final,flush=True) + except Exception as exc: + run.update(failed_phase=run.get('phase'),phase='failed',error=str(exc)) + write_json(log_path,run) + print('PUBLISH_FAILED_NO_HISTORY_SQUASH',repr(exc),flush=True) + raise + + +if __name__=='__main__':main() diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/doc/CONTRACT.md b/H2O/shared-v1.1/script/v1_0_snapshot/doc/CONTRACT.md new file mode 100644 index 0000000000000000000000000000000000000000..f756d711647e109b6bb732ce1b9c84111730489d --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/doc/CONTRACT.md @@ -0,0 +1,457 @@ +# 手物数据仓库统一约定 v1.0 + +格式版本:`hand-warehouse/1.0`。存储约定:`lossless-video-2026-09-18`。 + +范围限于手物交互重建。按本任务纳入的源模态转换,不要求每个数据集填满所有组件。缺失模态、尚未下载、语义未核实分别报告,不能互相替代。 + +本文定义各字段的含义与使用规则,机器可读注册表见 [schema.json](schema.json)。两者互相补充;如有冲突,应先核实并统一定义。 + +## 1. 目录 + +```text +hand-datasets/ + / + raw/ + doc/ # 官方说明、来源与校验记录 + script/ # 官方下载脚本、必要包装脚本 + data/ # 保留原始包,不原地解压或改写 + / + doc/ # 发布说明、schema、来源清单 + script/ # 转换、校验脚本及运行配置 + data/ + / + / + metainfo.json + observation/ + rgb.mkv + rgb_valid.pt + depth.mkv # float32 深度的可逆视频编码 + depth_valid.mkv # 逐像素 bool 的无损视频编码 + camera/ + frames.jsonl + intrinsic.pt + intrinsic_valid.pt + extrinsic.pt + extrinsic_valid.pt + annotation/ + mano/ + motion.pt + motion_valid.pt + visibility.pt + keypoints/ + uv.pt + uv_valid.pt + xyz.pt + xyz_valid.pt + visibility.pt # 源数据有时提供 + object/ + / + assets/ # 该物体的网格、材质、纹理及部件资产 + .obj + pose.pt + pose_valid.pt + visibility.pt + metainfo.json # 物体身份、类别、mesh、尺寸与部件引用 + articulation.json + keypoints/ + vertex_part_ids.pt + joint_state.pt + joint_state_valid.pt + parts//pose.pt + parts//pose_valid.pt + segment/ + mask.mkv + mask_valid.pt + instances.jsonl + contact/ + relations.jsonl + __/ # 对应实体间的距离/接触区域 +``` + +目录展示可能存在的组件,不要求填满。具体文件、字段和缺省规则分别见后续对应小节。原始包的解压发生在临时工作区,raw 内原始包保持不变。 + +## 2. 相机视图的 metainfo.json + +### 2.1 顶层字段与发布信息 + +每个相机视图必须有 `metainfo.json`。以下字段除另行说明外均为必填: + +| 字段 | 填写内容 | +|---|---| +| schema_version | 结构版本,本版为 `hand-warehouse/1.0` | +| dataset_id | 数据集的逻辑标识 | +| release_id | 本次数据发布版本,对应目录中的 dataset_version | +| sequence_id | 所属序列或独立图片样本的标识 | +| camera_id | 当前相机视图标识 | +| sample_type | `image` 或 `video`,规则见 2.2 | +| num_frames | 当前视图帧数 T,所有随帧组件按同一时间轴组织 | +| hand_slots | 固定为 `["left", "right"]`;解剖学左右的使用规则见 5.1 | +| sampling | 采样类型、源 FPS、帧索引引用及选择策略,见 2.2 | +| camera | 当前相机模型与图像尺寸,见 2.3 | +| components | 实际提供的组件及其文件、schema、有效性和来源,见 2.5 | +| split | `train/val/test/unknown`,划分协议见 2.4 | +| view_type | 可选,`ego/exo/unknown` | + +`dataset_version` 是数据发布版本;`schema_version` 是结构版本,两者独立。原始包校验摘要、官方来源和转换配置应记录在发布清单中。解压发生在临时工作区,原始包保持不变。 + +### 2.2 图片、视频与 sampling + +`sample_type=image`:允许单图 T=1、`sampling.type=single`,也允许将独立图片批量装入一个视频容器,T>1 时 `sampling.type=independent`、`source_fps=null`。分片大小按数据集选择;FreiHAND 默认每片最多 4096 张,训练与评估分开,尾片不补帧。该数量不是其他数据集的强制要求;同批分辨率、相机模型类型及划分协议一致。每行 frames 必须有稳定且唯一的 `sample_id`、原始文件定位;内参、手形状等仍逐帧保留,不能因打包而共享错误的标定或身份。`sequence_id` 在这里仅是批次标识,不代表真实序列;不得按相邻帧推断跟踪、同步或接触延续。源 camera_id、image_variant、split 等随样本变化时放在 frames 的对应字段中。真实采集时间未知则 timestamp_ns=null。合成背景变体不视为真实多相机。 + +`sample_type=video`:`sampling.type=dense/sparse`;`source_fps` 是真实采集 FPS,未知为 null。非连续取样必须保留源帧号和已知源时间,不可用采样后索引除以 FPS 冒充源时间。可另记采样策略与步长。 + +shared 可以仅存所选 RGB 帧对应的数据。OakInk2 图像/动捕不同采样率时用 annotation_matches 明确映射;不要求将未采样动捕点硬塞进 T。多视角身份和源同步关系要保留;选择了哪些帧/相机及原因写在 sampling 中。 + +`sampling.frames_ref` 指向 `camera/frames.jsonl`。帧号、逐帧时间、同步与标注匹配记录的结构见 4.1;MKV 封装时间的约定见 3.1。 + +### 2.3 camera 模型声明 + +`camera` 至少包含 `model`、`schema_id`、`image_size:[W,H]`。模型未知使用 `unknown` 和 `null`,不猜成针孔。实际内参、畸变及外参数组放在 `camera/`,各模型的固定结构见第 4 节。 + +### 2.4 split 与划分协议 + +保留上游划分,不将同一采集序列的相邻帧随意拆到不同集合。 + +有官方划分时必填 split_scheme 和 split_source_locator,split_scheme 区分如 Dex-YCB s0/s1、ARCTIC P1/P2 等选定协议;不知道时 split=unknown 并给理由,不凭空分配。每发布可选择一种协议;存在逐帧差异时 frames 中的 split 覆盖视图默认值,并登记其来源。 + +### 2.5 components 组件登记 + +组件表的键是本发布内唯一名称,例如 `rgb`、`depth`、`mano`、`keypoints_uv`。每个已提供组件声明以下信息;模态特有参数在第 3–5 节对应小节中定义。 + +| 字段 | 约定 | +|---|---| +| available | 本发布是否提供该组件;缺省也表示未提供 | +| schema_id | 已登记的具体存储与语义类型,不得临时创造未登记名称 | +| data_ref | 数据文件路径,相对当前相机视图根目录,使用 POSIX 路径 | +| axes | 数组各维度的含义 | +| valid_ref / valid_axes | 有效性文件及其维度;语义由所属组件规定 | +| storage / valid_storage | 视频数据/视频有效性的存储配置;包含已登记 profile、实际 codec、pixel_format、encoded_size,见 3.1;非视频组件按原数组规则 | +| provenance | source / format_conversion / derived,以及转换或生成方法 | +| source_locator | 原文件、压缩包成员和记录/帧的定位信息 | + +不存在的组件允许缺省或写作 `{ "available": false, "reason": "..." }`,不用引用不存在的文件。静态网格可声明标量有效性;具体见 5.4。观测的 valid 见第 3 节,标注的 valid 与 visibility 区分见 5.1。 + +`provenance.kind` 使用 source/format_conversion/derived,`method` 说明转换或生成方法;发布清单补充脚本版本、参数、输入摘要。`source_locator` 定位到原始文件/压缩包成员和记录、帧号;允许引用有完整溯源清单的前一发布,但链条最终应能回到 raw。不得仅写一个无法定位记录的数据集名字。 + +`.pt` 仅保存 CPU Tensor,不保存 Python 自定义对象;浮点默认 float32,有效性为 bool,浮点无效位置填 NaN。所有随帧数组保留首维 T,单帧也不 squeeze;静态资产按其 schema 单独声明。单位、坐标及固定形状见各组件小节。 + +机器注册表 `schema.json` 中,`components` 固定解码后的数据类型、形状、单位和语义;`storage_profiles` 固定视频内的编码/还原方式。不得临时创造未登记的 schema_id 或 storage.profile。同一语义允许选择其登记的不同无损存储 profile。 + +## 3. observation 观测数据 + +### 3.1 rgb.mkv 与 rgb_valid.pt + +RGB、深度和栅格 mask 在 shared 中统一使用 MKV 视频容器,不展开为逐帧图片或图像 tar。MANO、关键点、位姿等数值标注仍用数组;分割的重叠多边形仍用 JSONL,不为了视频化而有损栅格化。单图可为一帧视频,独立图批量封装规则见 2.2。 + +**无损指共享层不增加信息损失。** 源 JPEG/H.264 等本身可能已是有损编码,原样保留并不恢复已丢失信息;不得重新以有损 JPEG、H.264、H.265、AV1 参数编码。源视频/图片的色彩、位深、分辨率和几何关系不得被静默改变。RGB schema `rgb/uint8/v1` 的统一读取结果是 `[T,H,W,3] uint8`、RGB 通道,有效性仍为 `rgb_valid.pt [T] bool`。超出该 schema 的高位深或 HDR 源必须报告并扩展定义,不能降到 8 位冒充无损。 + +#### 3.1.1 允许的 RGB 存储 profile + +| storage.profile | 编码方式 | 适用规则 | +|---|---|---| +| mkv/mjpeg_copy/v1 | 源 JPEG 压缩帧直接封装成 MJPEG/MKV | 不解码重编码;保持每张 JPEG 码流字节;普通 8 位 JPEG 且 MKV/解码器支持时使用 | +| mkv/source_copy/v1 | 已有视频的 RGB 对应码流直接封装为 MKV | 仅源编码能被 MKV 和选定解码器支持时使用,不伪造帧;需维持正确的呈现顺序与依赖帧 | +| mkv/h264_rgb_lossless/v1 | libx264rgb 的真正无损模式 | 必须 RGB 路径、CRF=0,并通过全帧 RGB 字节比较;不能替换成默认 libx264 YUV420 路径 | +| mkv/ffv1_rgb/v1 | FFV1 的 RGB 可逆编码路径 | 作为通用候选;解码回 RGB 后必须逐字节相同,不做色度降采样 | + +优先尝试源码流直接封装;不能封装或需要选择稀疏帧时,比较 FFV1 与无损 RGB H.264。对完整待发布片段,只在通过无损验收的候选中选择文件较小者,不假设某个编码器总最小;编码时间和随机读取代价记入构建记录。中间候选不作为 shared 多份常驻。H.264 跨帧压缩允许较长 GOP,必须记录 GOP/关键帧间隔,随机取帧需从前一关键帧正确解码,不能把 seek 返回的近似帧当目标帧。 + +普通源视频可以保留它已有的有损码流,但不允许新增有损重编码。源是 VRS 等记录容器时,先查明图像流实际编码:已有兼容 JPEG/视频包可直接提取封装,否则解码后使用真正无损编码;不把整个 VRS 改后缀当 MKV。PNG 不要求直接塞进 MKV,可选上表两种无损重编码方式。 + +#### 3.1.2 视频配置与校验 + +每个视频组件在 metainfo 中登记 `storage`,至少包含: + +| 字段 | 内容 | +|---|---| +| profile | 上述登记的存储 profile;语义仍由组件 schema_id 指定 | +| codec | 文件中实际 codec,例如 mjpeg、h264、ffv1;source_copy 必须写实际 codec | +| pixel_format | 实际编码像素格式;不得仅凭编码器参数猜测 | +| encoded_size | 视频物理像素尺寸 `[width,height]`;深度可能不同于逻辑尺寸,见 3.2 | +| decoder | 解码器名称、版本,以及颜色矩阵/范围/旋转处理等实际像素解释配置;未知的源色彩声明 unknown,不擅自称为 sRGB | +| encoder_parameters | 重编码时的编码器、版本、无损模式和 GOP 等参数;直接封装时记录 stream_copy | +| source_lossy | 源是否已有损:true / false / unknown;不是共享层再有损编码的许可 | + +无损重新编码的 RGB 必须使用同一固定解码配置,比较**全部帧**的统一 RGB 字节、数量及顺序。MJPEG-copy 不重新编码,生产校验采用 `jpeg-packets-all-rgb-sample16/v1`:从 MKV 逐包取回,对全部源 JPEG 的 SHA256、数量、顺序和图像尺寸进行精确核对;每视图另用同一固定解码配置比较最多 16 帧的源与目标 RGB 字节(含首尾与四分位位置,其余由固定种子抽取)。记录策略、实际索引、种子与结果;不足 16 帧时全查。试点与最终完整序列随机抽查,对选中视图的全部帧复核解码 RGB。历史已做全帧像素检查的证明继续保留。 + +逐包一致与像素抽查的范围必须分别声明,不能将抽查写成全量像素检查。不能用 PSNR 高、视觉相似、编码器参数称为 lossless 等替代精确检查。同时保留源编码的色彩标记和必要元数据;原图有 EXIF/色彩/方向等元数据时保留 raw 和必要来源信息;不能静默自动旋转图像而不更新像素对应与标定。以上加速策略仅适用于原 JPEG 码流直接封装,不适用于深度、标签或重新编码的 RGB。 + +所有共享视频的呈现帧顺序与统一 frame_index 一一对应,每个栅格组件恰好 T 帧。MKV 的 `storage_fps` 只服务封装,声明 `timebase_role=index_only`;source_copy 可以保留源 PTS 以避免改坏码流,但真实时间与标注对齐仍以 frames 为准。未知真实时间保留 null。缺失某帧组件时保留索引位置并使用该组件的无效占位/valid 标识,不删帧;不能以重复相邻图像冒充已知观测。 + +### 3.2 depth.mkv 与 depth_valid.mkv + +深度语义仍是 `depth/z_float32/v1`:统一读取结果 `[T,H,W] float32`,米制相机 Z 分量,`depth_type=z`。有效深度有限且大于 0,无效位置为 NaN。`depth_origin=measured/rendered/unknown` 必填,来源不明时 unknown。默认与 RGB 共用像素网格及相机参考系,不处理未注册 RGB-D。射线距离必须依据源定义转换成 z,不能只改声明。 + +#### 3.2.1 float32 的可逆视频编码 + +采用 `mkv/depth_float32_bits/v1`:**不是把深度量化成 uint16**,而是将规范化后每个 IEEE-754 float32 的完整 32 位拆成两个 uint16,使用 FFV1 gray16le 保存。视频物理尺寸为 `[2W,H]`:每行前 W 列存原 float32 位串的低 16 位,后 W 列存高 16 位。读取时先合并为 uint32 位串,再按 float32 重新解释,不能数值 cast 成 float32。 + +```text +u = reinterpret_uint32(depth_float32) +encoded[:, :, :W] = uint16(u & 65535) +encoded[:, :, W:] = uint16(u >> 16) +u_restored = uint32(low) | (uint32(high) << 16) +depth_float32 = reinterpret_float32(u_restored) +``` + +统一采用 little-endian 原始字节接口。`camera.image_size` 始终是逻辑 RGB 尺寸 `[W,H]`,不能改成编码视频的 2W;`storage.encoded_size=[2W,H]`。包括 NaN 在内的 float32 位串必须全帧完全恢复,不允许改成 float16、整数毫米、归一化灰度或 RGB 伪彩色。这里的无损验收基准是完成既定米制/坐标转换后的标准 float32 数组,不声称消除 float64→float32 等原约定转换本身的舍入。 + +#### 3.2.2 逐像素有效性 + +`depth_valid.mkv` 使用 `mkv/bool_ffv1/v1`,FFV1 gray8(FFmpeg pixel_format=`gray`),物理尺寸 `[W,H]`。像素只能为 0 或 1,统一解码为 `[T,H,W] bool`,逐像素含义不变。这样不再把庞大的 bool 数组保存为未压缩 `.pt`;标注的帧级/手级 valid 仍保留原有小数组。 + +登记示例(W、H 以下取 640、480;decoder/encoder_parameters 的实际版本由转换器填写): + +```json +{ + "available": true, + "schema_id": "depth/z_float32/v1", + "data_ref": "observation/depth.mkv", + "axes": ["T", "height", "width"], + "valid_ref": "observation/depth_valid.mkv", + "valid_axes": ["T", "height", "width"], + "unit": "m", + "depth_type": "z", + "depth_origin": "measured", + "invalid_value": "NaN", + "storage": { + "profile": "mkv/depth_float32_bits/v1", + "codec": "ffv1", + "pixel_format": "gray16le", + "encoded_size": [1280, 480], + "source_lossy": false, + "decoder": {"name": "ffmpeg", "version": "填写实际版本"}, + "encoder_parameters": {"name": "ffv1", "level": 3, "version": "填写实际版本"} + }, + "valid_storage": { + "profile": "mkv/bool_ffv1/v1", + "codec": "ffv1", + "pixel_format": "gray", + "encoded_size": [640, 480], + "source_lossy": false, + "decoder": {"name": "ffmpeg", "version": "填写实际版本"}, + "encoder_parameters": {"name": "ffv1", "version": "填写实际版本"} + }, + "provenance": {"kind": "format_conversion", "method": "源深度转米制 z float32;逐位打包为 FFV1"}, + "source_locator": {"file": "raw/data/depth.zip", "member": "depth/0001.png"} +} +``` + +深度和有效性视频都必须逐帧解码验收:float32 位串相同、bool 相同、T 相同,并检查 valid=true 的正有限值和 valid=false 的 NaN。读取器必须按 profile 还原,不能把 depth.mkv 的编码像素直接当深度值。 + +## 4. camera 相机、帧索引与标定 + +### 4.1 frames.jsonl:索引、时间与对应关系 + +`camera/frames.jsonl` 每行对应统一帧号 `frame_index=0..T-1`,是所有组件的唯一行索引。至少包含 `frame_index`、`timestamp_ns`、`clock_domain`、`source_locator`;原始帧号/文件名保存在 `source_frame_id`,不能被新帧号替代。每行还可有 `annotation_matches`,按组件键保存 `source_frame_id`、`source_timestamp_ns`、`clock_domain`、`match_method` 和 `delta_ns`;方法为 exact/index_map/nearest/interpolated,索引映射无时间依据时 delta_ns=null。nearest 必须记录允许误差;interpolated 必须记录两端源标识和权重。delta_ns 仅在同一时间域中计算为源标注时间减图像时间。多相机共享 `sequence_id`;已知同步关系必须用 `sync_id` 或明确的源帧/时间映射表达,不能仅凭相同数组索引认定同步。 + +每个视图必须提供此文件。源时间使用整数纳秒及 `clock_domain`,未知写 JSON `null`;不同时间域不能直接比较。逐帧 split 可以覆盖 metainfo 的视图默认划分,并保留来源,见 2.4。 + +### 4.2 坐标系与标定通则 + +| 项目 | 统一约定 | +|---|---| +| 相机坐标 | 右手系,X 向右、Y 向下、Z 向前,长度单位米 | +| 齐次变换 | 列向量,`p_target = T_target_from_source @ p_source` | +| 图像坐标 | `(u,v)`;左上像素中心为 `(0,0)`,u 向右、v 向下,单位 pixel | +| 固定标定 | 本版展开为 T 份,同一 schema 不混用静态与动态形状 | +| 分辨率或模型变化 | 分开存储为视图/片段,不在同一组件中混装 | +| 未知标定 | 相机内外参允许缺省,不填单位阵冒充已知标定 | + +### 4.3 intrinsic.pt 与畸变参数 + +| model / schema_id | intrinsic.pt 的固定结构 | +|---|---| +| pinhole / camera/pinhole/v1 | `[T,3,3]`,标准 K,最后一行为 `[0,0,1]`;限无畸变或已校正图像 | +| fisheye624 / camera/fisheye624/v1 | `[T,15]`,`[f,cx,cy,k0,k1,k2,k3,k4,k5,p0,p1,s0,s1,s2,s3]`,采用 Project Aria Fisheye624 投影定义 | +| opencv_fisheye4 / camera/opencv_fisheye4/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件 `distortion_ref` 指向 `[T,4]`,顺序 `[k1,k2,k3,k4]`,使用 OpenCV fisheye 等距角度多项式;已由 ReInterHand 实际原始相机参数验证 | +| rational8 / camera/rational8/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件必需 `distortion_ref` 指向 `[T,8]`,顺序 `[k1,k2,p1,p2,k3,k4,k5,k6]` | +| unknown / null | 不提供可用 intrinsic,不声称可以投影 | + +有畸变的其他模型必须注册新 schema,固定参数名、顺序和投影公式;不能塞进针孔 K 后遗失畸变项。`metainfo.camera.schema_id` 必须与 intrinsic 组件一致。同一模型的别名不可隐式改变参数布局。 + +`opencv_fisheye4`:对前方点令 `x=X/Z, y=Y/Z, r=sqrt(x²+y²), theta=atan(r)`,`theta_d=theta*(1+k1*theta²+k2*theta⁴+k3*theta⁶+k4*theta⁸)`;`u=fx*x*theta_d/r+cx, v=fy*y*theta_d/r+cy`。光轴 r=0 时使用连续极限 `theta_d/r=1`。四系数不能按普通径向畸变解释,也不能补零冒充 Fisheye624。 + +rational8 对归一化坐标 x=X/Z、y=Y/Z,令 r²=x²+y²,径向项为 `(1+k1*r²+k2*r⁴+k3*r⁶)/(1+k4*r²+k5*r⁴+k6*r⁶)`;再加 p1/p2 切向项并经 K 得到像素。`distortion_ref` 与 intrinsic 共用 `[T]` valid,保存到 camera/distortion.pt。不得把这种畸变三维坐标当作真实相机系 xyz 保存。 + +内参有效性为 `intrinsic_valid.pt [T] bool`;有畸变时使用对应 `distortion_ref`。同一模型的参数名和顺序固定。 + +### 4.4 extrinsic.pt 与 extrinsic_valid.pt + +`extrinsic.pt` 为 `[T,4,4]`,schema `transform/se3/v1`,方向固定 `T_camera_from_world`,有效性 `[T]`。世界坐标含义及源坐标转换记录在 provenance 中;只有相机坐标标注不要求虚构世界坐标。旋转块须正交且 determinant≈1。 + +## 5. annotation 标注数据 + +### 5.1 标注通则:手槽、valid 与 visibility + +手槽固定为 0=left、1=right,指解剖学左右,不按画面位置或可见性重排。本阶段只处理左右手两槽,不处理更多手。实体引用使用 `hand_left`、`hand_right`;手槽不证明跨采集片段的个人身份。 + +#### 5.1.1 valid:标注是否可用于监督 + +标注的 `valid=true` 表示:有对应实际标注、通过本 schema 数值检查,且通过来源明确提供并适用于该组件的有效性/QA 条件。`valid=false` 可由缺标注、无法建立帧对应、源无效占位或官方 QA 不通过导致;不等于画面没有手或手不可见。各组件独立判断,MANO 按 `[T,2]` 标记左右手,关键点按 `[T,2,K]` 标记。 + +**2026-09-20 将标注 valid 从“仅表示存在”修订为“可用于监督”,字段形状不变。** 公式为 `source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass`。没有官方 QA 时省略最后一项,不伪造 QA;不能把未知当成已通过已存在的 QA。适配器在组件 `valid_policy` 中记录具体规则、来源、聚合/广播作用域。缺失官方必需 QA 的记录须明确处理为未知或暂停验收,不能静默通过。无效浮点项仍填 NaN,原始数据保留在 raw;被排除原值可用于 doc 中明确标识的诊断渲染,不能冒充 shared 有效监督。 + +本地筛选须依据明确的规则,并在 `valid_policy.local_excluded_frame_indices`、排除原因和正式报告中记录。单个可疑投影作为问题记录,不直接硬编码排除该帧。已确认的曝光异常须明确作用范围,不能把一个序列的“前两帧有问题”套到所有序列。RGB 编码完好与几何监督可用是两件事,允许保留原图及帧索引而屏蔽对应标注;未发现问题不等于完成全部人工审核,试点待确认时不能作为已验收发布使用。 + +源字段必须按官方语义映射,不能直接按名字复制: + +| 来源 | 官方含义 | 映射原则 | +|---|---|---| +| [H2O](https://github.com/taeinkwon/h2odataset) 的手标注首位 | 0 未标注、1 已标注 | 可作为对应手标注存在性的依据,不推断未标注原因 | +| [HOT3D](https://github.com/facebookresearch/hot3d#using-mask-files) 的 pose_available、visible、mask_qa_pass | 分别表达姿态存在、可见性、对画面中可见手物位姿的人工 QA | 逐手/物体记录决定存在性,再 AND 当前相机当前帧 QA;QA 是整帧聚合判定,保守排除该帧全部手物几何监督,不声称每个实体均有错误;源可见性基于位姿推导时,其自身 valid 同样受 QA 约束 | +| [Dex-YCB](https://github.com/NVlabs/dex-ycb-toolkit#loading-dataset-and-visualizing-samples) 的全零 pose_m、全 -1 joints | 不可见的手或缺标注共用占位表示 | 对应组件 valid=false;不能从该值判定 visibility=false,也不能声称原因是动捕缺失 | +| [ARCTIC](https://github.com/zc-alexfan/arctic/blob/master/docs/data/data_doc.md) 的 is_valid/left_valid/right_valid | 是否有效用于官方评估 | 核实每项筛选依据;不把可见性/评估选择直接等同 QA。本次原始 mano.npy 不含这些派生评估标记,按原记录与数值检查生成 valid,并声明没有额外官方 QA 输入 | + +源 valid=false 若代表评估筛选或其他条件,应检查实际标注和源约定后映射;不能一律清空坐标。反之,占位零或 -1 只有在源官方明确规定时才判为缺失,不泛化成所有数据的判断规则。 + +`valid=true` 的标注应通过其 schema 的数值与形状检查;检查失败必须报告或修复,不能静默隐藏。QA 不通过应报告排除数量与原因,并保留可追溯信息;不能把这类无效称为缺标注。RGB、深度等观测有效性仍按各自 schema;手物 QA 不自动否定 RGB、静态相机内参或物体资产。相机外参是否过滤须依据其自身来源规则;HOT3D 本次保留源外参用于溯源和诊断,不能用其存在性证明 QA 失败帧的几何监督正确。 + +#### 5.1.2 visibility:可见性属性 + +附加质量属性只保留 `visibility`,存放在对应模态或标注集内,不设 quality 目录。同一份可见性仅存一次;uv 与 xyz 共用时引用同一个文件。 + +visibility 通过所属组件 attributes 登记 data_ref、axes、dtype、visibility_type、meaning、provenance、source_locator;未知值通过属性 valid_ref 标识,全已知可声明 valid=true。比例与布尔值不相互强转,也不按任意阈值二值化。没有 MANO 时,整手可见性挂在 keypoints 组件,使用独立的 whole_hand_visibility.pt,明确 meaning=whole_hand,不与逐关键点可见性混用。 + +`valid` 回答“这项标注能否用于监督”,`visibility` 回答“在当前图像中是否可见(或可见多少)”。不可见的手或关键点仍可有有效标注;不能因 visibility=0 就清空坐标。源没有 visibility 时缺省或标为未知,不由 valid 推断。 + +| 情况 | 手标注 valid | visibility | +|---|---|---| +| RGB 已开始录制,动捕尚未开始,没有其他对应手标注 | false | 以独立源可见性标注为准;没有则未知 | +| 手被遮挡,但源有标注且通过适用有效性检查 | true | 若源声明不可见,则 false 或源可见比例 | +| 手可见且有对应标注,通过适用 QA | true | 若源有此信息,则 true 或源可见比例 | +| 手可见,但该帧漏标或动捕中断 | false | 可以为 true,但必须有独立来源依据 | +| 有手部参数,但官方 QA 明确不通过 | false | 不据此断言不可见;源可见比例若基于不可靠位姿,其属性 valid 也为 false | + +visibility 自己的 valid_ref 表示该可见性标注是否可用,不复用 MANO 或关键点坐标的 valid_ref;明确记录源存在性及适用的 QA 条件。上述例子不要求凭图像自动生成可见性。 + +不设 quality 组件或目录,不另存拟合误差、曝光、截断比例等通用质量数组。适用的官方 QA 合并进对应 valid,在 `valid_policy` 记录来源与规则;正式校验报告保留原始 QA 时间区间及排除统计。原始 QA 文件仍在 raw,官方 split 保留。 + +### 5.2 mano:参数与整手可见性 + +MANO schema `mano/axis_angle61/v1`:`motion.pt [T,2,61]`,顺序为完整 16 关节 axis-angle 48、shape betas 10、全局平移 3。姿态使用弧度,平移米,位于当前相机系。有效性 `[T,2]`;缺少一侧整槽 NaN。PCA 必须先按对应模型展开,不能将 PCA 系数直接填入 axis-angle。 + +`model_profile` 必须固定 MANO 版本、`flat_hand_mean=true`、左手 shapedirs 修正状态。平移表示模型输出顶点所加的全局平移,不是某个腕关节的坐标;源语义不同须转换。shape 无量纲。模型权重不作为共享数据附带上传。 + +`mano/visibility.pt [T,2]` 保存源整手可见比例时使用 float32 [0,1],`visibility_type=ratio`;只有实际采用 0–100 的百分比才除以100,不能只凭表头判断。HOT3D 的 `visibility_ratio[%]` 实值已经是0–1,官方读取器原样读取,必须保留原值。通过 MANO 组件 attributes 登记,使用独立有效性,不复用 motion_valid。 + +手部共享表示仅保留 MANO 参数与选定关键点,不发布独立手表面几何。需要渲染或接触计算时由 MANO 参数生成,几何引用使用固定 MANO 模型配置与顶点顺序;不影响 object 下的物体模型和材质资产。 + +### 5.3 keypoints:二维点、三维点与逐点可见性 + +关键点独立于 MANO 参数存在;没有 motion 也可有关键点。`uv.pt [T,2,K,2]` 与 `xyz.pt [T,2,K,3]`,有效性 `[T,2,K]`,分别采用 `keypoints/uv/v1` 和 `keypoints/xyz/v1`。K 由 `keypoint_schema` 固定,不能在同一数组中逐帧变化;同体系统一顺序。数值使用像素坐标或米制相机系。 + +| keypoint_schema | K 与固定索引 | +|---|---| +| mano21/v1 | 21;wrist 后依次 thumb/index/middle/ring/little,每指由近端至指尖 | +| rhd21/v1 | 21;保持 wrist,然后五指由近端至指尖;原始每指 tip→palm 反序。只统一顺序,不宣称解剖学位置等价于 MANO | + +具体名称与源索引映射见 `schema.json`。当前只登记 MANO21 与 RHD21;不登记 MediaPipe、ReInterHand capture21 或 fit24 中间关键点。 + +每个发布中的每个视图只提供一套标准手关键点,直接放在 keypoints 下,不设 annotation_set_id 字段或目录。uv 与 xyz 是这套关键点的二维与三维表示,不是两套标注。provenance 分别记录二者来自原始标注还是计算结果;不要求已有 2D 必须由当前 xyz 重新投影覆盖。 + +ReInterHand 的 Original keypoints、Original fits keypoints 及带前臂关键点不纳入 shared;如需手关键点,从选定 MANO 参数生成 MANO21 并记录模型/指尖回归约定。其他数据集默认使用选定的官方关键点,不额外生成平行的 MANO 派生集合。后续主动更换生成方法或结果时发布新的 dataset_version,不在同一版本内增设方法分支。 + +manual/projection/fitting 只记录在 provenance,不作为目录或类型分支。不得通过坐标为零、是否出画或 visibility 判断标注是否存在。派生标注仅在实际生成并通过数值检查后声明 valid=true;没有生成的项为 false,不伪造坐标。 + +`keypoints/visibility.pt [T,2,K]` 保存源逐点可见性,布尔表示使用 `visibility_type=boolean`。uv 与 xyz 共用时引用同一份文件。整手比例属性没有 MANO 可挂载时使用 `whole_hand_visibility.pt [T,2]`,`meaning=whole_hand`;它与逐点可见性分开,通用登记规则见 5.1。 + +不使用 annotation_set_id;ReInterHand 中间关键点集合不进入 shared,raw 保留来源文件。 + +### 5.4 object:身份、资产、位姿与几何 + +#### 5.4.1 metainfo.json:物体身份与跟踪作用域 + +手用 `hand_left`、`hand_right` 及槽位 0、1 表示,不再另存 entities.json。物体身份登记在 `annotation/object//metainfo.json`,必填 `object_id`、`identity_scope`、`scope_id`、`source_locator`;可含 `category_id`、`source_object_id`、`mesh_ref`、`has_model`、部件引用。即使只有分割、没有 pose/mesh,也可只有这份物体元信息。 + +`identity_scope` 为 frame/subsequence/sequence,`scope_id` 指定具体作用域;跨相机共享身份只在已有源对应证据时使用。VISOR 按官方 subsequence 与实体名关联时记录 `association_basis=official_subsequence_entity_name`,不能声称这是全视频物理实例跟踪。无需与 object_id 一一对应的标准 track_id;官方独立轨迹标识存在时保留为 source_track_id,并声明作用域。手槽不证明跨采集片段的个人身份。 + +#### 5.4.2 assets:网格、材质与纹理 + +资产属于物体,统一存放在 `annotation/object//` 内,可用 `assets/` 子目录组织网格、材质、纹理和部件资产。序列层不设共享 assets。所有引用采用视图根目录为基准;其中物体资产组件的 `data_ref` 与部件的 `mesh_ref` 采用相对于当前视图目录的 POSIX 路径,例如 `annotation/object/cup_01/assets/cup.obj`,且必须指向所属物体目录内的资产。OBJ 内部的材质、纹理引用遵循文件格式自身的相对路径规则,依赖文件一并保留。不同相机视图允许各自保存物体资产,不要求跨视图去重;下载物体时包含其资产依赖。 + +网格 schema 为 `mesh/obj/v1`,顶点米制,静态有效性可直接声明标量 `valid`,或通过 `valid_ref` 指向标量 bool Tensor;不按 T 重复静态资产。由物体/部件通过引用关联,不仅凭文件名猜测。 + +#### 5.4.3 pose.pt、pose_valid.pt 与 visibility.pt + +刚体 schema 为 `object/rigid/v1`,`pose.pt [T,4,4]` 固定为 `T_camera_from_object`,平移米制,有效性 `[T]`。物体坐标原点、轴向必须与 mesh 一致;旋转块为正交矩阵且 determinant≈1。 + +`object//visibility.pt [T]` 保存源物体可见比例,float32 [0,1],`visibility_type=ratio`。通过所属物体组件 attributes 登记,独立表达其有效性。 + +#### 5.4.4 articulation.json、部件位姿与 joint_state.pt + +关节物体:schema `object/articulated/v1`,`articulation.json` 登记 `parts` 与 `joints`。每个 part 有 `part_id`、`parent_id`(根为 null)、`has_model`、`mesh_ref`;has_model=false 时 mesh_ref=null,结构节点允许没有网格。父链不得成环。每个 joint 有唯一 `joint_id`、`parent_part`、`child_part`、`type`;fixed 单位 null、revolute 弧度、prismatic 米。有源限位时保存 `limits:[lower,upper]`;没有时 null,不伪造上下限。部件姿态统一为 `T_camera_from_part [T,4,4]`,不与父局部变换混装。 + +若提供 `joint_state.pt [T,J]`,必须登记固定 joint_order、轴在父部件系的表达、零位变换与正方向,valid 为 `[T,J]`;缺少这些运动学定义时只发布部件位姿与已有来源信息,不伪造可驱动的关节模型。关节值与部件位姿同时存在时需验证一致性。 + +部件层级应声明语义:纯语义包含树允许 `joints=[]`,不将包含关系推断为机械关节。关节状态 schema 为 `object/joint_state/v1`;转动用弧度、移动用米,混合类型按 joint_order 对应的关节定义解释。 + +#### 5.4.5 dimensions、几何关键点与顶点部件标签 + +`dimensions.pt [T,3]` 采用 `object/dimensions/v1`,有效性为 `[T]`。 + +物体/部件 `dimensions` 为 `[length,width,height]` 米,轴顺序与该 mesh 的局部坐标关联,登记 `dimensions_semantics` 和来源。HOI4D dimensions 与 mesh 的具体尺度关系未验证前标为 source_unspecified,保留源值并暂停依赖该关系的几何验收,不能默认为待施加缩放。需要施加缩放时明确 scale_applied_to_mesh,禁止重复应用。 + +源物体关键点放 `object//keypoints/xyz.pt [T,K,3]`(相机系)或 `template_xyz.pt [K,3]`(物体系),schema 分别为 object_keypoints/camera/v1 和 object_keypoints/template/v1。明确 keypoint_schema、keypoint_names、单位及有效性;模板点配合 pose 可投影,无须重复生成全部帧。H2O 中心/角点/棱中点,以及 ARCTIC 部件点分别登记具体源顺序,不套用手的 21 点 schema。每个发布选择一套源几何点并记录选择,不另建方法分支。 + +`vertex_part_ids.pt [V] int64` 绑定 `mesh_ref` 与 topology_id,登记整数到 part_id 的映射;未知用 -1。ARCTIC 不同拓扑的资产分别绑定,不能共用未经转换的顶点标签。部件层级中 is_instance/has_model 等源属性保留,几何文件仍全部归 object。 + +### 5.5 segment:分割类别、编码与覆盖范围 + +每个发布选择一套任务使用的分割表示,不建立方法/标注集分支。没有分割就不创建 segment 目录,不为其他模态创建空的实体表。 + +| schema_id | 文件与数值语义 | +|---|---| +| segment/uint16_labels/v1 | mask.mkv;整数区域编号,通过 instances.jsonl 解释 | +| segment/instance_polygons/v1 | polygons.jsonl;实例多边形,可重叠;当前不支持孔洞拓扑 | +| segment/foreground_intensity/v1 | mask.mkv;0–255 前景强度,不是区域编号或经过校准的概率 | + +#### 5.5.1 uint16 标签图与 instances.jsonl + +组件声明 `segmentation_type=semantic/instance/part`;同一组件固定一种类型。`mask.mkv` 解码为 `[T,H,W] uint16`,schema `segment/uint16_labels/v1`,使用 `mkv/uint16_ffv1/v1`,FFV1 gray16le 无损;只有所有区域编码均 ≤255 时允许 gray8(pixel_format=gray),读取后转 uint16,数值不变。禁止调色板和有损编码。有效性 `[T]`,表示该帧有可用分割标注。数值 0 固定为 unassigned,65535 固定为 ignore,1–65534 为区域编码,不能直接等同 entity_id。 + +`instances.jsonl` 每帧一行,包含 `frame_index` 与 `labels`。每条标签包含 `mask_value`、`category_id`、`entity_id`、`part_id`;无意义或未知字段为 null。semantic 允许 entity_id=null;instance 必须引用 hand_left/hand_right 或登记的 object_id;part 还须关联登记部件。源实例 ID 和其他属性分别保存在 `source_instance_id`、`source_attributes`。mask 中每个非保留编码必须有且仅有一个映射。 + +FreiHAND 的试点按本任务需要,统一到手/背景类别,保留每个原生区域编码;不要求给原生细分区域猜测手指名称。需要细部件监督时,尚未核实的部件名称必须保持未知,不能因粗粒度手类别已核实便声称部件语义也已统一。 + +#### 5.5.2 重叠实例多边形 + +每发布选择一套任务使用的分割表示,不建立方法/标注集分支。VISOR 的实际试点存在重叠实例多边形,单层标签图不能无损表达。对此补充 `segment/instance_polygons/v1`:`segment/polygons.jsonl` 每帧包含 `frame_index` 和 `instances`,每实例包含 `mask_value` 与 `polygons`(列表,每个多边形为源图像像素坐标顶点序列,保留原始精度)。身份和类别仍由同一 `instances.jsonl` 映射,有效性仍为 `[T]`,通过 schema 区分物理编码。允许多实例重叠,不采用后画覆盖前画。消费者按需栅格化为独立实例二值 mask;不能声称合并的单层 mask 无损。 + +#### 5.5.3 灰度前景强度 + +ReInterHand 的官方渲染 mask 为双手合并的灰度前景掩码,实测存在 0–255 的中间值,不是左右手实例编号。登记 `segment/foreground_intensity/v1`:仍存 `segment/mask.mkv`,解码为 `[T,H,W] uint16`,使用 `mkv/uint16_ffv1/v1`,此类数据优先编码为 FFV1 gray8(pixel_format=gray),读取后转 uint16。有效值范围 0–255,归一化值为 `float32(value)/255`;0 为背景端点、255 为前景端点。组件声明 `foreground_category=hand`、`entity_id=null` 和双手合并语义,不使用区域编号映射。这里保留原始渲染 mask 强度,不把它称为经过校准的概率。若任务需要二值 mask,阈值化属于任务层派生操作,记录阈值;共享层不丢弃中间灰度。不同 schema 的数值含义不同,不能将该文件按整数类别图解码。 + +FreiHAND 训练集的 JPEG mask 使用 `segment/foreground_intensity/v1`,逐像素保留 JPEG 解码后的灰度,`entity_id=hand_right`。该 schema 不限定双手合并:单手或合并范围由 `entity_id` 与 `coverage` 明确声明。评估集整数区域图仍用 `segment/uint16_labels/v1`,两者不能仅凭文件名使用同一种解码语义。 + +#### 5.5.4 coverage 与有效性 + +`coverage.kind=full/selected_entities/partial/unknown`。full 指声明的标注范围完整;selected_entities 还应列出目标范围。无论哪种,0 本身不自动成为背景;背景要有明确类别映射,未标注区域不能用于构造负样本。保留源逐类/逐实例 exhaustive 信息,未知不可改写为完整。 + +三种表示的帧级有效性均为 `[T]`,表示该帧是否提供此分割标注;对应 valid_ref 在组件中登记,仍用小型 bool `.pt` 数组。栅格 mask 必须登记 storage,格式见 3.1.2,所有帧的整数编码或强度逐值完全相同。编码语义由 schema_id 决定,读取器不能仅依据 mask.mkv 文件名选择解码方式。 + +### 5.6 contact:接触、抓取、区域与距离 + +#### 5.6.1 relations.jsonl 与 relations_valid.pt + +`annotation/contact/relations.jsonl`,schema contact/relations/v1,每帧一行含 frame_index、relations。每条记录含 relation_type(contact/grasp)、subject_id(手槽或登记实体)、object_id、status、source_locator、provenance。status 固定为 positive/negative/unknown/target_unannotated:positive 必须有可解析目标,negative 表示源明确否定该关系,unknown 为不确定,target_unannotated 为确有接触但目标未标注。非 positive 的 object_id 可 null,不能用 null 冒充“不接触”。稀疏源无记录的帧不自动补 negative。 + +VISOR 的对象 mask ID 必须先按同帧 source_instance_id 解析成 object_id;hand-not-in-contact、none-of-the-above、inconclusive 分别映射 negative、target_unannotated、unknown,保留原始字符串。Dex ycb_grasp_ind 通过 ycb_ids 映射到登记物体,以 relation_type=grasp 保存;不得当作逐顶点接触。 + +relations 组件的 valid_ref 指向 `relations_valid.pt [T] bool`,表示该帧是否有可用源关系标注。有效帧中可以存在 status=unknown 的明确不确定标注;无源标注的帧为 valid=false、relations=[]。组件仍声明 available/provenance/source_locator。 + +#### 5.6.2 实体对的顶点区域与距离 + +已发布的接触区域/距离按参与关系的 subject_id 与 object_id 组织,每对实体保留选定的一套结果,以精确 geometry_ref/topology_id 关联到手或物体/部件;不要求每套数据都有。顶点区域 schema contact/vertex_region/v1:bool `[T,V]` 加同形 valid;顶点距离 schema contact/vertex_distance/v1:float32 `[T,V]`、米、同形 valid,声明 source/target geometry_ref、distance_definition(signed/unsigned、测量到点集或表面等明确源定义)。geometry_ref 必须指向已登记 mesh 或由固定 MANO 模型配置确定的拓扑;拓扑/顶点数变化时按拓扑拆分片段。其他源区域表示只有在实际接入并登记 schema 后才可转换,不能随意栅格化宣称等价。 + +顶点区域/距离已有存储定义,但尚未完成真实输入试点;接入时必须提供源语义与几何验收证据,不因已经登记 schema 就视为通过。 + +## 附录:任务范围 + +不强制收录 2D bbox、完整高频动捕、动作程序、身体 SMPL-X、点云或网络特征。范围内的接触、visibility、选定手关键点、物体几何不能因不便处理而静默丢弃。分割采用的物理编码由第 5.5 节决定,存在重叠时不能以单层标签图声称无损。 + +不设置 entities_ref/segment/entities.json,不要求与 object_id 重复的 track_id。MediaPipe 不在当前关键点定义中;旧版本迁移必须保留可追溯关系,不能直接删表。手部共享表示不含独立 hand_mesh。 + +schema.json 是普通注册表,不是 JSON Schema 文档或可执行验收器;定义存在不代表真实数据已验证。验收须保留实测范围与未决项。 + +本存储约定只更新标准,不代表既有 FFV1/depth.pt 试点已迁移。新发布必须显式写 storage 配置;旧产物按其旧定义读取,不能只改文件后缀或版本标识伪装为合规。 diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/doc/schema.json b/H2O/shared-v1.1/script/v1_0_snapshot/doc/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..d904a34272de7f3fd4428c8dc68a919e94a68fca --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/doc/schema.json @@ -0,0 +1,869 @@ +{ + "schema_version": "hand-warehouse/1.0", + "validity_revision": "usable-annotation-2026-09-20", + "annotation_validity": { + "meaning": "annotation usable for supervision, not merely record presence", + "formula": "source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass AND NOT explicitly_reviewed_local_exclusion", + "without_official_qa": "omit QA term; declare source rules; do not fabricate QA", + "policy_field": "components..valid_policy", + "visibility_is_independent": true, + "invalid_float_value": "NaN", + "hot3d": "broadcast per-camera frame manual QA conservatively to hand/object labels and pose-derived visibility; retain RGB and source calibration; keep native QA in raw and review report", + "hot3d_visibility": "native visibility_ratio[%] already ranges from 0 to 1; do not divide by 100" + }, + "hand_slots": [ + "left", + "right" + ], + "keypoints": { + "mano21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map": null, + "note": "adapter maps official MANO joint and fingertip convention" + }, + "rhd21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map_per_hand": [ + 0, + 4, + 3, + 2, + 1, + 8, + 7, + 6, + 5, + 12, + 11, + 10, + 9, + 16, + 15, + 14, + 13, + 20, + 19, + 18, + 17 + ] + } + }, + "camera": { + "opencv_fisheye4": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "k3", + "k4" + ], + "projection": "theta=atan(r); theta_d=theta*(1+k1*theta^2+k2*theta^4+k3*theta^6+k4*theta^8); source ReInterHand" + }, + "pinhole": { + "K": [ + 3, + 3 + ] + }, + "fisheye624": { + "parameters": [ + "f", + "cx", + "cy", + "k0", + "k1", + "k2", + "k3", + "k4", + "k5", + "p0", + "p1", + "s0", + "s1", + "s2", + "s3" + ] + }, + "rational8": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "p1", + "p2", + "k3", + "k4", + "k5", + "k6" + ] + } + }, + "segmentation": { + "segment/uint16_labels/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "polygons.jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "note": "Registry for hand-warehouse/1.0. Read CONTRACT.md for field semantics. This is not a JSON Schema document or executable validator.", + "components": { + "mano/axis_angle61/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 61 + ], + "valid_shape": [ + "T", + 2 + ], + "unit": "m", + "angle_unit": "rad", + "coordinate_frame": "camera", + "layout": { + "pose_axis_angle": [ + 0, + 48 + ], + "shape": [ + 48, + 58 + ], + "translation": [ + 58, + 61 + ] + } + }, + "keypoints/uv/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 2 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "pixel", + "required_metadata": [ + "keypoint_schema" + ] + }, + "keypoints/xyz/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 3 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "m", + "required_metadata": [ + "keypoint_schema" + ] + }, + "depth/z_float32/v1": { + "storage": "mkv", + "dtype": "float32", + "shape": [ + "T", + "H", + "W" + ], + "valid_shape": [ + "T", + "H", + "W" + ], + "unit": "m", + "depth_type": "z", + "pixel_grid": "current_rgb", + "coordinate_frame": "current_rgb_camera", + "valid_storage": "mkv", + "allowed_storage_profiles": [ + "mkv/depth_float32_bits/v1" + ], + "allowed_valid_storage_profiles": [ + "mkv/bool_ffv1/v1" + ], + "required_metadata": [ + "storage", + "valid_storage", + "depth_origin" + ], + "depth_origin_values": [ + "measured", + "rendered", + "unknown" + ] + }, + "transform/se3/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention" + ] + }, + "object/rigid/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention" + ] + }, + "camera/pinhole/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/rational8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/opencv_fisheye4/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/fisheye624/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 15 + ], + "valid_shape": [ + "T" + ] + }, + "camera/distortion8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 8 + ], + "valid_shape": [ + "T" + ] + }, + "camera/fisheye4_distortion/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4 + ], + "valid_shape": [ + "T" + ] + }, + "object/joint_state/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "J" + ], + "valid_shape": [ + "T", + "J" + ], + "required_metadata": [ + "joint_order" + ], + "unit_rule": "revolute radians; prismatic metres; mixed types declared per joint" + }, + "object_keypoints/camera/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "K", + 3 + ], + "valid_shape": [ + "T", + "K" + ], + "unit": "m", + "coordinate_frame": "camera", + "required_metadata": [ + "keypoint_schema" + ] + }, + "object/dimensions/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "dimensions_semantics" + ], + "axis_order": [ + "length", + "width", + "height" + ], + "scale_rule": "do not apply to mesh without source-supported size/scale relation" + }, + "object_keypoints/template/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "K", + 3 + ], + "valid_shape": [ + "K" + ], + "unit": "m", + "coordinate_frame": "object", + "static": true, + "required_metadata": [ + "keypoint_schema" + ] + }, + "mesh/obj/v1": { + "storage": "obj", + "unit": "m", + "static": true, + "valid_shape": [], + "dependencies": "MTL and textures retained under owning object" + }, + "rgb/uint8/v1": { + "storage": "mkv", + "dtype": "uint8", + "shape": [ + "T", + "H", + "W", + 3 + ], + "valid_shape": [ + "T" + ], + "color_order": "RGB", + "allowed_storage_profiles": [ + "mkv/mjpeg_copy/v1", + "mkv/source_copy/v1", + "mkv/h264_rgb_lossless/v1", + "mkv/ffv1_rgb/v1" + ], + "required_metadata": [ + "storage" + ] + }, + "contact/relations/v1": { + "storage": "jsonl", + "valid_shape": [ + "T" + ], + "frame_keys": [ + "frame_index", + "relations" + ], + "absence_semantics": "no record is not a negative contact annotation" + }, + "contact/vertex_region/v1": { + "storage": "pt", + "dtype": "bool", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id" + ], + "pilot_status": "defined_not_empirically_validated" + }, + "contact/vertex_distance/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "unit": "m", + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id", + "distance_definition" + ], + "pilot_status": "defined_not_empirically_validated" + }, + "object/articulated/v1": { + "storage": "json", + "required_keys": [ + "parts", + "joints" + ], + "part_keys": [ + "part_id", + "parent_id", + "has_model", + "mesh_ref" + ], + "hierarchy_semantics": "declare mechanical articulation or semantic containment; containment alone does not imply joints", + "acyclic": true + }, + "segment/uint16_labels/v1": { + "storage": "mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "storage_revision": "lossless-video-2026-09-18", + "sampling": { + "image": { + "single": { + "T": 1 + }, + "independent": { + "T": ">=2", + "required_frame_fields": [ + "sample_id", + "source_locator" + ], + "temporal_relationship": false + }, + "source_fps": null + }, + "video": { + "sampling_types": [ + "dense", + "sparse" + ] + } + }, + "storage_profiles": { + "mkv/mjpeg_copy/v1": { + "container": "matroska", + "codec": "mjpeg", + "method": "stream_copy_from_source_jpeg", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "source_jpeg_packet_sha256_exact", + "all_packet_count_order_and_dimensions_exact", + "deterministic_decoded_rgb_sample_exact", + "pilot_and_final_selected_whole_sequences_decoded_rgb_exact" + ], + "validation_policy": { + "id": "jpeg-packets-all-rgb-sample16/v1", + "sample_count_per_view": 16, + "short_views": "all_frames_if_T_less_than_16", + "fixed_indices": "0,T-1,T//4,T//2,3*T//4, deduplicated", + "remaining_indices": "sample without replacement to min(T,16) using Python random.Random(seed)", + "seed": "first 8 bytes of SHA256(sequence_id/camera_id/20260920), big-endian integer", + "report": "policy, exact selected frame indices, seed, separate packet and pixel coverage", + "legacy_all_frame_pixel_proofs": "still accepted; preserve historical evidence" + } + }, + "mkv/source_copy/v1": { + "container": "matroska", + "codec": "source_codec_declared_in_metadata", + "method": "stream_copy_only", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "no_reencoding", + "all_decoded_rgb_frames_exact", + "presentation_frame_order_exact" + ] + }, + "mkv/h264_rgb_lossless/v1": { + "container": "matroska", + "codec": "h264", + "encoder": "libx264rgb", + "crf": 0, + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "gop": "declared_in_encoder_parameters", + "validation": [ + "all_decoded_rgb_frames_exact" + ], + "forbidden": [ + "lossy_rate_control", + "rgb_to_yuv420_subsampling" + ] + }, + "mkv/ffv1_rgb/v1": { + "container": "matroska", + "codec": "ffv1", + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "validation": [ + "all_decoded_rgb_frames_exact" + ] + }, + "mkv/depth_float32_bits/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray16le", + "logical_dtype": "float32", + "logical_shape": [ + "T", + "H", + "W" + ], + "encoded_shape": [ + "T", + "H", + "2*W" + ], + "packing": "IEEE754 little-endian float32 bits; low uint16 in first W columns, high uint16 in last W columns", + "decode": "reinterpret_float32(uint32(low) | (uint32(high) << 16))", + "validation": [ + "all_float32_bits_exact_including_nan" + ] + }, + "mkv/bool_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray", + "logical_dtype": "bool", + "stored_values": [ + 0, + 1 + ], + "validation": [ + "all_bool_values_exact" + ] + }, + "mkv/uint16_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_formats": [ + "gray", + "gray16le" + ], + "logical_dtype": "uint16", + "gray_condition": "all values <=255; decode by exact uint8-to-uint16 promotion", + "validation": [ + "all_integer_values_exact" + ] + } + }, + "video_metadata": { + "required": [ + "profile", + "codec", + "pixel_format", + "encoded_size", + "decoder", + "encoder_parameters", + "source_lossy" + ], + "source_lossy_values": [ + true, + false, + "unknown" + ], + "timebase_role": "index_only", + "lossless_reference": "source compressed packets or fixed-decoder source pixels; depth uses normalized standard float32 bits", + "selection": "choose smaller complete candidate only after exact roundtrip validation" + } +} diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/check_dexycb_projection.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/check_dexycb_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..2774c004fc1359dea582135ec7171f600b33b336 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/check_dexycb_projection.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Check saved Dex-YCB source 3D joints against saved source 2D joints in sampled views.""" +import json +from pathlib import Path +import sys + +import numpy as np +import torch + +root = Path(sys.argv[1]) +report = json.loads((root / 'doc/validation/STRUCTURAL_AUDIT.json').read_text()) +checks = [] +for name in report['sampled_views']: + view = root / name + load = lambda path: torch.load(view / path, weights_only=True, map_location='cpu').numpy() + k = load('camera/intrinsic.pt') + xyz = load('annotation/keypoints/xyz.pt') + uv = load('annotation/keypoints/uv.pt') + valid = load('annotation/keypoints/xyz_valid.pt') & load('annotation/keypoints/uv_valid.pt') + z = xyz[..., 2] + valid &= np.isfinite(xyz).all(axis=-1) & np.isfinite(uv).all(axis=-1) & (z > 0) + z = np.where(valid, z, 1) + pred = np.stack((k[:, 0, 0, None, None] * xyz[..., 0] / z + k[:, 0, 2, None, None], + k[:, 1, 1, None, None] * xyz[..., 1] / z + k[:, 1, 2, None, None]), axis=-1) + errors = np.linalg.norm(pred[valid] - uv[valid], axis=-1) + checks.append(dict(view=name, points=int(errors.size), median_px=float(np.median(errors)) if errors.size else None, + p95_px=float(np.percentile(errors, 95)) if errors.size else None)) +(root / 'doc/validation/KEYPOINT_PROJECTION_QC.json').write_text(json.dumps({ + 'scope': 'Saved source 3D joints projected with saved color intrinsics vs saved source 2D joints; independent of hand mesh rendering.', + 'views': checks}, ensure_ascii=False, indent=2) + '\n') +print(json.dumps(checks, ensure_ascii=False), flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/config.json b/H2O/shared-v1.1/script/v1_0_snapshot/script/config.json new file mode 100644 index 0000000000000000000000000000000000000000..36d77ffb8ae7c4d8db5364324fac347a35522f99 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/config.json @@ -0,0 +1,24 @@ +{ + "root": "/home/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O", + "out": "/home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe", + "release_id": "shared-v1.0", + "limit": null, + "max_frames": null, + "mano_dir": "/home/xuzhefeng/Projects/WiLoR/mano_data", + "views": null, + "jpeg_full_check": false, + "workers": 4, + "view_backend": "processes", + "camera_pipeline": true, + "ffv1_slices": 16, + "view_workers": 16, + "ram_stage_dir": "/dev/shm/xuzhefeng-h2o-full-process16-20260930", + "ram_stage_gib": 32, + "stream_media": true, + "codec_threads": 10, + "decode_threads": 10, + "depth_threads": 4, + "subjects": null, + "include_casa": false, + "archive": null +} diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/convert_dexycb_v1.0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/convert_dexycb_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..ed3f479787fae378b3d3b51ce2f58ccaebfd3d0f --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/convert_dexycb_v1.0.py @@ -0,0 +1,349 @@ +#!/usr/bin/env python3 +"""Dex-YCB source annotations → CONTRACT.md v1.0. No derived annotations.""" +import io +import re +import shutil +import tarfile +import tempfile +from pathlib import Path + +import numpy as np +from PIL import Image +import yaml + +from warehouse_v1_0 import (View, build_record, find_file, locator, mano_models, mesh_asset, + model_profile, parser, pca_to_axis_angle, release, roots, safe_member, sequence_dir) + +IMG_W, IMG_H = 640, 480 + +class _Loader(yaml.SafeLoader): + pass + + +_Loader.add_constructor("tag:yaml.org,2002:python/tuple", + lambda l, n: tuple(l.construct_sequence(n))) + + +def yaml_load_bytes(data: bytes): + return yaml.load(io.BytesIO(data), Loader=_Loader) + + +class Calibration: + def __init__(self, dexycb_root: Path): + self.intrinsics = {} # serial -> {fx,fy,cx,cy,w,h} + self.extrinsics = {} # group -> {serial: [12] 行优先 3×4 cam→world} + self.betas = {} # mano_calib_name -> [10] + calib_dir = dexycb_root / "calibration" + if calib_dir.is_dir(): + self._load((p.as_posix(), p.read_bytes()) + for p in sorted(calib_dir.rglob("*")) if p.is_file()) + else: + tar_path = dexycb_root / "calibration.tar.gz" + if not tar_path.exists(): + raise FileNotFoundError(f"no calibration/ nor calibration.tar.gz in {dexycb_root}") + with tarfile.open(tar_path, "r:gz") as tf: + self._load((m.name, tf.extractfile(m).read()) for m in tf if m.isfile()) + + _RE_INTR = re.compile(r"(?:^|/)intrinsics/(\d+)_\d+x\d+\.yml$") + _RE_EXTRA = re.compile(r"(?:^|/)extrinsics_(\d{8}_\d{6})/extrinsics\.yml$") + _RE_MANO = re.compile(r"(?:^|/)mano_(\d{8}_\d{6}_subject-\d{2}_right)/mano\.yml$") + + def _load(self, files): + for rel, data in files: + m = self._RE_INTR.search(rel) + if m: + c = yaml_load_bytes(data)["color"] + self.intrinsics[m.group(1)] = {"fx": float(c["fx"]), "fy": float(c["fy"]), + "cx": float(c["ppx"]), "cy": float(c["ppy"]), + "w": IMG_W, "h": IMG_H} + continue + m = self._RE_EXTRA.search(rel) + if m: + raw = yaml_load_bytes(data)["extrinsics"] + self.extrinsics[m.group(1)] = { + str(s): [float(x) for x in np.asarray(v).ravel()] for s, v in raw.items()} + continue + m = self._RE_MANO.search(rel) + if m: + self.betas[m.group(1)] = [float(b) for b in yaml_load_bytes(data)["betas"]] + + + +def calibration_locator(path, member, **extra): + if path.is_dir(): + return locator(path / member.removeprefix('calibration/'), **extra) + return locator(path, member, **extra) + + +def prepare_models(root, destination): + archive = find_file(root, 'models.tar.gz') + if archive is None: + return {}, None + pattern = re.compile(r'^models/(\d{3}_[a-z0-9_]+)/(textured_simple\.obj(?:\.mtl)?|texture_map\.png)$') + names = set() + with tarfile.open(archive, 'r|gz') as tf: + for member in tf: + match = pattern.fullmatch(member.name) + if member.isfile() and match: + names.add(match[1]) + path = safe_member(destination, '/'.join(match.groups())) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(tf.extractfile(member).read()) + if len(names) != 21: + raise ValueError('expected all 21 source YCB model directories') + return {i: destination / name for i, name in enumerate(sorted(names), 1)}, archive + + +def convert_view(path, args, seq, serial, frames, meta, meta_loc, calib, calib_path, models, assets, asset_archive): + total = int(meta.get('num_frames', max(frames) + 1)) + ids = list(range(min(total, args.max_frames) if args.max_frames else total)) + for f in ids: + frames.setdefault(f, {}) + if not ids: + raise ValueError('no RGB frames') + source_rows = [] + for f in ids: + row = frames[f] + source_rows.append(dict(source_frame_id=f, sync_id=f'{seq}:{f}', + source_locator=row['color'][1] if 'color' in row else (meta_loc | {'source_frame_id': f, 'missing_rgb': True}), annotation_matches={ + 'labels': {'source_frame_id': f, 'source_timestamp_ns': None, 'clock_domain': None, + 'match_method': 'index_map', 'delta_ns': None, 'source_locator': row['labels'][1]} + for _ in [0] if 'labels' in row}, + component_sources={k: v[1] for k, v in row.items()})) + view = View(path, 'dex-ycb', args.release_id, seq, serial, source_rows, + sampling='dense' if ids == list(range(ids[0], ids[-1] + 1)) else 'sparse') + view.valid_rules = { + 'mano': 'Source pose_m present and not all zero; side model/calibration available', + 'keypoints': 'Corresponding joint_2d/joint_3d present; whole-hand all -1 is missing, broadcast to its 21 points', + 'pose': 'Source pose_y for this ycb_ids slot present and not an all-zero matrix', + 'segment': 'Source seg array provided for this frame; region codes and entity references validated', + 'relations': 'Source sequence ycb_grasp_ind resolves through ycb_ids; broadcast sequence grasp to selected frames', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'exo' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} + subject = re.search(r'subject-(\d+)', seq) + if subject and 1 <= int(subject[1]) <= 10: + index = int(subject[1]) + view.meta.update(split='val' if index == 7 else 'test' if index in (8, 9) else 'train', + split_scheme='Dex-YCB/s1', split_source_locator={ + 'url': 'https://github.com/NVlabs/dex-ycb-toolkit/blob/master/dex_ycb_toolkit/dex_ycb.py', + 'rule': 's1 unseen-subject: 01-06/10 train, 07 val, 08-09 test'}) + view.meta.pop('split_reason', None) + view.rgb([frames[f]['color'][0] if 'color' in frames[f] else None for f in ids], {'frames_ref': 'camera/frames.jsonl'}) + n = len(ids) + intr = calib.intrinsics.get(serial) + K = None if intr is None else np.array([[intr['fx'], 0, intr['cx']], [0, intr['fy'], intr['cy']], [0, 0, 1]]) + ext = calib.extrinsics.get(str(meta['extrinsics']), {}).get(serial) + E = None + if ext is not None: + E = np.eye(4) + E[:3] = np.asarray(ext).reshape(3, 4) + E = np.linalg.inv(E) + view.camera(K, calibration_locator(calib_path, f'calibration/intrinsics/{serial}_640x480.yml'), E, + calibration_locator(calib_path, f'calibration/extrinsics_{meta["extrinsics"]}/extrinsics.yml', + conversion='inverse of source T_world_from_camera')) + sides = meta.get('mano_sides') + if sides not in (['left'], ['right']): + raise ValueError(f'expected exactly one anatomical source hand: {sides}') + side = sides[0] + slot = ['left', 'right'].index(side) + cal_name = meta['mano_calib'][0] if isinstance(meta['mano_calib'], list) else meta['mano_calib'] + labels = [dict(np.load(frames[f]['labels'][0])) if 'labels' in frames[f] else {} for f in ids] + label_loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources.labels'} + motion = np.full((n, 2, 61), np.nan, np.float32) + mv = np.zeros((n, 2), bool) + if side in models and any('pose_m' in lab for lab in labels): + for i, lab in enumerate(labels): + if 'pose_m' not in lab: + continue + pose = np.asarray(lab['pose_m']).reshape(51) + if not np.any(pose): # Official Dex-YCB missing-pose sentinel, independent of joints/seg. + continue + motion[i, slot] = np.r_[pose[:3], pca_to_axis_angle(pose[3:48], models[side]), + calib.betas[cal_name], pose[48:51]] + mv[i, slot] = True + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], label_loc, model_profile=model_profile(models), + calibration_source=calibration_locator(calib_path, f'calibration/mano_{cal_name}/mano.yml'), + provenance={'kind': 'format_conversion', 'method': 'source PCA @ hands_components + hands_mean; explicit axis-angle consumed with flat_hand_mean=true'}) + elif any('pose_m' in lab for lab in labels): + view.absent('mano', 'Source PCA exists; provide --mano-dir to expand it', 'dependency_missing') + else: + view.absent('mano', 'No source pose_m field') + for source_key, key, dim, unit in [('joint_2d', 'uv', 2, 'pixel'), ('joint_3d', 'xyz', 3, 'm')]: + if not any(source_key in x for x in labels): + view.absent('keypoints_' + key, 'No source ' + source_key) + continue + points = np.full((n, 2, 21, dim), np.nan, np.float32) + valid = np.zeros((n, 2, 21), bool) + for i, lab in enumerate(labels): + if source_key not in lab: + continue + p = np.asarray(lab[source_key]).reshape(21, dim) + points[i, slot] = p + valid[i, slot] = not np.all(p == -1) # Official sentinel covers the whole source hand. + # An individual off-image point (-1, -1) is not evidence of missing annotation. + view.tensor('keypoints_' + key, f'keypoints/{key}/v1', f'annotation/keypoints/{key}.pt', + points, valid, ['T', 'hand', 'keypoint', 'coordinate'], label_loc, + keypoint_schema='mano21/v1', unit=unit) + ycb_ids = [int(x) for x in meta['ycb_ids']] + for j, oid in enumerate(ycb_ids): + entity = f'ycb_{oid:02d}' + view.object(entity, meta_loc, source_object_id=oid, category_id=oid) + poses = np.full((n, 4, 4), np.nan, np.float32) + valid = np.zeros(n, bool) + for i, lab in enumerate(labels): + if 'pose_y' in lab: + pose = np.asarray(lab['pose_y']) + if pose.shape != (len(ycb_ids), 3, 4): + raise ValueError('pose_y shape differs from ycb_ids') + if np.any(pose[j]): # Official all-zero missing object pose sentinel. + poses[i] = np.eye(4) + poses[i, :3] = pose[j] + valid[i] = True + if any('pose_y' in lab for lab in labels): + view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', + poses, valid, ['T', 'row', 'column'], label_loc, + convention='T_camera_from_object', unit='m') + else: + view.absent('pose_' + entity, 'No source pose_y field') + if oid in assets: + mesh_asset(view, entity, assets[oid], assets[oid] / 'textured_simple.obj', + locator(asset_archive, f'models/{assets[oid].name}/textured_simple.obj')) + else: + view.absent('mesh_' + entity, 'models.tar.gz unavailable', 'not_downloaded') + if any('seg' in lab for lab in labels): + mask_rows = [] + width, height = view.meta['camera']['image_size'] + for i, lab in enumerate(labels): + values = np.unique(lab.get('seg', np.zeros((height, width), np.uint8))) + mappings = [] + for value in values: + value = int(value) + if value == 0: + continue + if value != 255 and value not in ycb_ids: + raise ValueError(f'unknown Dex-YCB region value {value}') + mappings.append(dict(mask_value=value, category_id='hand' if value == 255 else value, + entity_id='hand_' + side if value == 255 else f'ycb_{value:02d}', part_id=None, + source_instance_id=value)) + mask_rows.append(dict(frame_index=i, labels=mappings)) + view.raster('segment', (lab.get('seg', np.zeros((height, width), np.uint16)) for lab in labels), + ['seg' in lab for lab in labels], label_loc, mask_rows) + view.meta['components']['segment'].update(coverage={'kind': 'selected_entities', + 'entities': ['hand_' + side] + [f'ycb_{o:02d}' for o in ycb_ids]}, source_zero_meaning='background') + else: + view.absent('segment', 'No source seg field') + if any('aligned_depth_to_color' in frames[f] for f in ids): + def depths(): + width, height = view.meta['camera']['image_size'] + for f in ids: + item = frames[f].get('aligned_depth_to_color') + if item is None: + yield np.full((height, width), np.nan, np.float32) + else: + with Image.open(item[0]) as im: + yield np.asarray(im).astype(np.float32) / 1000.0 + view.raster('depth', depths(), None, {'frames_ref': 'camera/frames.jsonl', + 'source_field': 'component_sources.aligned_depth_to_color', 'conversion': 'millimetres to metres'}) + else: + view.absent('depth', 'No source aligned_depth_to_color frames') + grasp = meta.get('ycb_grasp_ind') + if grasp is not None: + if not 0 <= int(grasp) < len(ycb_ids): + raise ValueError('invalid ycb_grasp_ind') + relation = dict(relation_type='grasp', subject_id='hand_' + side, + object_id=f'ycb_{ycb_ids[int(grasp)]:02d}', status='positive', source_locator=meta_loc, + provenance={'kind': 'source', 'method': 'sequence ycb_grasp_ind resolved through ycb_ids; not per-frame contact'}) + view.relations([{'frame_index': i, 'relations': [relation]} for i in range(n)], np.ones(n, bool), meta_loc) + else: + view.absent('relations', 'No source grasp/contact relation') + return view.finish() + + +MEMBER = re.compile(r'^([^/]+)/(\d{8}_\d{6})/(meta\.yml|(\d{12})/(color|labels|aligned_depth_to_color)_(\d+)\.(jpg|npz|png))$') + + +def convert_archive(archive, args, out, calib, calib_path, models, assets, asset_archive): + selected_views = set(args.views.split(',')) if args.views else None + done = 0 + current, meta, meta_loc, rows = None, None, None, {} + with tempfile.TemporaryDirectory(prefix='dex-source-') as wd: + work = Path(wd) + def flush(): + nonlocal done + if not rows: + return + seq = archive.name.split('.tar')[0] + '_' + current + reports = {} + with sequence_dir(out, seq) as target: + for serial, frames in sorted(rows.items()): + reports[serial] = convert_view(target / serial, args, seq, serial, frames, meta, + meta_loc, calib, calib_path, models, assets, asset_archive) + build_record(out, seq, reports) + for staged in list(work.iterdir()): + if staged.is_dir(): + shutil.rmtree(staged) + else: + staged.unlink() + done += 1 + print(f'Converted {seq}', flush=True) + with tarfile.open(archive, 'r|gz') as tf: + for member in tf: + match = MEMBER.fullmatch(member.name) + if not member.isfile() or not match: + continue + seq = match[2] + if seq != current: + flush() + if args.limit and done >= args.limit: + break + current, meta, meta_loc, rows = seq, None, None, {} + data_kind = match[3] + if data_kind == 'meta.yml': + data = tf.extractfile(member).read() + meta = yaml_load_bytes(data) + meta_loc = locator(archive, member.name, data) + continue + serial, kind, f = match[4], match[5], int(match[6]) + if selected_views and serial not in selected_views or args.max_frames and f >= args.max_frames: + continue + data = tf.extractfile(member).read() + dest = safe_member(work, member.name) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(data) + row = rows.setdefault(serial, {}).setdefault(f, {}) + if kind in row: + raise ValueError('duplicate archive frame') + row[kind] = (dest, locator(archive, member.name, data)) + else: + flush() + return done + + +def main(argv=None): + p = parser('dex-ycb', __doc__) + p.add_argument('--subjects') + args = p.parse_args(argv) + archives = sorted({a for r in roots(args.root) for a in r.glob('*-subject-*.tar.gz')}) + if args.subjects: + subjects = {s.strip().zfill(2) for s in args.subjects.split(',')} + archives = [a for a in archives if re.search(r'subject-(\d+)', a.name)[1] in subjects] + if not archives: + p.error('no Dex-YCB subject archives found') + cp = find_file(args.root, 'calibration.tar.gz') or find_file(args.root, 'calibration') + if cp is None: + p.error('calibration source missing') + calib = Calibration(cp.parent) + models = mano_models(args.mano_dir) + out = release(args, 'dex-ycb') + with tempfile.TemporaryDirectory(prefix='dex-models-') as wd: + assets, asset_archive = prepare_models(args.root, Path(wd)) + for archive in archives: + convert_archive(archive, args, out, calib, cp, models, assets, asset_archive) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/convert_h2o_v1.0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/convert_h2o_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..84c5878726db45a492347035386bf0f7ff30b8d6 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/convert_h2o_v1.0.py @@ -0,0 +1,678 @@ +#!/usr/bin/env python3 +"""H2O native RGB-D, MANO, joints and objects → CONTRACT.md v1.0 (no rendered masks).""" +from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor +import io +import json +import multiprocessing +import os +import re +import shutil +import tarfile +import tempfile +import threading +from pathlib import Path +import zipfile + +# Bound native libraries before loading NumPy/Torch; each worker still uses independent FFmpeg processes. +for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + +import numpy as np +from PIL import Image +import torch + +from warehouse_v1_0 import (View, build_record, check_mesh, find_file, locator, mano_models, mesh_asset, + model_profile, parser, release, roots, safe_member, sequence_dir, sha256) + +OBJECTS = {1: 'book', 2: 'espresso', 3: 'lotion', 4: 'spray', + 5: 'milk', 6: 'cocoa', 7: 'chips', 8: 'cappuccino'} +MEMBER = re.compile(r'^(?:h2o_CASA/)?(subject\d+)/([^/]+)/(\d+)/(cam\d)/(.+)$') +FRAME = re.compile(r'(rgb|depth|cam_pose|hand_pose|hand_pose_mano|obj_pose|obj_pose_rt)/(\d+)\.(png|jpg|txt)$') + + +def load_splits(root): + archive = find_file(root, 'label_split.zip') + result = {} + if archive is not None: + with zipfile.ZipFile(archive) as z: + for split in ('train', 'val', 'test'): + member = f'label_split/action_{split}.txt' + for line_no, line in enumerate(z.read(member).decode().splitlines(), 1): + fields = line.split() + if len(fields) < 2 or fields[1] == 'path': + continue + key = fields[1] + if key in result and result[key][0] != split: + raise ValueError('conflicting official splits') + result[key] = (split, locator(archive, member, record=line_no)) + return result + + +def load_assets(root, work): + archive = find_file(root, 'object.zip') + if archive is None: + return {}, None + with zipfile.ZipFile(archive) as z: + for member in z.infolist(): + if member.is_dir(): + continue + path = safe_member(work, member.filename) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(z.read(member)) + result = {} + for oid, name in OBJECTS.items(): + directory = work / 'object' / name + aliases = [] + # Source cocoa.obj -> ovomaltine.mtl -> cocoa.png, but the ZIP names the + # supplied texture ovomaltine.png. Keep all originals and add a byte-identical alias. + if name == 'cocoa' and not (directory / 'cocoa.png').exists(): + mtl = directory / 'ovomaltine.mtl' + if mtl.is_file() and 'map_Kd cocoa.png' in mtl.read_text().splitlines(): + texture = directory / 'ovomaltine.png' + shutil.copyfile(texture, directory / 'cocoa.png') + aliases.append({'file': 'cocoa.png', 'sha256': sha256(texture), + 'source': locator(archive, 'object/cocoa/ovomaltine.png')}) + candidates = list(directory.glob('*.obj')) + if len(candidates) != 1: + raise ValueError(f'expected one source OBJ for {name}') + check_mesh(candidates[0], directory) # Fail before decoding any large subject archive. + result[oid] = (directory, candidates[0], aliases) + return result, archive + + +def convert_view(path, args, seq, cam, rows, intr, splits, models, assets, asset_archive): + codec_threads = getattr(args, 'codec_threads', 1) + ids = list(range(min(rows), max(rows) + 1)) + for f in ids: + rows.setdefault(f, {}) + n = len(ids) + if not n: + raise ValueError('no RGB frames') + split, split_loc = splits.get(seq, ('unknown', None)) + frame_rows = [dict(source_frame_id=f, sync_id=f'{seq}:{f}', source_locator=rows[f]['rgb'][1] if 'rgb' in rows[f] else {'sequence': seq, 'camera': cam, 'source_frame_id': f, 'missing_rgb': True}, + component_sources={k: item[1] for k, item in rows[f].items()}, + annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None) + for k in rows[f] if k != 'rgb'}) for f in ids] + view = View(path, 'H2O', args.release_id, seq.replace('/', '_'), cam, frame_rows, split=split) + view.valid_rules = { + 'mano': 'Per-hand hand_pose_mano flag equals 1; corresponding side model available', + 'keypoints': "Per-hand hand_pose flag equals 1, broadcast to that hand's 21 source points independently of MANO", + 'pose': 'Source obj_pose_rt class equals this nonzero object class', + 'points': 'Source obj_pose class equals this nonzero object class, broadcast to its 21 points', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'ego' if cam == 'cam4' else 'exo' if cam in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} + if split_loc: + view.meta.update(split_scheme='official_action_split', split_source_locator=split_loc) + # In the measured 275 H2O views, exact FFV1 was always smaller than exact H.264. + view.rgb([rows[f]['rgb'][0] if 'rgb' in rows[f] else None for f in ids], + {'frames_ref': 'camera/frames.jsonl'}, ffv1_first=True, codec_threads=codec_threads, + stream_source=getattr(args, 'stream_media', False)) + loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} + if intr is not None: + fx, fy, cx, cy, width, height = np.loadtxt(io.BytesIO(intr[0])).ravel() + if [int(width), int(height)] != view.meta['camera']['image_size']: + raise ValueError('source intrinsics resolution mismatch') + K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) + view.camera(K, intr[1]) + camps = np.full((n, 4, 4), np.nan, np.float32) + cv = np.zeros(n, bool) + data = [] + for i, f in enumerate(ids): + lab = {k: np.loadtxt(io.BytesIO(item[0])).ravel() for k, item in rows[f].items() if k not in ('rgb', 'depth')} + data.append(lab) + if 'cam_pose' in lab: + camps[i] = np.linalg.inv(lab['cam_pose'].reshape(4, 4)) + cv[i] = True + if cv.any(): + view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', camps, cv, + ['T', 'row', 'column'], loc, convention='T_camera_from_world', + source_convention='T_world_from_camera') + motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) + points, pv = np.full((n, 2, 21, 3), np.nan, np.float32), np.zeros((n, 2, 21), bool) + object_ids = set() + for i, lab in enumerate(data): + if 'hand_pose_mano' in lab: + hands = lab['hand_pose_mano'].reshape(2, 62) + for side, row in enumerate(hands): + if row[0] not in (0, 1): + raise ValueError('unexpected H2O MANO presence flag') + if row[0] == 1: + motion[i, side] = np.r_[row[4:52], row[52:62], row[1:4]] + mv[i, side] = True + if 'hand_pose' in lab: + hands = lab['hand_pose'].reshape(2, 64) + for side, row in enumerate(hands): + if row[0] not in (0, 1): + raise ValueError('unexpected H2O keypoint presence flag') + if row[0] == 1: + points[i, side] = row[1:].reshape(21, 3) + pv[i, side] = True + for key in ('obj_pose', 'obj_pose_rt'): + if key in lab and lab[key][0] != 0: + object_ids.add(int(lab[key][0])) + if any('hand_pose_mano' in lab for lab in data): + if len(models) == 2: + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) + else: + view.absent('mano', 'Source parameters exist; --mano-dir must identify both model profiles', 'dependency_missing') + if any('hand_pose' in lab for lab in data): + view.tensor('keypoints_xyz', 'keypoints/xyz/v1', 'annotation/keypoints/xyz.pt', points, pv, + ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='m') + for oid in sorted(object_ids): + if oid not in OBJECTS: + raise ValueError(f'unknown H2O object class {oid}') + entity = OBJECTS[oid] + view.object(entity, loc, category_id=oid, source_object_id=oid) + poses, ov = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + pts, kv = np.full((n, 21, 3), np.nan, np.float32), np.zeros((n, 21), bool) + for i, lab in enumerate(data): + if 'obj_pose_rt' in lab and lab['obj_pose_rt'][0] == oid: + poses[i] = lab['obj_pose_rt'][1:].reshape(4, 4) + ov[i] = True + if 'obj_pose' in lab and lab['obj_pose'][0] == oid: + pts[i] = lab['obj_pose'][1:].reshape(21, 3) + kv[i] = True + if ov.any(): + view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', + poses, ov, ['T', 'row', 'column'], loc, convention='T_camera_from_object', unit='m') + if kv.any(): + view.tensor('points_' + entity, 'object_keypoints/camera/v1', + f'annotation/object/{entity}/keypoints/xyz.pt', pts, kv, + ['T', 'keypoint', 'coordinate'], loc, keypoint_schema='H2O_official_object21', + keypoint_names=['center'] + [f'corner_{i}' for i in range(8)] + [f'edge_midpoint_{i}' for i in range(12)], + source_order='official obj_point_order.jpg: center, 8 corners, 12 edge midpoints', unit='m') + if oid in assets: + directory, obj, aliases = assets[oid] + asset_loc = locator(asset_archive, f'object/{entity}/{obj.name}') + if aliases: + asset_loc['texture_aliases'] = aliases + mesh_asset(view, entity, directory, obj, asset_loc) + else: + view.absent('mesh_' + entity, 'Source object.zip unavailable', 'not_downloaded') + if any('depth' in rows[f] for f in ids): + width, height = view.meta['camera']['image_size'] + depth_threads = getattr(args, 'depth_threads', 1) + def read_depth(f): + item = rows[f].get('depth') + if item: + with Image.open(item[0]) as im: + return np.asarray(im).astype(np.float32) / 1000.0 + return np.full((height, width), np.nan, np.float32) + def depths(): + if depth_threads == 1: + yield from map(read_depth, ids) + else: + with ThreadPoolExecutor(max_workers=depth_threads) as pool: + # Ordered batches bound decoded arrays to depth_threads frames per view. + for start in range(0, len(ids), depth_threads): + yield from pool.map(read_depth, ids[start:start + depth_threads]) + view.raster('depth', depths(), None, loc | {'source_field': 'component_sources.depth', + 'definition': 'https://github.com/taeinkwon/h2oplayer/blob/main/utils.py', + 'conversion': 'registered millimetre camera-Z to metres; no viewer range clipping'}, + codec_threads=codec_threads, stream=getattr(args, 'stream_media', False)) + else: + view.absent('depth', 'No source depth frames') + view.absent('segment', 'H2O provides no native segmentation; rendering deferred to v2.0') + view.absent('relations', 'No source contact/grasp annotation') + return view.finish() + + +def convert_archive(archive, args, out, splits, models, assets, asset_archive, view_pool=None, ram_budget=None): + selected_views = set(args.views.split(',')) if args.views else None + subjects = {'subject' + s.strip() for s in args.subjects.split(',')} if args.subjects else None + current, rows, intrinsics, done = None, {}, {}, 0 + published_views = set() + camera_jobs, closed_cameras = {}, set() + last_camera = None + pipeline_active = False + ram_reserved = 0 + try: + with tempfile.TemporaryDirectory(prefix='h2o-source-') as wd, \ + tempfile.TemporaryDirectory(prefix='h2o-ram-', dir=args.ram_stage_dir) as rd: + work, ram_work = Path(wd), Path(rd) + def queue_camera(cam): + if cam in closed_cameras: + return + closed_cameras.add(cam) + if cam not in published_views and rows.get(cam): + camera_jobs[cam] = view_pool.submit(convert_view, work / '.converted' / cam, + args, '/'.join(current), cam, rows[cam], intrinsics.get(cam), + splits, models, assets, asset_archive) + def flush(): + nonlocal done, ram_reserved + if not rows: + return + seq = '/'.join(current) + reports, pending = {}, {} + for cam, frames in sorted(rows.items()): + existing = out / 'data' / seq.replace('/', '_') / cam + if (existing / 'metainfo.json').is_file(): + old_frames = [json.loads(line) for line in (existing / 'camera/frames.jsonl').read_text().splitlines()] + if [f['source_frame_id'] for f in old_frames] != list(range(min(frames), max(frames) + 1)): + raise ValueError('existing view has different sampling; choose a new release-id') + for frame in old_frames: + incoming = frames.get(frame['source_frame_id'], {}) + previous = frame.get('component_sources', {}) + if set(previous) != set(incoming) or any(previous[k].get('sha256') != v[1].get('sha256') for k, v in incoming.items()): + raise ValueError('duplicate H2O view differs from the published source; choose a new release-id') + else: + pending[cam] = frames + if pending: + if pipeline_active: + for cam in pending: + queue_camera(cam) + failure = None + for cam, job in camera_jobs.items(): + try: + reports[cam] = job.result() + except Exception as exc: + failure = failure or exc + if failure is not None: + raise failure + with sequence_dir(out, seq.replace('/', '_')) as target: + if pipeline_active: + for cam in pending: + shutil.move(work / '.converted' / cam, target / cam) + elif view_pool is None: + for cam, frames in pending.items(): + reports[cam] = convert_view(target / cam, args, seq, cam, frames, + intrinsics.get(cam), splits, models, assets, asset_archive) + else: + jobs = {cam: view_pool.submit(convert_view, target / cam, args, seq, cam, + frames, intrinsics.get(cam), splits, models, assets, asset_archive) + for cam, frames in pending.items()} + failure = None + # Every sibling must finish before sequence_dir can remove its inputs. + for cam, job in jobs.items(): + try: + reports[cam] = job.result() + except Exception as exc: + failure = failure or exc + if failure is not None: + raise failure + build_record(out, seq.replace('/', '_'), reports) + for directory in (work, ram_work): + for staged in list(directory.iterdir()): + if staged.is_dir(): + shutil.rmtree(staged) + else: + staged.unlink() + if ram_budget is not None: + lock, used, limit = ram_budget + with lock: + used[0] -= ram_reserved + ram_reserved = 0 + done += 1 + print(f'{"Converted" if pending else "Verified existing"} {seq}', flush=True) + # Uncompressed CASA supports seeking over large frames; gzip is single-pass. + mode = 'r:' if archive.suffix == '.tar' else 'r|gz' + try: + with tarfile.open(archive, mode) as tf: + for member in tf: + match = MEMBER.fullmatch(member.name) + if not member.isfile() or not match: + continue + subj, scene, seq, cam, tail = match.groups() + if subjects and subj not in subjects: + continue + key = (subj, scene, seq) + if key != current: + flush() + if args.limit and done >= args.limit: + break + current, rows, intrinsics = key, {}, {} + camera_jobs.clear() + closed_cameras.clear() + last_camera = None + pipeline_active = args.camera_pipeline + published_views = {view.name for view in + (out / 'data' / '_'.join(key)).glob('cam*') + if (view / 'metainfo.json').is_file()} + if selected_views and cam not in selected_views: + continue + if pipeline_active and cam != last_camera: + if last_camera is not None: + queue_camera(last_camera) + if cam in closed_cameras: + # Complete queued readers before accepting late fields for those cameras. + for job in camera_jobs.values(): + try: + job.result() + except Exception: + pass + shutil.rmtree(work / '.converted', ignore_errors=True) + camera_jobs.clear() + closed_cameras.clear() + pipeline_active = False + print(f'Camera-order fallback: {"/".join(current)}', flush=True) + last_camera = cam + frame = FRAME.fullmatch(tail) + if tail != 'cam_intrinsics.txt' and not frame: + continue + if frame and args.max_frames and int(frame[2]) >= args.max_frames: + continue + data = tf.extractfile(member).read() + if tail.endswith('.txt'): + payload = data # Small source annotations stay in RAM, not thousands of HDD files. + else: + staging = work + if ram_budget is not None and cam not in published_views: + lock, used, limit = ram_budget + needed = (len(data) + 4095) // 4096 * 4096 + with lock: + if used[0] + needed <= limit: + used[0] += needed + ram_reserved += needed + staging = ram_work + payload = safe_member(staging, member.name) + if cam not in published_views: + payload.parent.mkdir(parents=True, exist_ok=True) + payload.write_bytes(data) + # Published views still verify source bytes, but never read their staging paths. + item = (payload, locator(archive, member.name, data)) + if tail == 'cam_intrinsics.txt': + intrinsics[cam] = item + else: + kind, f = frame[1], int(frame[2]) + row = rows.setdefault(cam, {}).setdefault(f, {}) + if kind in row: + raise ValueError('duplicate H2O frame') + row[kind] = item + else: + flush() + finally: + # Never delete staging while a closed-camera job can still read from it. + for job in camera_jobs.values(): + try: + job.result() + except Exception: + pass + finally: + if ram_budget is not None: + lock, used, limit = ram_budget + with lock: + used[0] -= ram_reserved + return done + + +def main(argv=None): + p = parser('H2O', __doc__) + p.set_defaults(release_id='shared-v1.0') + p.add_argument('--workers', type=int, choices=range(1, 5), default=1, + help='Independent subject archives in parallel, 1..4; benchmark before using >2') + p.add_argument('--view-backend', choices=('threads', 'processes'), default='threads', + help='Use spawn processes to isolate Python camera processing') + p.add_argument('--camera-pipeline', action='store_true', + help='Overlap contiguous-camera extraction and conversion; reject interleaved input') + p.add_argument('--ffv1-slices', type=int, choices=(16,), + help='Optional FFV1 v3 slice parallelism; decoded frames must still match exactly') + p.add_argument('--view-workers', type=int, choices=range(1, 17), default=1, + help='Shared camera-view conversion pool, independent of archive readers') + p.add_argument('--ram-stage-dir', type=Path, help='Optional tmpfs staging; excess PNGs fall back to disk') + p.add_argument('--ram-stage-gib', type=int, choices=range(1, 65), default=32, + help='Shared PNG tmpfs quota across all archive readers, not per worker') + p.add_argument('--stream-media', action='store_true', + help='Pipe RGB/depth frames to FFmpeg instead of spooling huge RAW files') + p.add_argument('--codec-threads', type=int, choices=(1, 2, 4, 8, 10), default=4, + help='FFV1 slice threads per encode; default 4, use 10 for the current full run') + p.add_argument('--decode-threads', type=int, choices=(1, 2, 4, 8, 10), default=1, + help='FFmpeg threads for source RGB decoding and decoded-media checks') + p.add_argument('--depth-threads', type=int, choices=(1, 2, 4), default=1, + help='Bounded ordered source depth PNG loading per worker') + p.add_argument('--subjects') + p.add_argument('--include-casa', action='store_true') + p.add_argument('--archive', type=Path, help='Convert one explicit source archive') + args = p.parse_args(argv) + if args.camera_pipeline and args.view_workers < 2: + p.error('--camera-pipeline requires at least two --view-workers') + os.environ['HAND_WAREHOUSE_FFMPEG_THREADS'] = str(args.decode_threads) + if args.ffv1_slices is None: + os.environ.pop('HAND_WAREHOUSE_FFV1_SLICES', None) + else: + os.environ['HAND_WAREHOUSE_FFV1_SLICES'] = str(args.ffv1_slices) + if args.include_casa and args.workers != 1: + p.error('CASA can share sequence IDs with subject archives; convert it sequentially in a separate release') + archives = [args.archive.expanduser()] if args.archive else sorted( + {a for root in roots(args.root) for a in root.glob('subject*_v1_1.tar.gz')}) + if args.subjects and not args.archive: + requested = {'subject' + s.strip() for s in args.subjects.split(',')} + archives = [arc for arc in archives if arc.name.split('_', 1)[0] in requested] + if args.include_casa: + casa = find_file(args.root, 'h2o_CASA.tar') + if casa: + archives.append(casa) + if not archives: + p.error('no H2O archives found') + out = release(args, 'H2O') + source_mapping = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/h2o-RAW_TO_SHARED.md', + Path(__file__).resolve().parents[1] / 'doc/RAW_TO_SHARED.md', + out / 'doc/RAW_TO_SHARED.md') if p.is_file()) + mapping = out / 'doc/RAW_TO_SHARED.md' + if mapping.exists() and mapping.read_bytes() != source_mapping.read_bytes(): + raise ValueError('RAW_TO_SHARED.md changed; choose a new release-id') + if not mapping.exists(): + shutil.copyfile(source_mapping, mapping) + os.environ.pop('HAND_WAREHOUSE_MEDIA_TMPDIR', None) + ram_budget = None + if args.ram_stage_dir is not None: + args.ram_stage_dir = args.ram_stage_dir.expanduser().resolve() + if not args.ram_stage_dir.is_relative_to(Path('/dev/shm').resolve()): + p.error('--ram-stage-dir must be on /dev/shm; it is temporary input, not an output dataset') + args.ram_stage_dir.mkdir(parents=True, exist_ok=True) + limit = args.ram_stage_gib * 1024**3 + if shutil.disk_usage(args.ram_stage_dir).free < limit + 8 * 1024**3: + p.error('not enough tmpfs headroom for the requested shared staging quota') + ram_budget = (threading.Lock(), [0], limit) + if args.stream_media: + os.environ['HAND_WAREHOUSE_MEDIA_TMPDIR'] = str(args.ram_stage_dir) + torch.set_num_threads(1) + models, splits = mano_models(args.mano_dir), load_splits(args.root) + executor = ProcessPoolExecutor if args.view_backend == 'processes' else ThreadPoolExecutor + options = {'mp_context': multiprocessing.get_context('spawn')} if args.view_backend == 'processes' else {'thread_name_prefix': 'h2o-view'} + with tempfile.TemporaryDirectory(prefix='h2o-assets-') as wd, \ + executor(max_workers=args.view_workers, **options) as views: + assets, asset_archive = load_assets(args.root, Path(wd)) + def convert_one(archive): + return convert_archive(archive, args, out, splits, models, assets, asset_archive, + views if args.view_workers > 1 else None, ram_budget) + if args.workers == 1: + for archive in archives: + convert_one(archive) + else: + with ThreadPoolExecutor(max_workers=args.workers) as pool: + for archive, count in zip(archives, pool.map(convert_one, archives), strict=True): + print(f'Archive {archive.name}: {count} sequences', flush=True) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) + +# TODO(v2.0): 以下旧 MANO 网格和渲染分割代码仅保留备查;v1.0 不生成标注。 +# def load_mano_model(path: Path): +# """MPI MANO pkl → numpy 字典。shapedirs 在 pkl 内为 chumpy Select(对 (778,3,20) 基 +# 底 flat 选取前 10 个 shape 分量;idxs 已核实等价于 base[:,:,:10])。""" +# with open(path, "rb") as f: +# d = _ManoUnpickler(f, encoding="latin1").load() +# sd = d["shapedirs"] +# base = np.asarray(sd.a.x, np.float64) # (778, 3, 20) +# shapedirs = base.reshape(-1)[np.asarray(sd.idxs)].reshape(base.shape[0], 3, -1) +# jreg = d["J_regressor"] +# jreg = np.asarray(jreg.todense()) if hasattr(jreg, "todense") else np.asarray(jreg) +# return {"v_template": np.asarray(d["v_template"], np.float64), +# "shapedirs": shapedirs, +# "posedirs": np.asarray(d["posedirs"], np.float64), +# "weights": np.asarray(d["weights"], np.float64), +# "J_regressor": np.asarray(jreg, np.float64), +# "kintree": np.asarray(d["kintree_table"], np.int64), +# "faces": np.asarray(d["f"], np.int64)} +# +# +# def rodrigues(r): +# """axis-angle (N,3) → 旋转矩阵 (N,3,3)。公式 I + sinθ·K + (1−cosθ)·K²(已对 scipy 核验)。""" +# r = np.asarray(r, np.float64).reshape(-1, 3) +# th = np.linalg.norm(r, axis=1) +# R = np.zeros((len(r), 3, 3)) +# nz = th > 1e-12 +# R[~nz] = np.eye(3) +# k = r[nz] / th[nz, None] +# K = np.zeros((len(k), 3, 3)) +# K[:, 0, 1], K[:, 0, 2], K[:, 1, 2] = -k[:, 2], k[:, 1], -k[:, 0] +# K[:, 1, 0], K[:, 2, 0], K[:, 2, 1] = k[:, 2], -k[:, 1], k[:, 0] +# s, c = np.sin(th[nz])[:, None, None], np.cos(th[nz])[:, None, None] +# R[nz] = np.eye(3) + s * K + (1 - c) * (K @ K) +# return R +# +# +# def _mano_chain(model, betas, pose): +# """返回 (v_shaped, J, Rs, G):G 为 16 个关节的全局变换(平移列 = 关节位置)。""" +# v = model["v_template"] + np.einsum("nkc,c->nk", model["shapedirs"], betas) +# J = model["J_regressor"] @ v +# Rs = rodrigues(np.asarray(pose, np.float64).reshape(16, 3)) +# kt = model["kintree"] +# G = np.zeros((16, 4, 4)) +# for j in range(16): +# p = kt[0, j] if j else -1 +# loc = np.eye(4) +# loc[:3, :3] = Rs[j] +# loc[:3, 3] = J[j] - (J[p] if j else 0.0) +# G[j] = loc if not j else G[p] @ loc +# return v, J, Rs, G +# +# +# def mano_forward(model, betas, pose, transl): +# """MANO LBS 前向(经典蒙皮 M_j = G_j·G0_j⁻¹;对 hand_pose 21 关节实证 0.0 mm)。 +# pose: 48 axis-angle([0:3] 全局);返回相机系米顶点 (778,3)。""" +# v, J, Rs, G = _mano_chain(model, betas, pose) +# lrot = (Rs[1:] - np.eye(3)).ravel() +# v_posed = v + np.einsum("nkc,c->nk", model["posedirs"], lrot) +# kt = model["kintree"] +# G0 = np.zeros((16, 4, 4)) +# for j in range(16): +# p = kt[0, j] if j else -1 +# loc = np.eye(4) +# loc[:3, 3] = J[j] - (J[p] if j else 0.0) +# G0[j] = loc if not j else G0[p] @ loc +# M = np.einsum("nj,jab->nab", model["weights"], G @ np.linalg.inv(G0)) +# out = np.einsum("nab,nb->na", M[:, :3, :3], v_posed) + M[:, :3, 3] +# return out + np.asarray(transl, np.float64) +# +# +# def mano_chain_joints(model, betas, pose, transl): +# """16 个关节位置(相机系米)= 链平移列;自检用。""" +# _, _, _, G = _mano_chain(model, betas, pose) +# return G[:, :3, 3] + np.asarray(transl, np.float64) +# +# +# def rasterize(verts_cam, faces, labels, W, H, fx, fy, cx, cy): +# z = verts_cam[:, 2] +# P = faces +# ok = (z[P] > 0.02).all(1) # 任一顶点在相机后 → 丢弃该三角形 +# P, labels = P[ok], labels[ok] +# if len(P) == 0: +# return np.zeros((H, W), np.uint16), np.zeros(0, np.int64) +# x = verts_cam[:, 0] / z * fx + cx +# y = verts_cam[:, 1] / z * fy + cy +# xa = np.maximum(0, np.minimum(np.floor(x[P[:, 0]]), np.minimum( +# np.floor(x[P[:, 1]]), np.floor(x[P[:, 2]]))).astype(np.int64)) +# xb = np.minimum(W - 1, np.maximum(np.ceil(x[P[:, 0]]), np.maximum( +# np.ceil(x[P[:, 1]]), np.ceil(x[P[:, 2]]))).astype(np.int64)) +# ya = np.maximum(0, np.minimum(np.floor(y[P[:, 0]]), np.minimum( +# np.floor(y[P[:, 1]]), np.floor(y[P[:, 2]]))).astype(np.int64)) +# yb = np.minimum(H - 1, np.maximum(np.ceil(y[P[:, 0]]), np.maximum( +# np.ceil(y[P[:, 1]]), np.ceil(y[P[:, 2]]))).astype(np.int64)) +# xa, ya = np.minimum(xa, xb), np.minimum(ya, yb) # 完全出画的三角形 → 空 bbox +# wdt, hgt = xb - xa + 1, yb - ya + 1 +# cnt = wdt * hgt +# tot = int(cnt.sum()) +# tri = np.repeat(np.arange(len(P)), cnt) +# k = np.arange(tot) - (np.cumsum(cnt) - cnt)[tri] +# px = xa[tri] + k % wdt[tri] + 0.5 +# py = ya[tri] + k // wdt[tri] + 0.5 +# ax, ay = x[P[tri, 0]], y[P[tri, 0]] +# bx, by = x[P[tri, 1]], y[P[tri, 1]] +# cx_, cy_ = x[P[tri, 2]], y[P[tri, 2]] +# area = ((x[P[:, 1]] - x[P[:, 0]]) * (y[P[:, 2]] - y[P[:, 0]]) +# - (y[P[:, 1]] - y[P[:, 0]]) * (x[P[:, 2]] - x[P[:, 0]])) +# areat = area[tri] +# e0 = (bx - ax) * (py - ay) - (by - ay) * (px - ax) +# e1 = (cx_ - bx) * (py - by) - (cy_ - by) * (px - bx) +# e2 = (ax - cx_) * (py - cy_) - (ay - cy_) * (px - cx_) +# s = np.sign(areat) +# inside = (np.abs(areat) > 1e-9) & ((e0 * s >= 0) & (e1 * s >= 0) & (e2 * s >= 0)) +# px, py, tri = px[inside], py[inside], tri[inside] +# at = areat[inside] +# w0, w1, w2 = e1[inside] / at, e2[inside] / at, e0[inside] / at +# zz = w0 * z[P[tri, 0]] + w1 * z[P[tri, 1]] + w2 * z[P[tri, 2]] +# pix = py.astype(np.int64) * W + px.astype(np.int64) +# order = np.lexsort((zz, pix)) # 同像素按深度升序 → 首条即最近 +# pix, tri = pix[order], tri[order] +# first = np.unique(pix, return_index=True)[1] +# mask = np.zeros(H * W, np.uint16) +# win = tri[first] +# mask[pix[first]] = labels[win] + 1 # 临时标签 +1(0=背景) +# return mask.reshape(H, W), np.bincount(labels[win] + 1) +# +# +# # ============================================================================ +# # ffmpeg 写出与核验(与 convert_dexycb.py 同构) +# # ============================================================================ +# verts, faces_all, labels = [], [], [] +# for ti, (tid, kind) in enumerate(tracks): +# if kind == "hand_left" and b["mano"][0] > 0.5: +# verts.append(mano_forward(mano_models["left"], b["mano"][52:62], +# b["mano"][4:52], b["mano"][1:4])) +# faces_all.append(mano_models["left"]["faces"]) +# elif kind == "hand_right" and b["mano"][62] > 0.5: +# verts.append(mano_forward(mano_models["right"], b["mano"][114:124], +# b["mano"][66:114], b["mano"][63:66])) +# faces_all.append(mano_models["right"]["faces"]) +# elif isinstance(kind, tuple) and int(b["objp"][0]) == kind[1]: +# M = np.asarray(b["objrt"][1:17], np.float64).reshape(4, 4) +# V0, F0 = meshes[kind[1]] +# verts.append(V0 @ M[:3, :3].T + M[:3, 3]) +# faces_all.append(F0) +# else: +# continue +# labels.append(np.full(len(faces_all[-1]), ti)) +# if verts: +# V = np.concatenate(verts) +# offs = np.cumsum([0] + [len(v) for v in verts[:-1]]) +# F = np.concatenate([fa + o for fa, o in zip(faces_all, offs)]) +# mask, counts = rasterize(V, F, np.concatenate(labels), +# IMG_W, IMG_H, fx, fy, cx, cy) +# else: +# mask, counts = np.zeros((IMG_H, IMG_W), np.uint16), np.zeros(0, np.int64) +# lut = np.zeros(n_tracks + 1, np.uint16) +# for ti in range(n_tracks): +# present = ti + 1 < len(counts) and counts[ti + 1] > 0 +# if present: +# presence[tracks[ti][0]][f] = True +# if active_id[ti] is None: +# pid = next(i for i in range(1, 65535) if i not in used) +# used.add(pid) +# active_id[ti], seg_start[ti] = pid, f +# frame_maps[ti].append({"id": pid}) +# lut[ti + 1] = active_id[ti] +# elif active_id[ti] is not None: +# frame_maps[ti][-1]["frames"] = [seg_start[ti], f - 1] +# segments[ti].append([seg_start[ti], f - 1]) +# used.discard(active_id[ti]) +# active_id[ti] = None +# mw.write(lut[mask]) + + +# TODO(v2.0): 旧物体尺寸派生代码;v1.0 仅保留源物体关键点。 +# pts = np.asarray(b["objp"][1:64], np.float64).reshape(21, 3) +# half = np.abs((pts[1:9] - pts[0]) @ M[:3, :3]).max(0) +# obj_recs.append({ +# "track_id": f"o{classes.index(c)}", "frame": f, +# "mesh_ref": f"h2o/{OBJ_CLASSES[c]}.obj", +# "pose": {"quat": rotmat_to_quat_wxyz(M[:3, :3])[0].tolist(), +# "trans": M[:3, 3].tolist()}, +# "bbox_center3d": pts[0].tolist(), +# "bbox_size": (2 * half).tolist()}) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/convert_hoi4d_v1.0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/convert_hoi4d_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..9d5914d64ae72ee62564897743dfe5a41923e08d --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/convert_hoi4d_v1.0.py @@ -0,0 +1,595 @@ +#!/usr/bin/env python3 +"""HOI4D native observations and annotations → CONTRACT.md v1.0.""" +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from contextlib import ExitStack +from functools import lru_cache +import gzip +import io +import json +import os +from pathlib import Path +import pickle +import re +import shutil +import shlex +import posixpath +import subprocess +import tempfile +import tarfile +import threading +import zipfile + +# Each worker owns one Python thread; prevent native libraries spawning CPU pools. +for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + +import numpy as np +from PIL import Image +from scipy.spatial.transform import Rotation + +import torch + +from warehouse_v1_0 import (View, build_record, check_mesh, decode_args, find_file, json_write, locator, + mano_models, model_profile, parser, probe, release, run, safe_member, sequence_dir) + +CATEGORIES = { + 1: dict(cad="rigid/ToyCar", groups=[("main", [1], "Toy Car", 1)], + hands={2: "right"}, objmap={"Toycar": "main"}), + 2: dict(cad="rigid/Mug", groups=[("a", [1], "Mug", 2), ("b", [3], "Mug", 2)], + hands={2: "right"}, objmap={"Watercup": "a"}), + 3: dict(cad="articulated/Laptop", groups=[("main", [1, 3], "Laptop", 3)], + hands={2: "right"}, + objmap={"Laptopdisplay": "main", "Laptopkeyboard": "main"}), + 4: dict(cad="articulated/StorageFurniture", + groups=[("main", [1, 3, 4], "Storage Furniture", 4), + ("bottle", [5], "Bottle", 5)], + hands={2: "right"}, + objmap={"Lockerbody": "main", "Lockersldingdoor": "main", + "Lockerdrawer": "main", "Safebox": "main"}), + 5: dict(cad="rigid/Bottle", groups=[("main", [1], "Bottle", 5), + ("mug", [3], "Mug", 2)], + hands={2: "right"}, objmap={"bottleddrinks": "main"}), + 6: dict(cad="articulated/Safe", groups=[("main", [1, 3], "Safe", 6), + ("bottle", [4], "Bottle", 5)], + hands={2: "right"}, objmap={"Safebox": "main", "Safedoor": "main"}), + 7: dict(cad="rigid/Bowl", groups=[("main", [1], "Bowl", 7), + ("ball", [3], "Ball", None)], + hands={2: "right"}, objmap={"bowl": "main"}), + 8: dict(cad="articulated/Bucket", + groups=[("a", [1, 3], "Bucket", 8), ("b", [4, 5], "Bucket", 8)], + hands={2: "right", 6: "left"}, + objmap={"bucket": "a", "Buckethandle": "a"}), + 9: dict(cad="articulated/Scissors", groups=[("main", [1, 3], "Scissors", 9)], + hands={2: "right"}, + objmap={"scissors": "main", "scissors2": None}), # scissors2:场景道具,无掩码 + 11: dict(cad="articulated/Pliers", groups=[("main", [1, 3], "Pliers", 11)], + hands={2: "right"}, objmap={"Pliersleft": "main", "Pliersright": "main"}), + 12: dict(cad="rigid/Kettle", groups=[("main", [1], "Kettle", 12), + ("mug", [3], "Mug", 2)], + hands={2: "right"}, objmap={"kettle": "main"}), + 13: dict(cad="rigid/Knife", groups=[("main", [1], "Knife", 13), + ("apple", [3], "Apple", None)], + hands={2: "right"}, objmap={"knife": "main"}), + 14: dict(cad="articulated/TrashCan", + groups=[("main", [1, 3], "Trash Can", 14), ("bottle", [4], "Bottle", 5)], + hands={2: "right"}, objmap={"Dustbinbase": "main", "Dustbincover": "main"}), + 17: dict(cad="articulated/Lamp", groups=[("main", [1, 3, 4, 5], "Lamp", 17)], + hands={2: "right", 6: "left"}, + objmap={"Lampbase": "main", "Tablelampfirstjoint": "main", + "Tablelampsecondjoint": "main", "Thirdjointoftablelamp": "main"}), + 18: dict(cad="articulated/Stapler", + groups=[("main", [1, 3, 4], "Stapler", 18), ("paper", [5], "Paper", None)], + hands={2: "right", 6: "left"}, # 6=左手:官方 label.csv 缺列,实测修正 + objmap={"Staplerbase": "main", "Staplercover": "main"}), + 20: dict(cad="rigid/Chair", groups=[("main", [1], "Chair", 20)], + hands={2: "right", 3: "left"}, objmap={"chair": "main"}), +} + + +# Official HOI4D definitions/motion segmentation/label.csv; no spatial side inference. +REGION_NAMES = {1: {1: 'Toy Car', 2: 'Right Hand'}, 2: {1: 'Mug', 2: 'Right Hand', 3: 'Mug'}, 3: {1: 'Screen', 2: 'Right Hand', 3: 'Keyboard'}, 4: {1: 'Door', 2: 'Right Hand', 3: 'Body of the Cabinet', 4: 'Drawer', 5: 'Bottle'}, 5: {1: 'Bottle', 2: 'Right Hand', 3: 'Mug'}, 6: {1: 'Body of the Safe', 2: 'Right Hand', 3: 'Door', 4: 'Bottle'}, 7: {1: 'Bowl', 2: 'Right Hand', 3: 'Ball'}, 8: {1: 'Body of the Bucket', 2: 'Right Hand', 3: 'Handle', 4: 'Body of the Bucket', 5: 'Handle', 6: 'Left Hand'}, 9: {1: 'Left Part of the Scissors', 2: 'Right Hand', 3: 'Right Part of the Scissors'}, 11: {1: 'Left Part of the Pliers', 2: 'Right Hand', 3: 'Right Part of the Pliers'}, 12: {1: 'Kettle', 2: 'Right Hand', 3: 'Mug'}, 13: {1: 'Knife', 2: 'Right Hand', 3: 'Apple'}, 14: {1: 'Body of the Trash Can', 2: 'Right Hand', 3: 'Lid', 4: 'Bottle'}, 17: {1: 'Base', 2: 'Right Hand', 3: 'Tube', 4: 'Top Link', 5: 'Bottom Link', 6: 'Left Hand'}, 18: {1: 'Base', 2: 'Right Hand', 3: 'Slot', 4: 'Lid', 5: 'Paper'}, 20: {1: 'Chair', 2: 'Right Hand', 3: 'Left Hand'}} + + +class SplitFiles(io.RawIOBase): + """Read concatenated source gzip parts without concatenating 119 GB on disk.""" + def __init__(self, paths): + self.paths = iter(paths) + self.current = None + + def readable(self): + return True + + def readinto(self, buffer): + while True: + if self.current is None: + path = next(self.paths, None) + if path is None: + return 0 + self.current = path.open('rb') + n = self.current.readinto(buffer) + if n: + return n + self.current.close() + self.current = None + + def close(self): + if self.current is not None: + self.current.close() + super().close() + + +def extract_depths(root, sequences, work): + directory = find_file(root, 'DEPTH') + if directory is None: + return {}, [] + parts = sorted(directory.glob('HOI4D_depth_video.tar.gz*'), key=lambda p: int(p.name.split('.gz')[1] or 0)) + if not parts: + return {}, [] + wanted = {f'HOI4D_depth_video/{seq}/align_depth/depth_video.avi': seq for seq in sequences} + found = {} + with SplitFiles(parts) as joined, io.BufferedReader(joined) as inp, gzip.GzipFile(fileobj=inp) as gz: + with tarfile.open(fileobj=gz, mode='r|') as tf: + for member in tf: + if member.isfile() and member.name in wanted: + seq = wanted[member.name] + dest = work / (seq.replace('/', '_') + '.avi') + with tf.extractfile(member) as src, dest.open('wb') as dst: + shutil.copyfileobj(src, dst) + found[seq] = (dest, {'files': [str(p.resolve()) for p in parts], 'member': member.name}) + if len(found) == len(wanted): + break + return found, parts + + +def palette_mask(data): + with Image.open(io.BytesIO(data)) as im: + arr = np.asarray(im) + if arr.ndim == 2: + return arr.astype(np.uint16) + if arr.shape[-1] != 3: + raise ValueError('unsupported HOI4D mask representation') + # VOC's 256-color palette interleaves eight label bits into the high RGB bits. + # Invert it directly instead of sorting every pixel with np.unique. + if np.any(arr & np.array([31, 31, 63], dtype=np.uint8)): + raise ValueError('source mask has colors outside official VOC palette') + mask = np.zeros(arr.shape[:2], dtype=np.uint16) + for bit in range(8): + mask |= ((arr[..., bit % 3] >> (7 - bit // 3)) & 1).astype(np.uint16) << bit + return mask + + +# Four workers each reuse annotation and hand indices instead of rebuilding the ZIP directory. +@lru_cache(maxsize=8) +def index_frames(z): + index = {} + for name in z.namelist(): + parent, _, filename = name.rpartition('/') + stem, dot, suffix = filename.rpartition('.') + if not dot or not stem.isdigit() or suffix not in ('png', 'json', 'pickle'): + continue + entries = index.setdefault((parent + '/', '.' + suffix), {}) + f = int(stem) + if f in entries: + raise ValueError(f'duplicate frame number under {parent}') + entries[f] = name + return index + + +def frame_members(z, prefix, suffix): + return index_frames(z).get((prefix, suffix), {}) + + +def convert_sequence(seq, args, target, rgbz, annz, hpz, calz, cadz, paths, models, depth): + # ponytail: cache only one sequence's encoded annotation bytes; no decoded masks or CAD cache. + @lru_cache(maxsize=None) + def read_annotation(archive, name): + return archive.read(name) + + category = int(re.search(r'/C(\d+)/', seq)[1]) + definition = CATEGORIES.get(category) + if definition is None: + raise ValueError(f'category mapping unavailable: {category}') + prefix = f'HOI4D_annotations/{seq}' + mask_members = frame_members(annz, prefix + '/2Dseg/mask/', '.png') + shifted = frame_members(annz, prefix + '/2Dseg/shift_mask/', '.png') + if not mask_members: + mask_members = shifted + pose_members = frame_members(annz, prefix + '/objpose/', '.json') + hand_members = {side: frame_members(hpz, f'Hand_pose/handpose_{side}_hand/{seq}/', '.pickle') + for side in ('left', 'right')} if hpz else {'left': {}, 'right': {}} + with tempfile.TemporaryDirectory(prefix='hoi4d-source-') as wd: + work = Path(wd) + member = f'HOI4D_release/{seq}/align_rgb/image.mp4' + video = work / 'rgb.mp4' + with rgbz.open(member) as src, video.open('wb') as dst: + shutil.copyfileobj(src, dst) + info = probe(video) + if 'nb_frames' not in info: + info['nb_frames'] = json.loads(run(['ffprobe', '-v', 'error', '-count_frames', '-select_streams', 'v:0', + '-show_entries', 'stream=nb_read_frames', '-of', 'json', str(video)], stdout=subprocess.PIPE).stdout)['streams'][0]['nb_read_frames'] + n = int(info['nb_frames']) + if args.max_frames: + n = min(n, args.max_frames) + if shifted and mask_members != shifted and any(f not in mask_members and f in shifted for f in range(n)): + raise ValueError('shift_mask has frames absent from mask; correspondence unverified') + frames = [] + for f in range(n): + sources = {} + if f in mask_members: + sources['segment'] = locator(paths['annotations'], mask_members[f], read_annotation(annz, mask_members[f])) + if f in pose_members: + sources['object'] = locator(paths['annotations'], pose_members[f], read_annotation(annz, pose_members[f])) + for side in ('left', 'right'): + if f in hand_members[side]: + sources['hand_' + side] = locator(paths['hand'], hand_members[side][f], read_annotation(hpz, hand_members[side][f])) + frames.append(dict(source_frame_id=f, source_locator=locator(paths['release'], member, frame=f), + component_sources=sources, annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None) for k in sources})) + view = View(target, 'HOI4D', args.release_id, seq.replace('/', '_'), 'ego', frames) + view.valid_rules = { + 'mano': 'Matched side pickle contains poseCoeff, beta, trans and corresponding model available; zero angles are not missing', + 'keypoints': 'Matched side pickle contains kps2D; independently provided source points, no visibility gate', + 'pose': 'Matched source object record contains rotation and center; record identity retained', + 'dimensions': 'Matched source object record contains dimensions; size/mesh relation remains source_unspecified', + 'segment': 'Source mask or shift_mask present with verified palette codes and entity/part mapping', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'ego' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'source_sequence': seq} + view.rgb([], locator(paths['release'], member), video=video, count=n) + intr_name = f'camera_params/{seq.split("/")[0]}/intrin.npy' + if calz and intr_name in calz.namelist(): + view.camera(np.load(io.BytesIO(calz.read(intr_name))), locator(paths['camera'], intr_name)) + extr_name = prefix + '/3Dseg/output.log' + if extr_name in annz.NameToInfo: + lines = [line for line in annz.read(extr_name).decode().splitlines() if line.strip()] + if len(lines) % 5: + raise ValueError('invalid Open3D camera trajectory') + extr, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + for i in range(0, len(lines), 5): + idx = int(lines[i].split()[0]) + if idx < n: + if valid[idx]: + raise ValueError('duplicate trajectory index') + extr[idx] = np.linalg.inv(np.loadtxt(io.StringIO('\n'.join(lines[i + 1:i + 5])))) + valid[idx] = True + view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', extr, valid, + ['T', 'row', 'column'], locator(paths['annotations'], extr_name), + convention='T_camera_from_world', source_convention='Open3D LOG camera-to-world; inverted') + loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} + motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) + points, pv = np.full((n, 2, 21, 2), np.nan, np.float32), np.zeros((n, 2, 21), bool) + for slot, side in enumerate(('left', 'right')): + for f, name in hand_members[side].items(): + if f >= n: + continue + data = pickle.loads(read_annotation(hpz, name), encoding='latin1') + if all(k in data for k in ('poseCoeff', 'beta', 'trans')): + motion[f, slot] = np.r_[np.asarray(data['poseCoeff']).reshape(48), + np.asarray(data['beta']).reshape(10), np.asarray(data['trans']).reshape(3)] + mv[f, slot] = True # Zero angles are a valid pose, not a missing sentinel. + if 'kps2D' in data: + points[f, slot] = np.asarray(data['kps2D']).reshape(21, 2) + pv[f, slot] = True + if mv.any(): + if all(side in models for slot, side in enumerate(('left', 'right')) if mv[:, slot].any()): + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) + else: + view.absent('mano', 'Source MANO exists; provide --mano-dir to fix model identity', 'dependency_missing') + if pv.any(): + view.tensor('keypoints_uv', 'keypoints/uv/v1', 'annotation/keypoints/uv.pt', points, pv, + ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='pixel', + source_method='Upstream fitted MANO projection already present in kps2D') + objects = {} + groups = {key: (vals, name, cls) for key, vals, name, cls in definition['groups']} + def ensure_object(key, source_loc, category_id=None, frame=None, source_id=None): + if key not in objects: + view.object(key, source_loc, scope='frame' if frame is not None else 'sequence', + scope_id=f'{seq}:{frame}' if frame is not None else None, + category_id=category_id, source_object_id=source_id) + objects[key] = {} + mappings = [] + mask_valid = [f in mask_members for f in range(n)] + if any(mask_valid): + width, height = view.meta['camera']['image_size'] + def masks(): + for f in range(n): + labels = [] + if f in mask_members: + mask = palette_mask(read_annotation(annz, mask_members[f])) + for value in np.unique(mask): + value = int(value) + if value in (0, 255): + if value == 255: + raise ValueError('HOI4D 255 region semantics unverified') + continue + if REGION_NAMES[category].get(value) in ('Left Hand', 'Right Hand'): + entity, part, cls = 'hand_' + REGION_NAMES[category][value].split()[0].lower(), None, 'hand' + else: + group = next((k for k, (vals, _, _) in groups.items() if value in vals), None) + entity = group or f'unknown_region_{value}' + cls = groups[group][2] if group else None + part = f'region_{value}' if group and len(groups[group][0]) > 1 else None + ensure_object(entity, frames[f]['component_sources']['segment'], cls) + if part: + objects[entity].setdefault('parts', {})[part] = {'part_id': part, 'parent_id': None, + 'has_model': False, 'mesh_ref': None, 'source_region_code': value, 'name': REGION_NAMES[category].get(value)} + labels.append(dict(mask_value=value, category_id=cls, entity_id=entity, + part_id=part, source_instance_id=value, + source_attributes={'region_name': REGION_NAMES[category].get(value)})) + else: + mask = np.zeros((height, width), np.uint16) + mappings.append(dict(frame_index=f, labels=labels)) + yield mask + view.raster('segment', masks(), mask_valid, loc, mappings) + view.meta['components']['segment']['coverage'] = {'kind': 'unknown'} + if any(label['part_id'] for row in mappings for label in row['labels']): + view.meta['components']['segment']['segmentation_type'] = 'part' + else: + view.absent('segment', 'No native segmentation for this source sequence') + records = {} + for f, name in pose_members.items(): + if f >= n: + continue + data = json.loads(read_annotation(annz, name)) + # isEffective is not used to erase existing numerical annotations. + source_records = data.get('dataList', data.get('objects')) + if source_records is None: + raise ValueError('unrecognized source object annotation structure') + if category == 2 and source_records and (len(source_records) != 1 or + source_records[0].get('id') != 1 or source_records[0].get('label') != 'Watercup'): + raise ValueError('C2 native pose differs from the verified one-object target; cannot map to mask region 1') + label_counts = Counter(record['label'] for record in source_records) + per_frame = set() + for record_index, record in enumerate(source_records): + label = record['label'] + group = definition['objmap'].get(label) + # Pinned official ObjTracking reads dataList[0] with segmentation label 1. + source_primary = category == 2 and record_index == 0 and record.get('id') == 1 and group == 'a' + ambiguous = group is not None and sum(g[2] == groups[group][2] for g in groups.values()) > 1 and not source_primary + ambiguous = ambiguous or (label_counts[label] > 1 and not source_primary) or group is None + entity = f'pose_frame_{f}_{record_index}' if ambiguous else group + ensure_object(entity, locator(paths['annotations'], name, record=record_index), + groups[group][2] if group else None, frame=f if ambiguous else None, source_id=record.get('id')) + if ambiguous: + view.build['unresolved'].append({'component': entity, 'status': 'source_semantics_unverified', + 'reason': 'Source pose retained with frame identity; no guessed association to same-class mask instances'}) + label_key = (entity, label) + if label_key in per_frame: + raise ValueError(f'ambiguous repeated object label {label}; source identity must be resolved') + per_frame.add(label_key) + records.setdefault(label_key, {})[f] = (record, locator(paths['annotations'], name, record=record.get('id'))) + if category == 2 and any(entity == 'a' for entity, _ in records): + view.build['validation'].append({'component': 'C2_source_pose_mask_identity', + 'rule': 'Official ObjTracking process_data.py reads dataList[0] with semantic mask label 1', + 'source_revision': 'afa7bf37b02b7e33cf245acd08b98c207ccc175c', + 'source_pose_id': 1, 'mask_value': 1, 'matched_frames': sum(len(by_frame) for (entity, _), by_frame in records.items() if entity == 'a')}) + for (entity, label), by_frame in records.items(): + part_labels = [k[1] for k in records if k[0] == entity] + articulated = definition['cad'].startswith('articulated/') and entity == definition['groups'][0][0] + part = 'pose_' + re.sub(r'[^a-zA-Z0-9_]', '_', label) if articulated or len(part_labels) > 1 else None + base = f'annotation/object/{entity}' + if part: + base += '/parts/' + part + objects[entity].setdefault('parts', {})[part] = dict(part_id=part, parent_id=None, + has_model=False, mesh_ref=None, source_label=label) + poses, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + dimensions = np.full((n, 3), np.nan, np.float32) + dv = np.zeros(n, bool) + for f, (record, _) in by_frame.items(): + if all(k in record for k in ('rotation', 'center')): + poses[f] = np.eye(4) + poses[f, :3, :3] = Rotation.from_euler('XYZ', [record['rotation'][k] for k in ('x', 'y', 'z')]).as_matrix() + poses[f, :3, 3] = [record['center'][k] for k in ('x', 'y', 'z')] + valid[f] = True + if 'dimensions' in record: + dimensions[f] = [record['dimensions'][k] for k in ('length', 'width', 'height')] + dv[f] = True + key = entity + ('_' + part if part else '') + view.tensor('pose_' + key, 'transform/se3/v1' if part else 'object/rigid/v1', base + '/pose.pt', poses, valid, + ['T', 'row', 'column'], loc, convention='T_camera_from_part' if part else 'T_camera_from_object', + unit='m', source_label=label, source_euler_order='XYZ', + definition='https://github.com/hoi4d/ObjTracking/blob/main/process_data.py') + if dv.any(): + view.tensor('dimensions_' + key, 'object/dimensions/v1', base + '/dimensions.pt', dimensions, dv, + ['T', 'dimension'], loc, dimensions_semantics='source_unspecified', unit='m', scale_applied_to_mesh=False) + if cadz: + primary = definition['groups'][0][0] + if category != 2 and sum(g[2] == category for g in groups.values()) > 1: + primary = 'source_cad_instance' + instance = int(re.search(r'/N(\d+)/', seq)[1]) + mesh_prefix = f'HOI4D_CAD_Model_for_release/{definition["cad"]}/{instance:03d}' + candidates = [name for name in cadz.namelist() if not name.endswith('/') and + (name == mesh_prefix + '.obj' or name.startswith(mesh_prefix + '/'))] + if candidates: + # Retain OBJ material/texture dependencies beside their original names. + queue = list(candidates) + for name in queue: + if Path(name).suffix.lower() not in ('.obj', '.mtl'): + continue + for line in cadz.read(name).decode().splitlines(): + fields = shlex.split(line, comments=True) + if not fields: + continue + refs = fields[1:] if fields[0] == 'mtllib' else ([fields[-1]] if + fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal') else []) + for ref in refs: + dependency = posixpath.normpath(posixpath.join(posixpath.dirname(name), ref)) + if dependency not in cadz.NameToInfo: + raise ValueError(f'missing CAD dependency: {dependency}') + if dependency not in candidates: + candidates.append(dependency) + queue.append(dependency) + ensure_object(primary, locator(paths['cad'], mesh_prefix), category) + asset_dir = view.path / f'annotation/object/{primary}/assets' + asset_refs = [] + for name in candidates: + relative = posixpath.relpath(name, mesh_prefix if definition['cad'].startswith('articulated/') else posixpath.dirname(mesh_prefix)) + dest = safe_member(asset_dir, relative) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(cadz.read(name)) + ref = dest.relative_to(view.path).as_posix() + if dest.suffix.lower() == '.obj': + asset_key = re.sub(r'[^a-zA-Z0-9_]', '_', relative) + view.component('mesh_' + primary + '_' + asset_key, 'mesh/obj/v1', ref, ['vertex'], + locator(paths['cad'], name), unit='m', valid=True, + scale_applied_to_mesh=False, dimensions_semantics='source_unspecified') + asset_refs.append(ref) + if definition['cad'].startswith('articulated/'): + part_id = 'asset_' + asset_key + objects[primary].setdefault('parts', {})[part_id] = dict(part_id=part_id, + parent_id=None, has_model=True, mesh_ref=ref, source_asset=relative, + note='Source asset; correspondence to motion part labels remains unverified') + for asset_ref in asset_refs: + mesh_check = check_mesh(view.path / asset_ref, asset_dir) + view.build['validation'].append({'component': asset_ref, **mesh_check, + 'unit_basis': 'official ObjTracking loads source canonical CAD without scaling in metre camera coordinates', + 'geometric_acceptance': 'physical dimensions-to-mesh relation remains source_unspecified'}) + metadata_path = view.path / f'annotation/object/{primary}/metainfo.json' + metadata = json.loads(metadata_path.read_text()) + metadata.update(has_model=bool(asset_refs), asset_refs=asset_refs) + if definition['cad'].startswith('rigid/') and len(asset_refs) == 1: + metadata['mesh_ref'] = asset_refs[0] + json_write(metadata_path, metadata) + if definition['cad'].startswith('articulated/'): + view.build['unresolved'].append({'component': 'object_part_asset_association', + 'status': 'source_semantics_unverified', + 'reason': 'All source assets and motion labels retained, but no guessed correspondence or joint_state'}) + for entity, info in objects.items(): + if 'parts' in info: + ref = f'annotation/object/{entity}/articulation.json' + json_write(view.path / ref, {'parts': list(info['parts'].values()), 'joints': [], + 'hierarchy_semantics': 'semantic_containment', + 'note': 'Unassociated source region, motion and asset nodes; original CAD trees retained in assets'}) + view.component('articulation_' + entity, 'object/articulated/v1', ref, [], loc) + meta_path = view.path / f'annotation/object/{entity}/metainfo.json' + metadata = json.loads(meta_path.read_text()) + metadata['articulation_ref'] = ref + json_write(meta_path, metadata) + if depth is not None: + dpath, dloc = depth + dmeta = probe(dpath) + if [dmeta['width'], dmeta['height']] != view.meta['camera']['image_size']: + raise ValueError('HOI4D depth grid differs from RGB') + if dmeta['pix_fmt'] != 'gray16le': + raise ValueError('unexpected HOI4D depth pixel format') + width, height = view.meta['camera']['image_size'] + raw = work / 'depth.raw' + limits = ['-frames:v', str(n)] if args.max_frames else [] + run(decode_args(dpath, 'gray16le') + limits + ['-y', str(raw)]) + if raw.stat().st_size != n * width * height * 2: + raise ValueError('depth/RGB frame count or grid mismatch') + def depths(): + with raw.open('rb') as inp: + for _ in range(n): + yield np.frombuffer(inp.read(width * height * 2), ' best_iou + 0.1 and i > 0.15: +# best, best_iou = s[0], i +# if best != gk: +# gk, iou_fixups = best, iou_fixups + 1 diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/convert_visor_v1.0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/convert_visor_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..8f0595bf5e89ae00c959472ff197dfda2d7a6ea6 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/convert_visor_v1.0.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +"""VISOR source polygons and contact → CONTRACT.md v1.0, without rasterization or side inference.""" +from collections import Counter +import hashlib +import json +import re +import shutil +import tempfile +from pathlib import Path +import zipfile + +import numpy as np +import torch + +from warehouse_v1_0 import (View, build_record, find_file, jsonl_write, locator, parser, + release, roots, sequence_dir, source) + +FRAME = re.compile(r'frame_(\d+)') +HAND = {300: 'left', 301: 'right'} +GLOVE = {303: 'left', 304: 'right'} +STATES = {'hand-not-in-contact': 'negative', 'glove-not-in-contact': 'negative', + 'none-of-the-above': 'target_unannotated', 'inconclusive': 'unknown'} + + +def hand_side(ann): + if ann['class_id'] in HAND: + return HAND[ann['class_id']] + if ann['class_id'] not in (60, 303, 304): + return None + raw = ann.get('on_which_hand') + raw = raw if isinstance(raw, list) else [raw] + sides = set() + for item in raw: + if item == 'left hand': + sides.add('left') + if item in ('right hand', 'rigth hand'): + sides.add('right') + if len(sides) == 1: + return next(iter(sides)) + if not sides and ann['class_id'] in GLOVE: + return GLOVE[ann['class_id']] + return None + + +def convert_video(video, split, annotation, ann_loc, rgb_zip, rgb_loc, mapping, args, target): + indexed = sorted(enumerate(annotation['video_annotations']), key=lambda row: int(FRAME.search(row[1]['image']['name'])[1])) + if args.max_frames: + indexed = indexed[:args.max_frames] + if len({row['image']['name'] for _, row in indexed}) != len(indexed): + raise ValueError('duplicate VISOR frame') + keys = lambda row, ann: (row['image']['subsequence'], ann['class_id'], ann['name']) + collisions = set() + for _, row in indexed: + collisions.update(key for key, number in Counter(keys(row, a) for a in row['annotations']).items() if number > 1) + frames, paths = [], [] + with tempfile.TemporaryDirectory(prefix='visor-rgb-') as wd, zipfile.ZipFile(rgb_zip) as z: + work = Path(wd) + for original_index, row in indexed: + name = row['image']['name'] + data = z.read(name) + path = work / Path(name).name + path.write_bytes(data) + paths.append(path) + loc = rgb_loc | {'nested_member': name, 'sha256': hashlib.sha256(data).hexdigest()} + frames.append(dict(source_frame_id=int(FRAME.search(name)[1]), source_locator=loc, + source_image=row['image'], original_frame_name=mapping.get(name), + annotation_matches={'segment': dict(source_frame_id=name, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None, + source_locator=ann_loc | {'record': f'video_annotations[{original_index}]'})})) + view = View(target, 'EPIC-KITCHENS-VISOR', args.release_id, video, 'ego', frames, sampling='sparse', split=split) + view.valid_rules = { + 'segment': 'Selected sparse annotation frame present; all source polygons finite with at least three vertices and entity mapping valid', + 'relations': 'At least one source in_contact_object value present; positive targets resolve in the same frame; unknown is an explicit usable status', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta.update(view_type='ego', split_scheme='VISOR_GroundTruth_SparseAnnotations', split_source_locator=ann_loc) + view.meta['sampling']['selection'] = {'representation': 'official sparse annotations', 'max_frames': args.max_frames} + view.rgb(paths, rgb_loc) + entities = {} + polygons, mappings, relations, relation_valid = [], [], [], [] + for f, (original_index, row) in enumerate(indexed): + frame_loc = ann_loc | {'record': f'video_annotations[{original_index}]'} + id_map, labels, polys = {}, [], [] + for code, ann in enumerate(row['annotations'], 1): + if code >= 65535: + raise ValueError('too many source instances') + sid = ann['id'] + if sid in id_map: + raise ValueError('duplicate source instance ID within a frame') + side = hand_side(ann) + if side is not None: + entity = 'hand_' + side + else: + key = keys(row, ann) + identity = key + (sid, row['image']['name']) if key in collisions else key + entity = 'object_' + hashlib.sha256(json.dumps(identity).encode()).hexdigest()[:20] + if entity not in entities: + scope = 'frame' if key in collisions else 'subsequence' + scope_id = f'{video}:{row["image"]["name"]}' if scope == 'frame' else f'{video}:{key[0]}' + view.object(entity, frame_loc | {'source_instance_id': sid}, scope, scope_id, + category_id=ann['class_id'], name=ann['name'], + association_basis='source_frame_instance' if scope == 'frame' else 'official_subsequence_entity_name') + entities[entity] = True + id_map[sid] = entity + for polygon in ann.get('segments', []): + p = np.asarray(polygon) + if p.ndim != 2 or p.shape[1] != 2 or len(p) < 3 or not np.isfinite(p).all(): + raise ValueError(f'invalid source polygon {sid}') + polys.append(dict(mask_value=code, polygons=ann.get('segments', []))) + labels.append(dict(mask_value=code, category_id=ann['class_id'], entity_id=entity, + part_id=None, source_instance_id=sid, + source_attributes={k: v for k, v in ann.items() if k != 'segments'})) + rr = [] + provided = False + for ann in row['annotations']: + raw = ann.get('in_contact_object') + values = raw if isinstance(raw, list) else [raw] + for value in values: + if value is None: + continue + provided = True + status = STATES.get(value) + obj = None + if status is None: + if value not in id_map: + raise ValueError(f'unresolved source contact target {value} in {video} frame {f}') + status, obj = 'positive', id_map[value] + rr.append(dict(relation_type='contact', subject_id=id_map[ann['id']], object_id=obj, + status=status, source_value=value, source_locator=frame_loc | {'source_instance_id': ann['id']}, + provenance=source('Resolve source contact ID against instances in this frame'))) + polygons.append(dict(frame_index=f, instances=polys)) + mappings.append(dict(frame_index=f, labels=labels)) + relations.append(dict(frame_index=f, relations=rr)) + relation_valid.append(provided) + jsonl_write(view.path / 'annotation/segment/polygons.jsonl', polygons) + jsonl_write(view.path / 'annotation/segment/instances.jsonl', mappings) + torch.save(torch.ones(len(frames), dtype=torch.bool, device='cpu'), view.path / 'annotation/segment/mask_valid.pt') + view.component('segment', 'segment/instance_polygons/v1', 'annotation/segment/polygons.jsonl', ['T'], ann_loc, + valid_ref='annotation/segment/mask_valid.pt', valid_axes=['T'], segmentation_type='instance', + mapping_ref='annotation/segment/instances.jsonl', coverage={'kind': 'unknown', 'exhaustive_ref': 'annotation/segment/instances.jsonl'}) + view.relations(relations, relation_valid, ann_loc) + for component in ('depth', 'mano', 'keypoints_uv', 'keypoints_xyz', 'intrinsic', 'extrinsic'): + view.absent(component, 'Not provided by VISOR sparse source annotations') + return view.finish() + + +def main(argv=None): + p = parser('EPIC-KITCHENS-VISOR', __doc__) + p.add_argument('--videos', help='Comma-separated video names') + p.add_argument('--splits', default='train,val') + args = p.parse_args(argv) + wanted = set(args.videos.split(',')) if args.videos else None + splits = set(args.splits.split(',')) + if not splits <= {'train', 'val'}: + p.error('only annotated train/val splits are available') + out = release(args, 'EPIC-KITCHENS-VISOR') + archive = find_file(args.root, 'EPIC-KITCHENS VISOR.zip') + with tempfile.TemporaryDirectory(prefix='visor-source-') as wd: + work = Path(wd) + if archive: + with zipfile.ZipFile(archive) as z: + suffix = 'GroundTruth-SparseAnnotations/annotations/' + members = [n for n in z.namelist() if suffix in n and n.endswith('.json')] + prefix = members[0].split(suffix)[0] + fm = json.loads(z.read(prefix + 'frame_mapping.json')) + done = 0 + for member in sorted(members): + split, filename = member.split(suffix)[1].split('/') + video = Path(filename).stem + if split not in splits or wanted and video not in wanted: + continue + data = z.read(member) + rgb_member = prefix + f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' + rgb_zip = work / (video + '.zip') + with z.open(rgb_member) as inp, rgb_zip.open('wb') as dest: + shutil.copyfileobj(inp, dest) + with sequence_dir(out, video) as dest: + report = convert_video(video, split, json.loads(data), locator(archive, member, data), + rgb_zip, locator(archive, rgb_member), fm.get(video, {}), args, dest / 'ego') + build_record(out, video, {'ego': report}) + rgb_zip.unlink() + done += 1 + print(f'Converted {video}', flush=True) + if args.limit and done >= args.limit: + break + else: + root = next((r for r in roots(args.root) if (r / 'GroundTruth-SparseAnnotations').is_dir()), None) + if root is None: + p.error('VISOR outer ZIP or extracted source directory not found') + fm = json.loads((root / 'frame_mapping.json').read_text()) if (root / 'frame_mapping.json').exists() else {} + done = 0 + for split in sorted(splits): + for ann in sorted((root / 'GroundTruth-SparseAnnotations/annotations' / split).glob('*.json')): + video = ann.stem + if wanted and video not in wanted: + continue + rgb = root / f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' + with sequence_dir(out, video) as dest: + report = convert_video(video, split, json.loads(ann.read_text()), locator(ann), rgb, + locator(rgb), fm.get(video, {}), args, dest / 'ego') + build_record(out, video, {'ego': report}) + done += 1 + if args.limit and done >= args.limit: + return 0 + if not done: + p.error('no matching annotated videos found') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) + +# TODO(v2.0): 旧距离猜侧和单层掩码生成仅注释保留;v1.0 不执行。 +# if side is None and len(frame_hands) == 1: +# # 空间门槛:脱下放在远处的手套不并入(实测双峰 0..25px / ≥44px) +# hb = frame_hands[0][1] +# gb = _bbox_of(polys) +# if hb and gb and _bbox_dist(gb, hb) <= GLOVE60_MERGE_BBOX_DIST: +# side = frame_hands[0][0] +# stats["glove60_merged_into_sole_hand"] += 1 +# if side is None: +# stats["dropped_glove60_unresolved"] += 1 +# id_disp[mid] = ("dropped", "glove60") +# continue +# def rasterize_and_encode(vdir, frames, frame_draw, zip_path, n, stats): +# """流式读 zip 内 jpg + 光栅化多边形 → rgb.mkv / mask.mkv;返回 (w, h)。""" +# from PIL import Image, ImageDraw +# +# with zipfile.ZipFile(zip_path) as zf: +# member_of = {} +# for nm in zf.namelist(): +# member_of[os.path.basename(nm)] = nm +# names = [im["name"] for im in frames] +# missing = [nm for nm in names if nm not in member_of] +# if missing: +# raise RuntimeError(f"{len(missing)} annotated frames missing in zip, " +# f"e.g. {missing[:3]}") +# stats["zip_extra_members"] = len(member_of) - len(names) +# +# # 首帧定分辨率(官方 1920×1080,实测每帧校验) +# img0 = Image.open(io.BytesIO(zf.read(member_of[names[0]]))).convert("RGB") +# w, h = img0.size +# +# bin_img = Image.new("L", (w, h), 0) +# bin_draw = ImageDraw.Draw(bin_img) +# canvas = np.zeros((h, w), np.uint16) +# with VideoPipe(vdir / "mask.mkv", w, h, FPS, "mask") as mw, \ +# VideoPipe(vdir / "rgb.mkv", w, h, FPS, "rgb") as rw: +# for f in range(n): +# canvas[:] = 0 +# for pid, polys in frame_draw[f]: +# bin_draw.rectangle((0, 0, w, h), fill=0) +# for poly in polys: +# bin_draw.polygon([(float(x), float(y)) for x, y in poly], fill=255) +# arr = np.asarray(bin_img) +# canvas[arr > 0] = pid # 后画覆盖先画:物体→手(modal) +# mw.write(canvas) +# img = img0 if f == 0 else Image.open( +# io.BytesIO(zf.read(member_of[names[f]]))).convert("RGB") +# if img.size != (w, h): +# raise RuntimeError(f"frame {names[f]}: size {img.size} != {(w, h)}") +# rw.write(np.asarray(img)) +# n_mask, n_rgb = mw.n, rw.n +# if (n_rgb, n_mask) != (n, n): +# raise RuntimeError(f"wrote rgb={n_rgb} mask={n_mask} != {n}") +# got = (count_frames(vdir / "rgb.mkv"), count_frames(vdir / "mask.mkv")) +# if got != (n, n): +# raise RuntimeError(f"encoded rgb={got[0]} mask={got[1]} != {n} (decode verify)") +# return w, h +# +# diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-check-fallback.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-check-fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..96c33bf9e1c9db26ac0a555e174470827da026ad --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-check-fallback.py @@ -0,0 +1,137 @@ +"""Full coverage/numeric audit, plus representative persisted-media QC and offline HTML.""" +import os +for key in ('OMP_NUM_THREADS','OPENBLAS_NUM_THREADS','MKL_NUM_THREADS','NUMEXPR_NUM_THREADS'): + os.environ[key]='1' +os.environ['HAND_WAREHOUSE_FFMPEG_THREADS']='4' +os.environ.pop('HAND_WAREHOUSE_FFV1_SLICES',None) +os.environ.pop('HAND_WAREHOUSE_MEDIA_TMPDIR',None) +import collections,datetime,hashlib,html,json,re,sys,time,zipfile +from concurrent.futures import ThreadPoolExecutor,as_completed +from pathlib import Path +from zoneinfo import ZoneInfo +import numpy as np +import torch +root=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe') +release=root/'H2O/shared-v1.0' +sys.path.insert(0,str(root/'frozen-code/scripts')) +from warehouse_v1_0 import SCHEMA,check_transform,check_valid_policy,check_view_type,safe_member,sha256 +from render_h2o_validation import render +out=release/'doc/validation/final-quick-check' +out.mkdir(exist_ok=True) +torch.set_num_threads(1) +started=time.monotonic() +expected={} +with zipfile.ZipFile('/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/label_split.zip') as z: + for name in z.namelist(): + if '/action_' not in name:continue + for line in z.read(name).decode().splitlines(): + fields=line.split() + if len(fields)>1 and fields[1]!='path': + seq=fields[1].replace('/','_') + expected[seq]=max(expected.get(seq,0),int(fields[-1])+1) +folders={p.name:p for p in (release/'data').iterdir() if p.is_dir()} +assert set(folders)==set(expected),(sorted(set(expected)-set(folders)),sorted(set(folders)-set(expected))) +assert len(expected)==184 and sum(expected.values())==114329 +receipts={p.name.removesuffix('.build.json'):p for p in (release/'doc').glob('*.build.json')} +assert set(receipts)==set(expected) +assert 'EXIT=0' in (root/'full.status').read_text() +failures=[] +rows=[] +def require(ok,message): + if not ok:raise ValueError(message) +def load(path): + def cpu(storage,location): + require(location=='cpu',f'non-CPU storage: {path}') + return storage + obj=torch.load(path,map_location=cpu,weights_only=True) + require(type(obj) is torch.Tensor,f'non-tensor: {path}') + return obj.numpy() +def check_sequence(seq): + folder=folders[seq];n=expected[seq] + require({p.name for p in folder.iterdir() if p.is_dir()}=={f'cam{i}' for i in range(5)},'five-camera coverage') + receipt=json.loads(receipts[seq].read_text()) + require(receipt['sequence_id']==seq and set(receipt['views'])=={f'cam{i}' for i in range(5)},'build receipt') + result=[] + for i in range(5): + cam=f'cam{i}';view=folder/cam + meta=json.loads((view/'metainfo.json').read_text()) + require((meta['dataset_id'],meta['sequence_id'],meta['camera_id'],meta['num_frames'])==('H2O',seq,cam,n),'header/timeline') + require(meta['view_type']==('ego' if i==4 else 'exo'),'view role') + require(meta['sampling']['selection']=={'max_frames':None,'views':None},'unexpected subsampling') + check_view_type(meta) + components=meta['components'] + require(all(components[k].get('available') for k in ('rgb','depth','mano','keypoints_xyz','intrinsic','extrinsic')),'required modality absent') + require(not components['segment']['available'] and not components['relations']['available'],'unexpected synthesized component') + rgb_sources=[];depth_sources=[];rgb_count=depth_count=0 + with (view/'camera/frames.jsonl').open() as inp: + count=0 + for index,line in enumerate(inp): + f=json.loads(line) + require(f['frame_index']==index and f['source_frame_id']==index,'source frame index') + require(f['sync_id']==f'{seq.replace("_","/")}:{index}','synchronization ID') + sources=f['component_sources'] + for kind,loc in sources.items(): + require(re.fullmatch('[0-9a-f]{64}',loc.get('sha256','')) is not None,f'source SHA256: {kind}') + require(f'/{cam}/' in loc.get('member',''),'wrong source camera') + rgb_sources.append('rgb' in sources);depth_sources.append('depth' in sources) + rgb_count+=rgb_sources[-1];depth_count+=depth_sources[-1];count+=1 + require(count==n,'frames.jsonl length') + numeric=0 + object_names=[] + for key,c in components.items(): + if not c['available']:continue + for field in ('data_ref','valid_ref','mapping_ref'): + if c.get(field): + path=safe_member(view,c[field]) + require(path.is_file() and path.stat().st_size>0,f'missing/empty {c[field]}') + schema=SCHEMA['components'][c['schema_id']] + if c.get('valid_policy'):check_valid_policy(c,n) + valid=load(view/c['valid_ref']) if c.get('valid_ref','').endswith('.pt') else None + if valid is not None: + shape=schema.get('valid_shape') + require(valid.dtype==np.bool_ and valid.shape[0]==n,f'{key}: validity dtype/timeline') + if shape:require(len(shape)==valid.ndim and all(not isinstance(s,int) or valid.shape[j]==s for j,s in enumerate(shape)),f'{key}: validity shape') + if key=='rgb':require(np.array_equal(valid,np.asarray(rgb_sources)), 'RGB existence validity mismatch') + if c['data_ref'].endswith('.pt'): + arr=load(view/c['data_ref']);numeric+=1 + require(arr.dtype==np.float32 and arr.shape[0]==n,f'{key}: dtype/timeline') + shape=schema.get('shape') + if shape:require(len(shape)==arr.ndim and all(not isinstance(s,int) or arr.shape[j]==s for j,s in enumerate(shape)),f'{key}: tensor shape') + if valid is not None: + require(arr.shape[:valid.ndim]==valid.shape and np.isfinite(arr[valid]).all() and np.isnan(arr[~valid]).all(),f'{key}: finite/NaN validity semantics') + if c['schema_id'] in ('transform/se3/v1','object/rigid/v1'):check_transform(arr[valid]) + if key=='intrinsic':require(np.allclose(arr[:,2],[0,0,1]) and (arr[:,0,0]>0).all() and (arr[:,1,1]>0).all(),'camera intrinsics') + if key.startswith('mesh_'):object_names.append(key.removeprefix('mesh_')) + proof=receipt['views'][cam] + require(not proof['unresolved'],'unresolved QC components') + media={} + for p in proof['validation']: + if p.get('profile')==components['rgb']['storage']['profile'] and p.get('all_frames_exact') is True:media['rgb']=p + elif p.get('component') in ('depth','depth_valid'):media[p['component']]=p + require(set(media)=={'rgb','depth','depth_valid'},'media roundtrip proof missing') + for key,p in media.items(): + require(p.get('all_frames_exact') is True and re.fullmatch('[0-9a-f]{64}',p.get('decoded_sha256','')) is not None,f'{key}: failed original roundtrip proof') + require((view/'observation'/f'{key}.mkv').stat().st_size==p['bytes'],f'{key}: encoded file size changed since conversion') + result.append({'sequence_id':seq,'camera':cam,'frames':n,'numeric_components':numeric, + 'rgb_source_frames':rgb_count,'depth_source_frames':depth_count,'objects':sorted(object_names)}) + return result + +result=check_sequence('subject1_k2_6') +from warehouse_v1_0 import decoded_digest +receipt=json.loads(receipts['subject1_k2_6'].read_text()) +view=folders['subject1_k2_6']/'cam0' +meta=json.loads((view/'metainfo.json').read_text()) +proofs=receipt['views']['cam0']['validation'] +verified=[] +for name,pix in (('rgb','rgb24'),('depth','gray16le'),('depth_valid','gray')): + p=next(x for x in proofs if (x.get('profile')==meta['components']['rgb']['storage']['profile'] if name=='rgb' else x.get('component')==name)) + digest,size,seconds=decoded_digest(view/'observation'/f'{name}.mkv',pix) + assert digest==p['decoded_sha256'],(name,digest,p['decoded_sha256']) + expected_bytes=expected['subject1_k2_6']*1280*720*({'rgb':3,'depth':4,'depth_valid':1}[name]) + assert size==expected_bytes,(name,size,expected_bytes) + verified.append({'component':name,'decoded_sha256':digest,'decoded_bytes':size,'seconds':seconds}) +page=render(view,out/'subject1_k2_6_cam0_fallback') +json_result={'passed':True,'views':result,'full_decode_comparison':verified,'html':str(page.relative_to(out)), + 'note':'Registered lossless H.264 fallback; all current decoded media digests equal original conversion receipts'} +(out/'H264_FALLBACK_CHECK.json').write_text(json.dumps(json_result,indent=2)+'\n') +print('FALLBACK_PASS',json.dumps(json_result),flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-finalize-quick-validation.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-finalize-quick-validation.py new file mode 100644 index 0000000000000000000000000000000000000000..75a0c5f7db6f94423e22d2e8862125a674841dc6 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-finalize-quick-validation.py @@ -0,0 +1,39 @@ +import datetime,html,json,shutil +from pathlib import Path +from zoneinfo import ZoneInfo +release=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe/H2O/shared-v1.0') +out=release/'doc/validation/final-quick-check' +report=json.loads((out/'QUICK_VALIDATION.json').read_text()) +assert report['failures']==[{'sequence':'subject1_k2_6','error':"ValueError('rgb: failed original roundtrip proof')"}] +fallback=json.loads((out/'H264_FALLBACK_CHECK.json').read_text());assert fallback['passed'] +shutil.copy2(out/'QUICK_VALIDATION.json',out/'INITIAL_CHECKER_ALERT.json') +rows=fallback['views'] +report['checked_sequences']+=1;report['checked_views']+=len(rows) +report['checked_view_frames']+=sum(r['frames'] for r in rows) +report['rgb_source_frames']+=sum(r['rgb_source_frames'] for r in rows) +report['depth_source_frames']+=sum(r['depth_source_frames'] for r in rows) +report['numeric_components']+=sum(r['numeric_components'] for r in rows) +report['samples'].append({'sequence_id':'subject1_k2_6','camera':'cam0','object':'espresso', + 'frames':678,'passed':True,'html':fallback['html'], + 'extra_check':'Full RGB/depth/valid current decoded digests equal original receipts'}) +report['resolved_alerts']=[{'view':'subject1_k2_6/cam0','classification':'Registered lossless H.264 fallback, not missing data or corruption', + 'original_checker_limitation':'First pass selected only FFV1 proofs; fixed to select the profile actually declared by metainfo', + 'followup':'All five cameras rechecked; problematic view RGB, depth and validity fully decoded and matched original SHA256/byte length'}] +report['failures']=[];report['passed']=True +report['time']=datetime.datetime.now(ZoneInfo('Asia/Shanghai')).isoformat() +report['sample_views']=len(report['samples']) +assert report['checked_sequences']==184 and report['checked_views']==920 +assert report['checked_view_frames']==report['rgb_source_frames']==report['depth_source_frames']==571645 +report['rgb_profiles']={} +for meta in (release/'data').glob('*/cam*/metainfo.json'): + name=json.loads(meta.read_text())['components']['rgb']['storage']['profile'] + report['rgb_profiles'][name]=report['rgb_profiles'].get(name,0)+1 +(out/'QUICK_VALIDATION.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n') +summary={k:v for k,v in report.items() if k!='samples'} +(out/'index.html').write_text('H2O 全量后抽样验收

H2O 全量后抽样验收

自动检查通过不等于原始几何标注准确。覆盖四个 subject、八类物体、ego/exo;青色为源手部关节点投影,粉色为源物体点投影,仅用于预览。

'+html.escape(json.dumps(summary,ensure_ascii=False,indent=2))+'
') +operations=release/'script/provenance/operations' +for src in ('h2o-quick-validation.py','h2o-check-fallback.py','h2o-finalize-quick-validation.py'): + shutil.copy2(Path('/tmp')/src,operations/src) +shutil.copy2('/tmp/h2o-quick-validation.log',out/'INITIAL_RUN.log') +shutil.copy2('/tmp/h2o-fallback-check.log',out/'FALLBACK_RUN.log') +print(json.dumps(summary,ensure_ascii=False,indent=2),flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-pipeline-bench-job.sh b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-pipeline-bench-job.sh new file mode 100644 index 0000000000000000000000000000000000000000..5751d4926d5be28c5d00544b5e89f3d19424e827 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-pipeline-bench-job.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +set -u +cd /home/xuzhefeng/Projects/uni-hoi-dataset || exit 1 +case "$1" in + old) code=/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10/frozen-code/scripts/convert_h2o_v1.0.py; extra=();; + v8) code=/tmp/h2o-stream-v8-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 8 --stream-media);; + v8ram) code=/tmp/h2o-stream-v8ram-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 8 --stream-media --ram-stage-dir /dev/shm/xuzhefeng-h2o-pipeline-v8ram-20260930 --ram-stage-gib 32);; + s16) code=/tmp/h2o-stream-s16-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 16 --stream-media --ffv1-slices 16 --ram-stage-dir /dev/shm/xuzhefeng-h2o-pipeline-s16-20260930 --ram-stage-gib 32);; + pipeline) code=/tmp/h2o-stream-pipeline-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 16 --camera-pipeline --stream-media --ffv1-slices 16 --ram-stage-dir /dev/shm/xuzhefeng-h2o-pipeline-overlap-20260930 --ram-stage-gib 32);; + process) code=/tmp/h2o-process-pipeline-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 16 --view-backend processes --camera-pipeline --stream-media --ffv1-slices 16 --ram-stage-dir /dev/shm/xuzhefeng-h2o-pipeline-process-20260930 --ram-stage-gib 32);; + v16) code=/tmp/h2o-stream-v8-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 16 --stream-media);; + *) exit 2;; +esac +root=/data/xuzhefeng/Datasets/uni-hoi-h2o-pipeline-bench-20260930 +caseout="$root/$1" +mkdir -p "$caseout/scratch" +export TMPDIR="$caseout/scratch" PYTHONUNBUFFERED=1 +cg=$(awk -F: '$1=="0" {print $3}' /proc/self/cgroup) +cat "/sys/fs/cgroup$cg/cpu.stat" > "$caseout/cpu.start" +date -Is > "$caseout/start" +.venv/bin/python "$code" --root "$root/raw" --out "$caseout" --workers 4 --codec-threads 10 --decode-threads 10 --depth-threads 4 --max-frames 200 --mano-dir /home/xuzhefeng/Projects/WiLoR/mano_data "${extra[@]}" > "$caseout/convert.log" 2>&1 +code=$? +cat "/sys/fs/cgroup$cg/cpu.stat" > "$caseout/cpu.end" +printf '%s\n' "$code" > "$caseout/exit" +exit "$code" diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-pipeline-benchmark.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-pipeline-benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..1bc90e6ead0eca79856b81000c60bff9d3b4f8b5 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-pipeline-benchmark.py @@ -0,0 +1,48 @@ +import datetime,json,os,subprocess,time +from pathlib import Path +root=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-pipeline-bench-20260930') +cpus=os.cpu_count() +records=[] +for mode in ('old','v8'): + unit=f'h2o-pipeline-{mode}-20260930.scope' + begin=time.monotonic() + proc=subprocess.Popen(['systemd-run','--user','--scope','--unit='+unit,'-p','CPUAccounting=yes', + '/bin/bash','/tmp/h2o-pipeline-bench-job.sh',mode]) + path=Path(f'/sys/fs/cgroup/user.slice/user-{os.getuid()}.slice/user@{os.getuid()}.service/app.slice/{unit}') + samples=[] + while proc.poll() is None: + try: + stat=dict(line.split() for line in (path/'cpu.stat').read_text().splitlines()) + samples.append((time.monotonic()-begin,int(stat['usage_usec']))) + except (FileNotFoundError,PermissionError):pass + time.sleep(0.5) + elapsed=time.monotonic()-begin + assert proc.returncode==0,(mode,(root/mode/'convert.log').read_text()[-3000:]) + def usage(name):return int(dict(line.split() for line in (root/mode/name).read_text().splitlines())['usage_usec']) + total=usage('cpu.end')-usage('cpu.start') + peak=max(((b[1]-a[1])/(b[0]-a[0])/1e6/cpus*100 for a,b in zip(samples,samples[10:])),default=0) + row=dict(mode=mode,seconds=elapsed,cpu_seconds=total/1e6,cpu_percent_machine=total/elapsed/1e6/cpus*100, + peak_5s_cpu_percent_machine=peak,samples=samples) + records.append(row) + (root/'performance.json').write_text(json.dumps(records,indent=2)+'\n') + print(json.dumps({k:v for k,v in row.items() if k!='samples'}),flush=True) +# Prove actual media and every numeric tensor match, not just wall-clock speed. +os.environ['HAND_WAREHOUSE_FFMPEG_THREADS'] = '10' +import sys +sys.path.insert(0,'/tmp/h2o-stream-v8-recovery/scripts') +from warehouse_v1_0 import decoded_digest,validate_view +import torch +for view in sorted((root/'old/H2O/shared-v1.0/data').glob('*/cam*')): + rel=view.relative_to(root/'old/H2O/shared-v1.0/data') + candidate=root/'v8/H2O/shared-v1.0/data'/rel + assert validate_view(candidate)['validated'] + for name,pix in (('rgb','rgb24'),('depth','gray16le'),('depth_valid','gray')): + aa=decoded_digest(view/'observation'/f'{name}.mkv',pix)[:2] + bb=decoded_digest(candidate/'observation'/f'{name}.mkv',pix)[:2] + assert aa==bb,(rel,name) + for pt in view.rglob('*.pt'): + aa=torch.load(pt,weights_only=True) + bb=torch.load(candidate/pt.relative_to(view),weights_only=True) + assert aa.shape==bb.shape and aa.dtype==bb.dtype and aa.numpy().tobytes()==bb.numpy().tobytes(),(rel,pt) +print('PASS all 10 real views: full RGB/depth/valid decoded digests and every numeric tensor match',flush=True) +(root/'validation.exit').write_text('0\n') diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-pipeline-process-benchmark.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-pipeline-process-benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..b47120c02f15314c732031cbc4b05996c75b2c3e --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-pipeline-process-benchmark.py @@ -0,0 +1,48 @@ +import datetime,json,os,subprocess,time +from pathlib import Path +root=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-pipeline-bench-20260930') +cpus=os.cpu_count() +records=[] +for mode in ('process',): + unit=f'h2o-pipeline-{mode}-20260930.scope' + begin=time.monotonic() + proc=subprocess.Popen(['systemd-run','--user','--scope','--unit='+unit,'-p','CPUAccounting=yes', + '/bin/bash','/tmp/h2o-pipeline-bench-job.sh',mode]) + path=Path(f'/sys/fs/cgroup/user.slice/user-{os.getuid()}.slice/user@{os.getuid()}.service/app.slice/{unit}') + samples=[] + while proc.poll() is None: + try: + stat=dict(line.split() for line in (path/'cpu.stat').read_text().splitlines()) + samples.append((time.monotonic()-begin,int(stat['usage_usec']))) + except (FileNotFoundError,PermissionError):pass + time.sleep(0.5) + elapsed=time.monotonic()-begin + assert proc.returncode==0,(mode,(root/mode/'convert.log').read_text()[-3000:]) + def usage(name):return int(dict(line.split() for line in (root/mode/name).read_text().splitlines())['usage_usec']) + total=usage('cpu.end')-usage('cpu.start') + peak=max(((b[1]-a[1])/(b[0]-a[0])/1e6/cpus*100 for a,b in zip(samples,samples[10:])),default=0) + row=dict(mode=mode,seconds=elapsed,cpu_seconds=total/1e6,cpu_percent_machine=total/elapsed/1e6/cpus*100, + peak_5s_cpu_percent_machine=peak,samples=samples) + records.append(row) + (root/'performance-process.json').write_text(json.dumps(records,indent=2)+'\n') + print(json.dumps({k:v for k,v in row.items() if k!='samples'}),flush=True) +# Prove actual media and every numeric tensor match, not just wall-clock speed. +os.environ['HAND_WAREHOUSE_FFMPEG_THREADS'] = '10' +import sys +sys.path.insert(0,'/tmp/h2o-process-pipeline-recovery/scripts') +from warehouse_v1_0 import decoded_digest,validate_view +import torch +for view in sorted((root/'old/H2O/shared-v1.0/data').glob('*/cam*')): + rel=view.relative_to(root/'old/H2O/shared-v1.0/data') + candidate=root/'process/H2O/shared-v1.0/data'/rel + assert validate_view(candidate)['validated'] + for name,pix in (('rgb','rgb24'),('depth','gray16le'),('depth_valid','gray')): + aa=decoded_digest(view/'observation'/f'{name}.mkv',pix)[:2] + bb=decoded_digest(candidate/'observation'/f'{name}.mkv',pix)[:2] + assert aa==bb,(rel,name) + for pt in view.rglob('*.pt'): + aa=torch.load(pt,weights_only=True) + bb=torch.load(candidate/pt.relative_to(view),weights_only=True) + assert aa.shape==bb.shape and aa.dtype==bb.dtype and aa.numpy().tobytes()==bb.numpy().tobytes(),(rel,pt) +print('PASS all 10 real views: full RGB/depth/valid decoded digests and every numeric tensor match',flush=True) +(root/'validation-process.exit').write_text('0\n') diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-prepare-pipeline-bench.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-prepare-pipeline-bench.py new file mode 100644 index 0000000000000000000000000000000000000000..6fbe75024965020f88eb282f2eeb448d491b8639 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-prepare-pipeline-bench.py @@ -0,0 +1,28 @@ +import json,os,tarfile,shutil +from pathlib import Path +root=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-pipeline-bench-20260930') +root.mkdir(exist_ok=True) +raw=root/'raw'; raw.mkdir(exist_ok=True) +old=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10') +records=[] +for subj in ('subject3','subject4'): + subject=next((old/'scratch').glob('h2o-source-*/'+subj)) + sequences=[p for p in subject.glob('*/*') if all((p/f'cam{i}/rgb/000199.png').is_file() for i in range(5))] + assert sequences, (subj,subject) + seq=sequences[0] + snapshot=root/'input-snapshot'/subj/seq.relative_to(subject) + for src in seq.glob('cam*/*/*'): + if src.is_file() and src.parent.name in ('rgb','depth','cam_pose','hand_pose','hand_pose_mano','obj_pose','obj_pose_rt') and int(src.stem)<200: + dest=snapshot/src.relative_to(seq);dest.parent.mkdir(parents=True,exist_ok=True) + os.link(src,dest) + for src in seq.glob('cam*/cam_intrinsics.txt'): + dest=snapshot/src.relative_to(seq);dest.parent.mkdir(parents=True,exist_ok=True);os.link(src,dest) + archive=raw/f'{subj}_v1_1.tar.gz' + with tarfile.open(archive,'w:gz',compresslevel=0) as tf: + tf.add(snapshot,arcname=str(snapshot.relative_to(root/'input-snapshot'))) + records.append({'sequence':str(snapshot.relative_to(root/'input-snapshot')),'frames':200,'views':5,'archive':str(archive), + 'origin':str(seq),'gzip_compression_level':0}) +for name in ('object.zip','label_split.zip'): + os.link(Path('/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data')/name,raw/name) +(root/'input-manifest.json').write_text(json.dumps(records,indent=2)+'\n') +print('PREPARED',records,flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-prepare-process-full.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-prepare-process-full.py new file mode 100644 index 0000000000000000000000000000000000000000..a3b73425e82cadf972633e303292f12f4f823fbf --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-prepare-process-full.py @@ -0,0 +1,45 @@ +"""Preserve complete persistent views; frozen process pipeline only changes execution/storage work.""" +import datetime,json,os,shutil +from pathlib import Path +old=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10') +new=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe') +new.mkdir() +shutil.copytree('/tmp/h2o-process-pipeline-recovery',new/'frozen-code') +release=new/'H2O/shared-v1.0' +for directory in ('data','doc/validation','script/provenance/previous-run','script/provenance/operations'): + (release/directory).mkdir(parents=True,exist_ok=True) +history=release/'script/provenance/previous-run' +shutil.copytree(old/'H2O/shared-v1.0/script',history/'script') +shutil.copytree(old/'frozen-code/docs',history/'docs') +for name in ('full.log','full.status','run-full.sh'): + shutil.copy2(old/name,history/name) +records=[] +for record in sorted((old/'H2O/shared-v1.0/doc').glob('*.build.json')): + build=json.loads(record.read_text());seq=build['sequence_id'] + assert Path(seq).name==seq and seq not in ('.','..') + assert set(build['views'])=={f'cam{i}' for i in range(5)} + folder=old/'H2O/shared-v1.0/data'/seq + for cam in build['views']:assert (folder/cam/'metainfo.json').is_file() + shutil.copytree(folder,release/'data'/seq,copy_function=os.link) + shutil.copy2(record,release/'doc'/record.name) + records.append({'sequence_id':seq,'original_script_sha256':build['scripts']}) +manifest={'time':datetime.datetime.now().astimezone().isoformat(),'source_run':str(old),'destination_run':str(new), + 'reason':'Native bytes unchanged; process/view pipeline, streaming RAW and bounded RAM staging', + 'target_cpu_percent_machine':80,'cpu_limit':None,'reused_sequences':records, + 'reuse':'Read-only hardlinks; original build records retained; source frame/component SHA256 checked on resume', + 'previous_run_provenance':'script/provenance/previous-run'} +(release/'doc/RESTART_PROVENANCE.json').write_text(json.dumps(manifest,indent=2)+'\n') +operations=release/'script/provenance/operations' +for name in ('h2o-prepare-process-full.py','h2o-switch-process-full.sh','h2o-pipeline-benchmark.py', + 'h2o-pipeline-process-benchmark.py','h2o-pipeline-bench-job.sh','h2o-prepare-pipeline-bench.py', + 'h2o-process-final-tests.log','h2o-shared-final-tests.log'): + shutil.copy2(Path('/tmp')/name,operations/name) +bench=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-pipeline-bench-20260930') +for p in bench.glob('performance*.json'):shutil.copy2(p,release/'doc/validation'/p.name) +shutil.copy2(bench/'input-manifest.json',release/'doc/validation/PIPELINE_BENCH_INPUTS.json') +shutil.copy2('/tmp/h2o-pipeline-process-benchmark.log',release/'doc/validation/PIPELINE_BENCHMARK.log') +shutil.copy2('/tmp/h2o-runtime-profile.log',release/'doc/validation/BEFORE_RUNTIME_PROFILE.log') +shutil.copy2('/tmp/h2o-current-iostat.log',release/'doc/validation/BEFORE_IOSTAT.log') +for destination in (new/'run-full.sh',release/'script/run-full.sh'): + shutil.copy2('/tmp/h2o-run-process-full.sh',destination) +print('REUSED_SEQUENCES',len(records),'REUSED_VIEWS',5*len(records),flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-process-final-tests.log b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-process-final-tests.log new file mode 100644 index 0000000000000000000000000000000000000000..fdf27a753f61c8755e23e54721f766549a081d48 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-process-final-tests.log @@ -0,0 +1,39 @@ +Converted subject1/h1/0 +Converted subject2/h1/0 +Converted subject3/h1/0 +Converted subject4/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Converted subject3/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +Verified existing subject1/h1/0 +Verified existing subject3/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Verified existing subject2/h1/0 +Verified existing subject4/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Archive subject3_v1_1.tar.gz: 1 sequences +Archive subject4_v1_1.tar.gz: 1 sequences +Camera-order fallback: subject1/h1/0 +Converted subject1/h1/0 +Converted subject2/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +PASS H2O pipe RGB/depth, RAM annotations, shared view pool 1/4/8, four archive workers, codec/decode 1/4/10, ordered depth 1/2/4 and missing-depth preservation, no resume PNG writes, RGB FFV1-only, depth and persistent QC diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-quick-validation.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-quick-validation.py new file mode 100644 index 0000000000000000000000000000000000000000..45efdc32457710d01161b4ba227f903a941b1611 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-quick-validation.py @@ -0,0 +1,161 @@ +"""Full coverage/numeric audit, plus representative persisted-media QC and offline HTML.""" +import os +for key in ('OMP_NUM_THREADS','OPENBLAS_NUM_THREADS','MKL_NUM_THREADS','NUMEXPR_NUM_THREADS'): + os.environ[key]='1' +os.environ['HAND_WAREHOUSE_FFMPEG_THREADS']='4' +os.environ.pop('HAND_WAREHOUSE_FFV1_SLICES',None) +os.environ.pop('HAND_WAREHOUSE_MEDIA_TMPDIR',None) +import collections,datetime,hashlib,html,json,re,sys,time,zipfile +from concurrent.futures import ThreadPoolExecutor,as_completed +from pathlib import Path +from zoneinfo import ZoneInfo +import numpy as np +import torch +root=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe') +release=root/'H2O/shared-v1.0' +sys.path.insert(0,str(root/'frozen-code/scripts')) +from warehouse_v1_0 import SCHEMA,check_transform,check_valid_policy,check_view_type,safe_member,sha256 +from render_h2o_validation import render +out=release/'doc/validation/final-quick-check' +out.mkdir(exist_ok=True) +torch.set_num_threads(1) +started=time.monotonic() +expected={} +with zipfile.ZipFile('/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/label_split.zip') as z: + for name in z.namelist(): + if '/action_' not in name:continue + for line in z.read(name).decode().splitlines(): + fields=line.split() + if len(fields)>1 and fields[1]!='path': + seq=fields[1].replace('/','_') + expected[seq]=max(expected.get(seq,0),int(fields[-1])+1) +folders={p.name:p for p in (release/'data').iterdir() if p.is_dir()} +assert set(folders)==set(expected),(sorted(set(expected)-set(folders)),sorted(set(folders)-set(expected))) +assert len(expected)==184 and sum(expected.values())==114329 +receipts={p.name.removesuffix('.build.json'):p for p in (release/'doc').glob('*.build.json')} +assert set(receipts)==set(expected) +assert 'EXIT=0' in (root/'full.status').read_text() +failures=[] +rows=[] +def require(ok,message): + if not ok:raise ValueError(message) +def load(path): + def cpu(storage,location): + require(location=='cpu',f'non-CPU storage: {path}') + return storage + obj=torch.load(path,map_location=cpu,weights_only=True) + require(type(obj) is torch.Tensor,f'non-tensor: {path}') + return obj.numpy() +def check_sequence(seq): + folder=folders[seq];n=expected[seq] + require({p.name for p in folder.iterdir() if p.is_dir()}=={f'cam{i}' for i in range(5)},'five-camera coverage') + receipt=json.loads(receipts[seq].read_text()) + require(receipt['sequence_id']==seq and set(receipt['views'])=={f'cam{i}' for i in range(5)},'build receipt') + result=[] + for i in range(5): + cam=f'cam{i}';view=folder/cam + meta=json.loads((view/'metainfo.json').read_text()) + require((meta['dataset_id'],meta['sequence_id'],meta['camera_id'],meta['num_frames'])==('H2O',seq,cam,n),'header/timeline') + require(meta['view_type']==('ego' if i==4 else 'exo'),'view role') + require(meta['sampling']['selection']=={'max_frames':None,'views':None},'unexpected subsampling') + check_view_type(meta) + components=meta['components'] + require(all(components[k].get('available') for k in ('rgb','depth','mano','keypoints_xyz','intrinsic','extrinsic')),'required modality absent') + require(not components['segment']['available'] and not components['relations']['available'],'unexpected synthesized component') + rgb_sources=[];depth_sources=[];rgb_count=depth_count=0 + with (view/'camera/frames.jsonl').open() as inp: + count=0 + for index,line in enumerate(inp): + f=json.loads(line) + require(f['frame_index']==index and f['source_frame_id']==index,'source frame index') + require(f['sync_id']==f'{seq.replace("_","/")}:{index}','synchronization ID') + sources=f['component_sources'] + for kind,loc in sources.items(): + require(re.fullmatch('[0-9a-f]{64}',loc.get('sha256','')) is not None,f'source SHA256: {kind}') + require(f'/{cam}/' in loc.get('member',''),'wrong source camera') + rgb_sources.append('rgb' in sources);depth_sources.append('depth' in sources) + rgb_count+=rgb_sources[-1];depth_count+=depth_sources[-1];count+=1 + require(count==n,'frames.jsonl length') + numeric=0 + object_names=[] + for key,c in components.items(): + if not c['available']:continue + for field in ('data_ref','valid_ref','mapping_ref'): + if c.get(field): + path=safe_member(view,c[field]) + require(path.is_file() and path.stat().st_size>0,f'missing/empty {c[field]}') + schema=SCHEMA['components'][c['schema_id']] + if c.get('valid_policy'):check_valid_policy(c,n) + valid=load(view/c['valid_ref']) if c.get('valid_ref','').endswith('.pt') else None + if valid is not None: + shape=schema.get('valid_shape') + require(valid.dtype==np.bool_ and valid.shape[0]==n,f'{key}: validity dtype/timeline') + if shape:require(len(shape)==valid.ndim and all(not isinstance(s,int) or valid.shape[j]==s for j,s in enumerate(shape)),f'{key}: validity shape') + if key=='rgb':require(np.array_equal(valid,np.asarray(rgb_sources)), 'RGB existence validity mismatch') + if c['data_ref'].endswith('.pt'): + arr=load(view/c['data_ref']);numeric+=1 + require(arr.dtype==np.float32 and arr.shape[0]==n,f'{key}: dtype/timeline') + shape=schema.get('shape') + if shape:require(len(shape)==arr.ndim and all(not isinstance(s,int) or arr.shape[j]==s for j,s in enumerate(shape)),f'{key}: tensor shape') + if valid is not None: + require(arr.shape[:valid.ndim]==valid.shape and np.isfinite(arr[valid]).all() and np.isnan(arr[~valid]).all(),f'{key}: finite/NaN validity semantics') + if c['schema_id'] in ('transform/se3/v1','object/rigid/v1'):check_transform(arr[valid]) + if key=='intrinsic':require(np.allclose(arr[:,2],[0,0,1]) and (arr[:,0,0]>0).all() and (arr[:,1,1]>0).all(),'camera intrinsics') + if key.startswith('mesh_'):object_names.append(key.removeprefix('mesh_')) + proof=receipt['views'][cam] + require(not proof['unresolved'],'unresolved QC components') + media={} + for p in proof['validation']: + if p.get('profile')==components['rgb']['storage']['profile'] and p.get('all_frames_exact') is True:media['rgb']=p + elif p.get('component') in ('depth','depth_valid'):media[p['component']]=p + require(set(media)=={'rgb','depth','depth_valid'},'media roundtrip proof missing') + for key,p in media.items(): + require(p.get('all_frames_exact') is True and re.fullmatch('[0-9a-f]{64}',p.get('decoded_sha256','')) is not None,f'{key}: failed original roundtrip proof') + require((view/'observation'/f'{key}.mkv').stat().st_size==p['bytes'],f'{key}: encoded file size changed since conversion') + result.append({'sequence_id':seq,'camera':cam,'frames':n,'numeric_components':numeric, + 'rgb_source_frames':rgb_count,'depth_source_frames':depth_count,'objects':sorted(object_names)}) + return result +with ThreadPoolExecutor(max_workers=4) as pool: + jobs={pool.submit(check_sequence,seq):seq for seq in sorted(expected)} + for job in as_completed(jobs): + seq=jobs[job] + try:rows.extend(job.result()) + except Exception as exc:failures.append({'sequence':seq,'error':repr(exc)}) + if len(rows)%100==0:print('STRUCTURAL_VIEWS',len(rows),'FAILURES',len(failures),flush=True) +print('STRUCTURAL_COMPLETE',len(rows),'FAILURES',failures,flush=True) +# Balance subjects while covering all eight source object classes; include matching exo views. +objects=('book','espresso','lotion','spray','milk','cocoa','chips','cappuccino') +selected=[] +for j,name in enumerate(objects): + subject=f'subject{j%4+1}_' + candidates=[r for r in rows if r['camera']=='cam4' and name in r['objects']] + require(candidates,f'no output for object {name}') + own=[r for r in candidates if r['sequence_id'].startswith(subject)] + r=min(own or candidates,key=lambda x:(x['frames'],x['sequence_id'])) + selected.append((r['sequence_id'],'cam4',name)) + selected.append((r['sequence_id'],'cam0',name)) +samples=[] +def full_sample(item): + seq,cam,name=item + view=folders[seq]/cam + destination=out/f'{seq}_{cam}' + page=render(view,destination) # Reuse persisted contract QC, depth semantics, frame snapshots, native mesh preview. + return {'sequence_id':seq,'camera':cam,'object':name,'frames':expected[seq], + 'passed':True,'html':str(page.relative_to(out))} +with ThreadPoolExecutor(max_workers=4) as pool: + jobs={pool.submit(full_sample,item):item for item in selected} + for job in as_completed(jobs): + item=jobs[job] + try:samples.append(job.result());print('SAMPLE_PASS',item,flush=True) + except Exception as exc:failures.append({'sample':item,'error':repr(exc)});print('SAMPLE_FAIL',item,repr(exc),flush=True) +report={'time':datetime.datetime.now(ZoneInfo('Asia/Shanghai')).isoformat(),'elapsed_seconds':time.monotonic()-started, + 'release':str(release),'passed':not failures,'scope':'All sequence/camera coverage, frame/source manifests, all numeric tensors and original media receipts; 16 representative full persisted-view QC checks and offline previews. Not a new all-video source-pixel comparison.', + 'expected_sequences':len(expected),'expected_sync_frames':sum(expected.values()), + 'checked_sequences':len(rows)//5,'checked_views':len(rows),'checked_view_frames':sum(r['frames'] for r in rows), + 'rgb_source_frames':sum(r['rgb_source_frames'] for r in rows),'depth_source_frames':sum(r['depth_source_frames'] for r in rows), + 'numeric_components':sum(r['numeric_components'] for r in rows),'samples':samples,'failures':failures, + 'next_step':'Human inspection of representative offline HTML; automatic QC is not proof of source geometric accuracy.'} +(out/'QUICK_VALIDATION.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n') +(out/'index.html').write_text('H2O 全量后抽样验收

H2O 全量后抽样验收

自动检查通过不等于源几何标注正确;以下为四个 subject、八类物体、ego/exo 的源数据预览。

'+html.escape(json.dumps({k:v for k,v in report.items() if k not in ('samples',)},ensure_ascii=False,indent=2))+'
') +print('FINAL_REPORT',json.dumps({k:v for k,v in report.items() if k!='samples'},ensure_ascii=False),flush=True) +raise SystemExit(0 if report['passed'] else 1) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-shared-final-tests.log b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-shared-final-tests.log new file mode 100644 index 0000000000000000000000000000000000000000..9e8b3fadfef4187f122c1bcd295692cddf1d2523 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-shared-final-tests.log @@ -0,0 +1 @@ +PASS: RGB full/prefix hashes, source depth frames, depth/valid/segment bits and missing-frame rejection diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-switch-process-full.sh b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-switch-process-full.sh new file mode 100644 index 0000000000000000000000000000000000000000..86ad70c2cc2df78859680827dad7973b5b14c576 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/h2o-switch-process-full.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -euo pipefail +cd /home/xuzhefeng/Projects/uni-hoi-dataset +test "$(cat /tmp/h2o-process-final-tests.exit)" = 0 +test "$(cat /tmp/h2o-shared-final-tests.exit)" = 0 +test "$(cat /tmp/h2o-pipeline-process-benchmark.exit)" = 0 +test ! -e /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe +old=/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10 +printf '\nRECONFIGURE=%s REASON=process16_camera_pipeline_ram32_streaming\n' "$(date -Is)" >> "$old/full.status" +systemctl --user stop h2o-full-d10-20260930.scope +.venv/bin/python /tmp/h2o-prepare-process-full.py +systemd-run --user --scope --unit=h2o-full-process16-20260930 -p CPUAccounting=yes /bin/bash /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe/run-full.sh diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/watch-steady-cpu.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/watch-steady-cpu.py new file mode 100644 index 0000000000000000000000000000000000000000..06472a5229fde6c7b8ffa97c3eb92dc16e1df864 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/operations/watch-steady-cpu.py @@ -0,0 +1,38 @@ +"""Measure the whole process tree only after conversion FFmpeg is active; no CPU-fill work.""" +import datetime,json,os,time +from pathlib import Path +unit='h2o-full-process16-20260930.scope' +cg=Path(f'/sys/fs/cgroup/user.slice/user-{os.getuid()}.slice/user@{os.getuid()}.service/app.slice/{unit}') +root=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe') +report=root/'H2O/shared-v1.0/doc/validation/STEADY_CPU_5MIN.json' +start_wait=time.monotonic() +while time.monotonic()-start_wait<7200: + if not (cg/'cgroup.procs').exists(): + print('Scope exited before a steady conversion sample',flush=True);raise SystemExit(1) + ffmpeg=False + for pid in (cg/'cgroup.procs').read_text().split(): + try:ffmpeg |= Path('/proc',pid,'comm').read_text().strip()=='ffmpeg' + except FileNotFoundError:pass + if ffmpeg:break + time.sleep(5) +else: + print('No conversion FFmpeg within two hours; no steady CPU claim made',flush=True);raise SystemExit(2) +def sample(): + values=dict(line.split() for line in (cg/'cpu.stat').read_text().splitlines()) + return time.monotonic(),int(values['usage_usec']) +begin=datetime.datetime.now().astimezone().isoformat() +samples=[sample()] +for _ in range(60): + time.sleep(5) + try:samples.append(sample()) + except FileNotFoundError: + print('Scope exited during sample; inspect full.status',flush=True);raise SystemExit(1) +cpus=os.cpu_count() +intervals=[(b[1]-a[1])/(b[0]-a[0])/1e6/cpus*100 for a,b in zip(samples,samples[1:])] +result={'start':begin,'end':datetime.datetime.now().astimezone().isoformat(),'logical_cpus':cpus, + 'whole_scope_cpu_percent_machine':(samples[-1][1]-samples[0][1])/(samples[-1][0]-samples[0][0])/1e6/cpus*100, + 'highest_5sec_cpu_percent_machine':max(intervals),'lowest_5sec_cpu_percent_machine':min(intervals), + 'target_percent':80,'intervals_percent_machine':intervals,'samples':samples, + 'scope':unit,'includes':'All scope threads and child processes, including children already exited'} +report.write_text(json.dumps(result,indent=2)+'\n') +print(json.dumps({k:v for k,v in result.items() if k not in ('samples','intervals_percent_machine')}),flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/docs/CONTRACT.md b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/docs/CONTRACT.md new file mode 100644 index 0000000000000000000000000000000000000000..f756d711647e109b6bb732ce1b9c84111730489d --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/docs/CONTRACT.md @@ -0,0 +1,457 @@ +# 手物数据仓库统一约定 v1.0 + +格式版本:`hand-warehouse/1.0`。存储约定:`lossless-video-2026-09-18`。 + +范围限于手物交互重建。按本任务纳入的源模态转换,不要求每个数据集填满所有组件。缺失模态、尚未下载、语义未核实分别报告,不能互相替代。 + +本文定义各字段的含义与使用规则,机器可读注册表见 [schema.json](schema.json)。两者互相补充;如有冲突,应先核实并统一定义。 + +## 1. 目录 + +```text +hand-datasets/ + / + raw/ + doc/ # 官方说明、来源与校验记录 + script/ # 官方下载脚本、必要包装脚本 + data/ # 保留原始包,不原地解压或改写 + / + doc/ # 发布说明、schema、来源清单 + script/ # 转换、校验脚本及运行配置 + data/ + / + / + metainfo.json + observation/ + rgb.mkv + rgb_valid.pt + depth.mkv # float32 深度的可逆视频编码 + depth_valid.mkv # 逐像素 bool 的无损视频编码 + camera/ + frames.jsonl + intrinsic.pt + intrinsic_valid.pt + extrinsic.pt + extrinsic_valid.pt + annotation/ + mano/ + motion.pt + motion_valid.pt + visibility.pt + keypoints/ + uv.pt + uv_valid.pt + xyz.pt + xyz_valid.pt + visibility.pt # 源数据有时提供 + object/ + / + assets/ # 该物体的网格、材质、纹理及部件资产 + .obj + pose.pt + pose_valid.pt + visibility.pt + metainfo.json # 物体身份、类别、mesh、尺寸与部件引用 + articulation.json + keypoints/ + vertex_part_ids.pt + joint_state.pt + joint_state_valid.pt + parts//pose.pt + parts//pose_valid.pt + segment/ + mask.mkv + mask_valid.pt + instances.jsonl + contact/ + relations.jsonl + __/ # 对应实体间的距离/接触区域 +``` + +目录展示可能存在的组件,不要求填满。具体文件、字段和缺省规则分别见后续对应小节。原始包的解压发生在临时工作区,raw 内原始包保持不变。 + +## 2. 相机视图的 metainfo.json + +### 2.1 顶层字段与发布信息 + +每个相机视图必须有 `metainfo.json`。以下字段除另行说明外均为必填: + +| 字段 | 填写内容 | +|---|---| +| schema_version | 结构版本,本版为 `hand-warehouse/1.0` | +| dataset_id | 数据集的逻辑标识 | +| release_id | 本次数据发布版本,对应目录中的 dataset_version | +| sequence_id | 所属序列或独立图片样本的标识 | +| camera_id | 当前相机视图标识 | +| sample_type | `image` 或 `video`,规则见 2.2 | +| num_frames | 当前视图帧数 T,所有随帧组件按同一时间轴组织 | +| hand_slots | 固定为 `["left", "right"]`;解剖学左右的使用规则见 5.1 | +| sampling | 采样类型、源 FPS、帧索引引用及选择策略,见 2.2 | +| camera | 当前相机模型与图像尺寸,见 2.3 | +| components | 实际提供的组件及其文件、schema、有效性和来源,见 2.5 | +| split | `train/val/test/unknown`,划分协议见 2.4 | +| view_type | 可选,`ego/exo/unknown` | + +`dataset_version` 是数据发布版本;`schema_version` 是结构版本,两者独立。原始包校验摘要、官方来源和转换配置应记录在发布清单中。解压发生在临时工作区,原始包保持不变。 + +### 2.2 图片、视频与 sampling + +`sample_type=image`:允许单图 T=1、`sampling.type=single`,也允许将独立图片批量装入一个视频容器,T>1 时 `sampling.type=independent`、`source_fps=null`。分片大小按数据集选择;FreiHAND 默认每片最多 4096 张,训练与评估分开,尾片不补帧。该数量不是其他数据集的强制要求;同批分辨率、相机模型类型及划分协议一致。每行 frames 必须有稳定且唯一的 `sample_id`、原始文件定位;内参、手形状等仍逐帧保留,不能因打包而共享错误的标定或身份。`sequence_id` 在这里仅是批次标识,不代表真实序列;不得按相邻帧推断跟踪、同步或接触延续。源 camera_id、image_variant、split 等随样本变化时放在 frames 的对应字段中。真实采集时间未知则 timestamp_ns=null。合成背景变体不视为真实多相机。 + +`sample_type=video`:`sampling.type=dense/sparse`;`source_fps` 是真实采集 FPS,未知为 null。非连续取样必须保留源帧号和已知源时间,不可用采样后索引除以 FPS 冒充源时间。可另记采样策略与步长。 + +shared 可以仅存所选 RGB 帧对应的数据。OakInk2 图像/动捕不同采样率时用 annotation_matches 明确映射;不要求将未采样动捕点硬塞进 T。多视角身份和源同步关系要保留;选择了哪些帧/相机及原因写在 sampling 中。 + +`sampling.frames_ref` 指向 `camera/frames.jsonl`。帧号、逐帧时间、同步与标注匹配记录的结构见 4.1;MKV 封装时间的约定见 3.1。 + +### 2.3 camera 模型声明 + +`camera` 至少包含 `model`、`schema_id`、`image_size:[W,H]`。模型未知使用 `unknown` 和 `null`,不猜成针孔。实际内参、畸变及外参数组放在 `camera/`,各模型的固定结构见第 4 节。 + +### 2.4 split 与划分协议 + +保留上游划分,不将同一采集序列的相邻帧随意拆到不同集合。 + +有官方划分时必填 split_scheme 和 split_source_locator,split_scheme 区分如 Dex-YCB s0/s1、ARCTIC P1/P2 等选定协议;不知道时 split=unknown 并给理由,不凭空分配。每发布可选择一种协议;存在逐帧差异时 frames 中的 split 覆盖视图默认值,并登记其来源。 + +### 2.5 components 组件登记 + +组件表的键是本发布内唯一名称,例如 `rgb`、`depth`、`mano`、`keypoints_uv`。每个已提供组件声明以下信息;模态特有参数在第 3–5 节对应小节中定义。 + +| 字段 | 约定 | +|---|---| +| available | 本发布是否提供该组件;缺省也表示未提供 | +| schema_id | 已登记的具体存储与语义类型,不得临时创造未登记名称 | +| data_ref | 数据文件路径,相对当前相机视图根目录,使用 POSIX 路径 | +| axes | 数组各维度的含义 | +| valid_ref / valid_axes | 有效性文件及其维度;语义由所属组件规定 | +| storage / valid_storage | 视频数据/视频有效性的存储配置;包含已登记 profile、实际 codec、pixel_format、encoded_size,见 3.1;非视频组件按原数组规则 | +| provenance | source / format_conversion / derived,以及转换或生成方法 | +| source_locator | 原文件、压缩包成员和记录/帧的定位信息 | + +不存在的组件允许缺省或写作 `{ "available": false, "reason": "..." }`,不用引用不存在的文件。静态网格可声明标量有效性;具体见 5.4。观测的 valid 见第 3 节,标注的 valid 与 visibility 区分见 5.1。 + +`provenance.kind` 使用 source/format_conversion/derived,`method` 说明转换或生成方法;发布清单补充脚本版本、参数、输入摘要。`source_locator` 定位到原始文件/压缩包成员和记录、帧号;允许引用有完整溯源清单的前一发布,但链条最终应能回到 raw。不得仅写一个无法定位记录的数据集名字。 + +`.pt` 仅保存 CPU Tensor,不保存 Python 自定义对象;浮点默认 float32,有效性为 bool,浮点无效位置填 NaN。所有随帧数组保留首维 T,单帧也不 squeeze;静态资产按其 schema 单独声明。单位、坐标及固定形状见各组件小节。 + +机器注册表 `schema.json` 中,`components` 固定解码后的数据类型、形状、单位和语义;`storage_profiles` 固定视频内的编码/还原方式。不得临时创造未登记的 schema_id 或 storage.profile。同一语义允许选择其登记的不同无损存储 profile。 + +## 3. observation 观测数据 + +### 3.1 rgb.mkv 与 rgb_valid.pt + +RGB、深度和栅格 mask 在 shared 中统一使用 MKV 视频容器,不展开为逐帧图片或图像 tar。MANO、关键点、位姿等数值标注仍用数组;分割的重叠多边形仍用 JSONL,不为了视频化而有损栅格化。单图可为一帧视频,独立图批量封装规则见 2.2。 + +**无损指共享层不增加信息损失。** 源 JPEG/H.264 等本身可能已是有损编码,原样保留并不恢复已丢失信息;不得重新以有损 JPEG、H.264、H.265、AV1 参数编码。源视频/图片的色彩、位深、分辨率和几何关系不得被静默改变。RGB schema `rgb/uint8/v1` 的统一读取结果是 `[T,H,W,3] uint8`、RGB 通道,有效性仍为 `rgb_valid.pt [T] bool`。超出该 schema 的高位深或 HDR 源必须报告并扩展定义,不能降到 8 位冒充无损。 + +#### 3.1.1 允许的 RGB 存储 profile + +| storage.profile | 编码方式 | 适用规则 | +|---|---|---| +| mkv/mjpeg_copy/v1 | 源 JPEG 压缩帧直接封装成 MJPEG/MKV | 不解码重编码;保持每张 JPEG 码流字节;普通 8 位 JPEG 且 MKV/解码器支持时使用 | +| mkv/source_copy/v1 | 已有视频的 RGB 对应码流直接封装为 MKV | 仅源编码能被 MKV 和选定解码器支持时使用,不伪造帧;需维持正确的呈现顺序与依赖帧 | +| mkv/h264_rgb_lossless/v1 | libx264rgb 的真正无损模式 | 必须 RGB 路径、CRF=0,并通过全帧 RGB 字节比较;不能替换成默认 libx264 YUV420 路径 | +| mkv/ffv1_rgb/v1 | FFV1 的 RGB 可逆编码路径 | 作为通用候选;解码回 RGB 后必须逐字节相同,不做色度降采样 | + +优先尝试源码流直接封装;不能封装或需要选择稀疏帧时,比较 FFV1 与无损 RGB H.264。对完整待发布片段,只在通过无损验收的候选中选择文件较小者,不假设某个编码器总最小;编码时间和随机读取代价记入构建记录。中间候选不作为 shared 多份常驻。H.264 跨帧压缩允许较长 GOP,必须记录 GOP/关键帧间隔,随机取帧需从前一关键帧正确解码,不能把 seek 返回的近似帧当目标帧。 + +普通源视频可以保留它已有的有损码流,但不允许新增有损重编码。源是 VRS 等记录容器时,先查明图像流实际编码:已有兼容 JPEG/视频包可直接提取封装,否则解码后使用真正无损编码;不把整个 VRS 改后缀当 MKV。PNG 不要求直接塞进 MKV,可选上表两种无损重编码方式。 + +#### 3.1.2 视频配置与校验 + +每个视频组件在 metainfo 中登记 `storage`,至少包含: + +| 字段 | 内容 | +|---|---| +| profile | 上述登记的存储 profile;语义仍由组件 schema_id 指定 | +| codec | 文件中实际 codec,例如 mjpeg、h264、ffv1;source_copy 必须写实际 codec | +| pixel_format | 实际编码像素格式;不得仅凭编码器参数猜测 | +| encoded_size | 视频物理像素尺寸 `[width,height]`;深度可能不同于逻辑尺寸,见 3.2 | +| decoder | 解码器名称、版本,以及颜色矩阵/范围/旋转处理等实际像素解释配置;未知的源色彩声明 unknown,不擅自称为 sRGB | +| encoder_parameters | 重编码时的编码器、版本、无损模式和 GOP 等参数;直接封装时记录 stream_copy | +| source_lossy | 源是否已有损:true / false / unknown;不是共享层再有损编码的许可 | + +无损重新编码的 RGB 必须使用同一固定解码配置,比较**全部帧**的统一 RGB 字节、数量及顺序。MJPEG-copy 不重新编码,生产校验采用 `jpeg-packets-all-rgb-sample16/v1`:从 MKV 逐包取回,对全部源 JPEG 的 SHA256、数量、顺序和图像尺寸进行精确核对;每视图另用同一固定解码配置比较最多 16 帧的源与目标 RGB 字节(含首尾与四分位位置,其余由固定种子抽取)。记录策略、实际索引、种子与结果;不足 16 帧时全查。试点与最终完整序列随机抽查,对选中视图的全部帧复核解码 RGB。历史已做全帧像素检查的证明继续保留。 + +逐包一致与像素抽查的范围必须分别声明,不能将抽查写成全量像素检查。不能用 PSNR 高、视觉相似、编码器参数称为 lossless 等替代精确检查。同时保留源编码的色彩标记和必要元数据;原图有 EXIF/色彩/方向等元数据时保留 raw 和必要来源信息;不能静默自动旋转图像而不更新像素对应与标定。以上加速策略仅适用于原 JPEG 码流直接封装,不适用于深度、标签或重新编码的 RGB。 + +所有共享视频的呈现帧顺序与统一 frame_index 一一对应,每个栅格组件恰好 T 帧。MKV 的 `storage_fps` 只服务封装,声明 `timebase_role=index_only`;source_copy 可以保留源 PTS 以避免改坏码流,但真实时间与标注对齐仍以 frames 为准。未知真实时间保留 null。缺失某帧组件时保留索引位置并使用该组件的无效占位/valid 标识,不删帧;不能以重复相邻图像冒充已知观测。 + +### 3.2 depth.mkv 与 depth_valid.mkv + +深度语义仍是 `depth/z_float32/v1`:统一读取结果 `[T,H,W] float32`,米制相机 Z 分量,`depth_type=z`。有效深度有限且大于 0,无效位置为 NaN。`depth_origin=measured/rendered/unknown` 必填,来源不明时 unknown。默认与 RGB 共用像素网格及相机参考系,不处理未注册 RGB-D。射线距离必须依据源定义转换成 z,不能只改声明。 + +#### 3.2.1 float32 的可逆视频编码 + +采用 `mkv/depth_float32_bits/v1`:**不是把深度量化成 uint16**,而是将规范化后每个 IEEE-754 float32 的完整 32 位拆成两个 uint16,使用 FFV1 gray16le 保存。视频物理尺寸为 `[2W,H]`:每行前 W 列存原 float32 位串的低 16 位,后 W 列存高 16 位。读取时先合并为 uint32 位串,再按 float32 重新解释,不能数值 cast 成 float32。 + +```text +u = reinterpret_uint32(depth_float32) +encoded[:, :, :W] = uint16(u & 65535) +encoded[:, :, W:] = uint16(u >> 16) +u_restored = uint32(low) | (uint32(high) << 16) +depth_float32 = reinterpret_float32(u_restored) +``` + +统一采用 little-endian 原始字节接口。`camera.image_size` 始终是逻辑 RGB 尺寸 `[W,H]`,不能改成编码视频的 2W;`storage.encoded_size=[2W,H]`。包括 NaN 在内的 float32 位串必须全帧完全恢复,不允许改成 float16、整数毫米、归一化灰度或 RGB 伪彩色。这里的无损验收基准是完成既定米制/坐标转换后的标准 float32 数组,不声称消除 float64→float32 等原约定转换本身的舍入。 + +#### 3.2.2 逐像素有效性 + +`depth_valid.mkv` 使用 `mkv/bool_ffv1/v1`,FFV1 gray8(FFmpeg pixel_format=`gray`),物理尺寸 `[W,H]`。像素只能为 0 或 1,统一解码为 `[T,H,W] bool`,逐像素含义不变。这样不再把庞大的 bool 数组保存为未压缩 `.pt`;标注的帧级/手级 valid 仍保留原有小数组。 + +登记示例(W、H 以下取 640、480;decoder/encoder_parameters 的实际版本由转换器填写): + +```json +{ + "available": true, + "schema_id": "depth/z_float32/v1", + "data_ref": "observation/depth.mkv", + "axes": ["T", "height", "width"], + "valid_ref": "observation/depth_valid.mkv", + "valid_axes": ["T", "height", "width"], + "unit": "m", + "depth_type": "z", + "depth_origin": "measured", + "invalid_value": "NaN", + "storage": { + "profile": "mkv/depth_float32_bits/v1", + "codec": "ffv1", + "pixel_format": "gray16le", + "encoded_size": [1280, 480], + "source_lossy": false, + "decoder": {"name": "ffmpeg", "version": "填写实际版本"}, + "encoder_parameters": {"name": "ffv1", "level": 3, "version": "填写实际版本"} + }, + "valid_storage": { + "profile": "mkv/bool_ffv1/v1", + "codec": "ffv1", + "pixel_format": "gray", + "encoded_size": [640, 480], + "source_lossy": false, + "decoder": {"name": "ffmpeg", "version": "填写实际版本"}, + "encoder_parameters": {"name": "ffv1", "version": "填写实际版本"} + }, + "provenance": {"kind": "format_conversion", "method": "源深度转米制 z float32;逐位打包为 FFV1"}, + "source_locator": {"file": "raw/data/depth.zip", "member": "depth/0001.png"} +} +``` + +深度和有效性视频都必须逐帧解码验收:float32 位串相同、bool 相同、T 相同,并检查 valid=true 的正有限值和 valid=false 的 NaN。读取器必须按 profile 还原,不能把 depth.mkv 的编码像素直接当深度值。 + +## 4. camera 相机、帧索引与标定 + +### 4.1 frames.jsonl:索引、时间与对应关系 + +`camera/frames.jsonl` 每行对应统一帧号 `frame_index=0..T-1`,是所有组件的唯一行索引。至少包含 `frame_index`、`timestamp_ns`、`clock_domain`、`source_locator`;原始帧号/文件名保存在 `source_frame_id`,不能被新帧号替代。每行还可有 `annotation_matches`,按组件键保存 `source_frame_id`、`source_timestamp_ns`、`clock_domain`、`match_method` 和 `delta_ns`;方法为 exact/index_map/nearest/interpolated,索引映射无时间依据时 delta_ns=null。nearest 必须记录允许误差;interpolated 必须记录两端源标识和权重。delta_ns 仅在同一时间域中计算为源标注时间减图像时间。多相机共享 `sequence_id`;已知同步关系必须用 `sync_id` 或明确的源帧/时间映射表达,不能仅凭相同数组索引认定同步。 + +每个视图必须提供此文件。源时间使用整数纳秒及 `clock_domain`,未知写 JSON `null`;不同时间域不能直接比较。逐帧 split 可以覆盖 metainfo 的视图默认划分,并保留来源,见 2.4。 + +### 4.2 坐标系与标定通则 + +| 项目 | 统一约定 | +|---|---| +| 相机坐标 | 右手系,X 向右、Y 向下、Z 向前,长度单位米 | +| 齐次变换 | 列向量,`p_target = T_target_from_source @ p_source` | +| 图像坐标 | `(u,v)`;左上像素中心为 `(0,0)`,u 向右、v 向下,单位 pixel | +| 固定标定 | 本版展开为 T 份,同一 schema 不混用静态与动态形状 | +| 分辨率或模型变化 | 分开存储为视图/片段,不在同一组件中混装 | +| 未知标定 | 相机内外参允许缺省,不填单位阵冒充已知标定 | + +### 4.3 intrinsic.pt 与畸变参数 + +| model / schema_id | intrinsic.pt 的固定结构 | +|---|---| +| pinhole / camera/pinhole/v1 | `[T,3,3]`,标准 K,最后一行为 `[0,0,1]`;限无畸变或已校正图像 | +| fisheye624 / camera/fisheye624/v1 | `[T,15]`,`[f,cx,cy,k0,k1,k2,k3,k4,k5,p0,p1,s0,s1,s2,s3]`,采用 Project Aria Fisheye624 投影定义 | +| opencv_fisheye4 / camera/opencv_fisheye4/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件 `distortion_ref` 指向 `[T,4]`,顺序 `[k1,k2,k3,k4]`,使用 OpenCV fisheye 等距角度多项式;已由 ReInterHand 实际原始相机参数验证 | +| rational8 / camera/rational8/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件必需 `distortion_ref` 指向 `[T,8]`,顺序 `[k1,k2,p1,p2,k3,k4,k5,k6]` | +| unknown / null | 不提供可用 intrinsic,不声称可以投影 | + +有畸变的其他模型必须注册新 schema,固定参数名、顺序和投影公式;不能塞进针孔 K 后遗失畸变项。`metainfo.camera.schema_id` 必须与 intrinsic 组件一致。同一模型的别名不可隐式改变参数布局。 + +`opencv_fisheye4`:对前方点令 `x=X/Z, y=Y/Z, r=sqrt(x²+y²), theta=atan(r)`,`theta_d=theta*(1+k1*theta²+k2*theta⁴+k3*theta⁶+k4*theta⁸)`;`u=fx*x*theta_d/r+cx, v=fy*y*theta_d/r+cy`。光轴 r=0 时使用连续极限 `theta_d/r=1`。四系数不能按普通径向畸变解释,也不能补零冒充 Fisheye624。 + +rational8 对归一化坐标 x=X/Z、y=Y/Z,令 r²=x²+y²,径向项为 `(1+k1*r²+k2*r⁴+k3*r⁶)/(1+k4*r²+k5*r⁴+k6*r⁶)`;再加 p1/p2 切向项并经 K 得到像素。`distortion_ref` 与 intrinsic 共用 `[T]` valid,保存到 camera/distortion.pt。不得把这种畸变三维坐标当作真实相机系 xyz 保存。 + +内参有效性为 `intrinsic_valid.pt [T] bool`;有畸变时使用对应 `distortion_ref`。同一模型的参数名和顺序固定。 + +### 4.4 extrinsic.pt 与 extrinsic_valid.pt + +`extrinsic.pt` 为 `[T,4,4]`,schema `transform/se3/v1`,方向固定 `T_camera_from_world`,有效性 `[T]`。世界坐标含义及源坐标转换记录在 provenance 中;只有相机坐标标注不要求虚构世界坐标。旋转块须正交且 determinant≈1。 + +## 5. annotation 标注数据 + +### 5.1 标注通则:手槽、valid 与 visibility + +手槽固定为 0=left、1=right,指解剖学左右,不按画面位置或可见性重排。本阶段只处理左右手两槽,不处理更多手。实体引用使用 `hand_left`、`hand_right`;手槽不证明跨采集片段的个人身份。 + +#### 5.1.1 valid:标注是否可用于监督 + +标注的 `valid=true` 表示:有对应实际标注、通过本 schema 数值检查,且通过来源明确提供并适用于该组件的有效性/QA 条件。`valid=false` 可由缺标注、无法建立帧对应、源无效占位或官方 QA 不通过导致;不等于画面没有手或手不可见。各组件独立判断,MANO 按 `[T,2]` 标记左右手,关键点按 `[T,2,K]` 标记。 + +**2026-09-20 将标注 valid 从“仅表示存在”修订为“可用于监督”,字段形状不变。** 公式为 `source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass`。没有官方 QA 时省略最后一项,不伪造 QA;不能把未知当成已通过已存在的 QA。适配器在组件 `valid_policy` 中记录具体规则、来源、聚合/广播作用域。缺失官方必需 QA 的记录须明确处理为未知或暂停验收,不能静默通过。无效浮点项仍填 NaN,原始数据保留在 raw;被排除原值可用于 doc 中明确标识的诊断渲染,不能冒充 shared 有效监督。 + +本地筛选须依据明确的规则,并在 `valid_policy.local_excluded_frame_indices`、排除原因和正式报告中记录。单个可疑投影作为问题记录,不直接硬编码排除该帧。已确认的曝光异常须明确作用范围,不能把一个序列的“前两帧有问题”套到所有序列。RGB 编码完好与几何监督可用是两件事,允许保留原图及帧索引而屏蔽对应标注;未发现问题不等于完成全部人工审核,试点待确认时不能作为已验收发布使用。 + +源字段必须按官方语义映射,不能直接按名字复制: + +| 来源 | 官方含义 | 映射原则 | +|---|---|---| +| [H2O](https://github.com/taeinkwon/h2odataset) 的手标注首位 | 0 未标注、1 已标注 | 可作为对应手标注存在性的依据,不推断未标注原因 | +| [HOT3D](https://github.com/facebookresearch/hot3d#using-mask-files) 的 pose_available、visible、mask_qa_pass | 分别表达姿态存在、可见性、对画面中可见手物位姿的人工 QA | 逐手/物体记录决定存在性,再 AND 当前相机当前帧 QA;QA 是整帧聚合判定,保守排除该帧全部手物几何监督,不声称每个实体均有错误;源可见性基于位姿推导时,其自身 valid 同样受 QA 约束 | +| [Dex-YCB](https://github.com/NVlabs/dex-ycb-toolkit#loading-dataset-and-visualizing-samples) 的全零 pose_m、全 -1 joints | 不可见的手或缺标注共用占位表示 | 对应组件 valid=false;不能从该值判定 visibility=false,也不能声称原因是动捕缺失 | +| [ARCTIC](https://github.com/zc-alexfan/arctic/blob/master/docs/data/data_doc.md) 的 is_valid/left_valid/right_valid | 是否有效用于官方评估 | 核实每项筛选依据;不把可见性/评估选择直接等同 QA。本次原始 mano.npy 不含这些派生评估标记,按原记录与数值检查生成 valid,并声明没有额外官方 QA 输入 | + +源 valid=false 若代表评估筛选或其他条件,应检查实际标注和源约定后映射;不能一律清空坐标。反之,占位零或 -1 只有在源官方明确规定时才判为缺失,不泛化成所有数据的判断规则。 + +`valid=true` 的标注应通过其 schema 的数值与形状检查;检查失败必须报告或修复,不能静默隐藏。QA 不通过应报告排除数量与原因,并保留可追溯信息;不能把这类无效称为缺标注。RGB、深度等观测有效性仍按各自 schema;手物 QA 不自动否定 RGB、静态相机内参或物体资产。相机外参是否过滤须依据其自身来源规则;HOT3D 本次保留源外参用于溯源和诊断,不能用其存在性证明 QA 失败帧的几何监督正确。 + +#### 5.1.2 visibility:可见性属性 + +附加质量属性只保留 `visibility`,存放在对应模态或标注集内,不设 quality 目录。同一份可见性仅存一次;uv 与 xyz 共用时引用同一个文件。 + +visibility 通过所属组件 attributes 登记 data_ref、axes、dtype、visibility_type、meaning、provenance、source_locator;未知值通过属性 valid_ref 标识,全已知可声明 valid=true。比例与布尔值不相互强转,也不按任意阈值二值化。没有 MANO 时,整手可见性挂在 keypoints 组件,使用独立的 whole_hand_visibility.pt,明确 meaning=whole_hand,不与逐关键点可见性混用。 + +`valid` 回答“这项标注能否用于监督”,`visibility` 回答“在当前图像中是否可见(或可见多少)”。不可见的手或关键点仍可有有效标注;不能因 visibility=0 就清空坐标。源没有 visibility 时缺省或标为未知,不由 valid 推断。 + +| 情况 | 手标注 valid | visibility | +|---|---|---| +| RGB 已开始录制,动捕尚未开始,没有其他对应手标注 | false | 以独立源可见性标注为准;没有则未知 | +| 手被遮挡,但源有标注且通过适用有效性检查 | true | 若源声明不可见,则 false 或源可见比例 | +| 手可见且有对应标注,通过适用 QA | true | 若源有此信息,则 true 或源可见比例 | +| 手可见,但该帧漏标或动捕中断 | false | 可以为 true,但必须有独立来源依据 | +| 有手部参数,但官方 QA 明确不通过 | false | 不据此断言不可见;源可见比例若基于不可靠位姿,其属性 valid 也为 false | + +visibility 自己的 valid_ref 表示该可见性标注是否可用,不复用 MANO 或关键点坐标的 valid_ref;明确记录源存在性及适用的 QA 条件。上述例子不要求凭图像自动生成可见性。 + +不设 quality 组件或目录,不另存拟合误差、曝光、截断比例等通用质量数组。适用的官方 QA 合并进对应 valid,在 `valid_policy` 记录来源与规则;正式校验报告保留原始 QA 时间区间及排除统计。原始 QA 文件仍在 raw,官方 split 保留。 + +### 5.2 mano:参数与整手可见性 + +MANO schema `mano/axis_angle61/v1`:`motion.pt [T,2,61]`,顺序为完整 16 关节 axis-angle 48、shape betas 10、全局平移 3。姿态使用弧度,平移米,位于当前相机系。有效性 `[T,2]`;缺少一侧整槽 NaN。PCA 必须先按对应模型展开,不能将 PCA 系数直接填入 axis-angle。 + +`model_profile` 必须固定 MANO 版本、`flat_hand_mean=true`、左手 shapedirs 修正状态。平移表示模型输出顶点所加的全局平移,不是某个腕关节的坐标;源语义不同须转换。shape 无量纲。模型权重不作为共享数据附带上传。 + +`mano/visibility.pt [T,2]` 保存源整手可见比例时使用 float32 [0,1],`visibility_type=ratio`;只有实际采用 0–100 的百分比才除以100,不能只凭表头判断。HOT3D 的 `visibility_ratio[%]` 实值已经是0–1,官方读取器原样读取,必须保留原值。通过 MANO 组件 attributes 登记,使用独立有效性,不复用 motion_valid。 + +手部共享表示仅保留 MANO 参数与选定关键点,不发布独立手表面几何。需要渲染或接触计算时由 MANO 参数生成,几何引用使用固定 MANO 模型配置与顶点顺序;不影响 object 下的物体模型和材质资产。 + +### 5.3 keypoints:二维点、三维点与逐点可见性 + +关键点独立于 MANO 参数存在;没有 motion 也可有关键点。`uv.pt [T,2,K,2]` 与 `xyz.pt [T,2,K,3]`,有效性 `[T,2,K]`,分别采用 `keypoints/uv/v1` 和 `keypoints/xyz/v1`。K 由 `keypoint_schema` 固定,不能在同一数组中逐帧变化;同体系统一顺序。数值使用像素坐标或米制相机系。 + +| keypoint_schema | K 与固定索引 | +|---|---| +| mano21/v1 | 21;wrist 后依次 thumb/index/middle/ring/little,每指由近端至指尖 | +| rhd21/v1 | 21;保持 wrist,然后五指由近端至指尖;原始每指 tip→palm 反序。只统一顺序,不宣称解剖学位置等价于 MANO | + +具体名称与源索引映射见 `schema.json`。当前只登记 MANO21 与 RHD21;不登记 MediaPipe、ReInterHand capture21 或 fit24 中间关键点。 + +每个发布中的每个视图只提供一套标准手关键点,直接放在 keypoints 下,不设 annotation_set_id 字段或目录。uv 与 xyz 是这套关键点的二维与三维表示,不是两套标注。provenance 分别记录二者来自原始标注还是计算结果;不要求已有 2D 必须由当前 xyz 重新投影覆盖。 + +ReInterHand 的 Original keypoints、Original fits keypoints 及带前臂关键点不纳入 shared;如需手关键点,从选定 MANO 参数生成 MANO21 并记录模型/指尖回归约定。其他数据集默认使用选定的官方关键点,不额外生成平行的 MANO 派生集合。后续主动更换生成方法或结果时发布新的 dataset_version,不在同一版本内增设方法分支。 + +manual/projection/fitting 只记录在 provenance,不作为目录或类型分支。不得通过坐标为零、是否出画或 visibility 判断标注是否存在。派生标注仅在实际生成并通过数值检查后声明 valid=true;没有生成的项为 false,不伪造坐标。 + +`keypoints/visibility.pt [T,2,K]` 保存源逐点可见性,布尔表示使用 `visibility_type=boolean`。uv 与 xyz 共用时引用同一份文件。整手比例属性没有 MANO 可挂载时使用 `whole_hand_visibility.pt [T,2]`,`meaning=whole_hand`;它与逐点可见性分开,通用登记规则见 5.1。 + +不使用 annotation_set_id;ReInterHand 中间关键点集合不进入 shared,raw 保留来源文件。 + +### 5.4 object:身份、资产、位姿与几何 + +#### 5.4.1 metainfo.json:物体身份与跟踪作用域 + +手用 `hand_left`、`hand_right` 及槽位 0、1 表示,不再另存 entities.json。物体身份登记在 `annotation/object//metainfo.json`,必填 `object_id`、`identity_scope`、`scope_id`、`source_locator`;可含 `category_id`、`source_object_id`、`mesh_ref`、`has_model`、部件引用。即使只有分割、没有 pose/mesh,也可只有这份物体元信息。 + +`identity_scope` 为 frame/subsequence/sequence,`scope_id` 指定具体作用域;跨相机共享身份只在已有源对应证据时使用。VISOR 按官方 subsequence 与实体名关联时记录 `association_basis=official_subsequence_entity_name`,不能声称这是全视频物理实例跟踪。无需与 object_id 一一对应的标准 track_id;官方独立轨迹标识存在时保留为 source_track_id,并声明作用域。手槽不证明跨采集片段的个人身份。 + +#### 5.4.2 assets:网格、材质与纹理 + +资产属于物体,统一存放在 `annotation/object//` 内,可用 `assets/` 子目录组织网格、材质、纹理和部件资产。序列层不设共享 assets。所有引用采用视图根目录为基准;其中物体资产组件的 `data_ref` 与部件的 `mesh_ref` 采用相对于当前视图目录的 POSIX 路径,例如 `annotation/object/cup_01/assets/cup.obj`,且必须指向所属物体目录内的资产。OBJ 内部的材质、纹理引用遵循文件格式自身的相对路径规则,依赖文件一并保留。不同相机视图允许各自保存物体资产,不要求跨视图去重;下载物体时包含其资产依赖。 + +网格 schema 为 `mesh/obj/v1`,顶点米制,静态有效性可直接声明标量 `valid`,或通过 `valid_ref` 指向标量 bool Tensor;不按 T 重复静态资产。由物体/部件通过引用关联,不仅凭文件名猜测。 + +#### 5.4.3 pose.pt、pose_valid.pt 与 visibility.pt + +刚体 schema 为 `object/rigid/v1`,`pose.pt [T,4,4]` 固定为 `T_camera_from_object`,平移米制,有效性 `[T]`。物体坐标原点、轴向必须与 mesh 一致;旋转块为正交矩阵且 determinant≈1。 + +`object//visibility.pt [T]` 保存源物体可见比例,float32 [0,1],`visibility_type=ratio`。通过所属物体组件 attributes 登记,独立表达其有效性。 + +#### 5.4.4 articulation.json、部件位姿与 joint_state.pt + +关节物体:schema `object/articulated/v1`,`articulation.json` 登记 `parts` 与 `joints`。每个 part 有 `part_id`、`parent_id`(根为 null)、`has_model`、`mesh_ref`;has_model=false 时 mesh_ref=null,结构节点允许没有网格。父链不得成环。每个 joint 有唯一 `joint_id`、`parent_part`、`child_part`、`type`;fixed 单位 null、revolute 弧度、prismatic 米。有源限位时保存 `limits:[lower,upper]`;没有时 null,不伪造上下限。部件姿态统一为 `T_camera_from_part [T,4,4]`,不与父局部变换混装。 + +若提供 `joint_state.pt [T,J]`,必须登记固定 joint_order、轴在父部件系的表达、零位变换与正方向,valid 为 `[T,J]`;缺少这些运动学定义时只发布部件位姿与已有来源信息,不伪造可驱动的关节模型。关节值与部件位姿同时存在时需验证一致性。 + +部件层级应声明语义:纯语义包含树允许 `joints=[]`,不将包含关系推断为机械关节。关节状态 schema 为 `object/joint_state/v1`;转动用弧度、移动用米,混合类型按 joint_order 对应的关节定义解释。 + +#### 5.4.5 dimensions、几何关键点与顶点部件标签 + +`dimensions.pt [T,3]` 采用 `object/dimensions/v1`,有效性为 `[T]`。 + +物体/部件 `dimensions` 为 `[length,width,height]` 米,轴顺序与该 mesh 的局部坐标关联,登记 `dimensions_semantics` 和来源。HOI4D dimensions 与 mesh 的具体尺度关系未验证前标为 source_unspecified,保留源值并暂停依赖该关系的几何验收,不能默认为待施加缩放。需要施加缩放时明确 scale_applied_to_mesh,禁止重复应用。 + +源物体关键点放 `object//keypoints/xyz.pt [T,K,3]`(相机系)或 `template_xyz.pt [K,3]`(物体系),schema 分别为 object_keypoints/camera/v1 和 object_keypoints/template/v1。明确 keypoint_schema、keypoint_names、单位及有效性;模板点配合 pose 可投影,无须重复生成全部帧。H2O 中心/角点/棱中点,以及 ARCTIC 部件点分别登记具体源顺序,不套用手的 21 点 schema。每个发布选择一套源几何点并记录选择,不另建方法分支。 + +`vertex_part_ids.pt [V] int64` 绑定 `mesh_ref` 与 topology_id,登记整数到 part_id 的映射;未知用 -1。ARCTIC 不同拓扑的资产分别绑定,不能共用未经转换的顶点标签。部件层级中 is_instance/has_model 等源属性保留,几何文件仍全部归 object。 + +### 5.5 segment:分割类别、编码与覆盖范围 + +每个发布选择一套任务使用的分割表示,不建立方法/标注集分支。没有分割就不创建 segment 目录,不为其他模态创建空的实体表。 + +| schema_id | 文件与数值语义 | +|---|---| +| segment/uint16_labels/v1 | mask.mkv;整数区域编号,通过 instances.jsonl 解释 | +| segment/instance_polygons/v1 | polygons.jsonl;实例多边形,可重叠;当前不支持孔洞拓扑 | +| segment/foreground_intensity/v1 | mask.mkv;0–255 前景强度,不是区域编号或经过校准的概率 | + +#### 5.5.1 uint16 标签图与 instances.jsonl + +组件声明 `segmentation_type=semantic/instance/part`;同一组件固定一种类型。`mask.mkv` 解码为 `[T,H,W] uint16`,schema `segment/uint16_labels/v1`,使用 `mkv/uint16_ffv1/v1`,FFV1 gray16le 无损;只有所有区域编码均 ≤255 时允许 gray8(pixel_format=gray),读取后转 uint16,数值不变。禁止调色板和有损编码。有效性 `[T]`,表示该帧有可用分割标注。数值 0 固定为 unassigned,65535 固定为 ignore,1–65534 为区域编码,不能直接等同 entity_id。 + +`instances.jsonl` 每帧一行,包含 `frame_index` 与 `labels`。每条标签包含 `mask_value`、`category_id`、`entity_id`、`part_id`;无意义或未知字段为 null。semantic 允许 entity_id=null;instance 必须引用 hand_left/hand_right 或登记的 object_id;part 还须关联登记部件。源实例 ID 和其他属性分别保存在 `source_instance_id`、`source_attributes`。mask 中每个非保留编码必须有且仅有一个映射。 + +FreiHAND 的试点按本任务需要,统一到手/背景类别,保留每个原生区域编码;不要求给原生细分区域猜测手指名称。需要细部件监督时,尚未核实的部件名称必须保持未知,不能因粗粒度手类别已核实便声称部件语义也已统一。 + +#### 5.5.2 重叠实例多边形 + +每发布选择一套任务使用的分割表示,不建立方法/标注集分支。VISOR 的实际试点存在重叠实例多边形,单层标签图不能无损表达。对此补充 `segment/instance_polygons/v1`:`segment/polygons.jsonl` 每帧包含 `frame_index` 和 `instances`,每实例包含 `mask_value` 与 `polygons`(列表,每个多边形为源图像像素坐标顶点序列,保留原始精度)。身份和类别仍由同一 `instances.jsonl` 映射,有效性仍为 `[T]`,通过 schema 区分物理编码。允许多实例重叠,不采用后画覆盖前画。消费者按需栅格化为独立实例二值 mask;不能声称合并的单层 mask 无损。 + +#### 5.5.3 灰度前景强度 + +ReInterHand 的官方渲染 mask 为双手合并的灰度前景掩码,实测存在 0–255 的中间值,不是左右手实例编号。登记 `segment/foreground_intensity/v1`:仍存 `segment/mask.mkv`,解码为 `[T,H,W] uint16`,使用 `mkv/uint16_ffv1/v1`,此类数据优先编码为 FFV1 gray8(pixel_format=gray),读取后转 uint16。有效值范围 0–255,归一化值为 `float32(value)/255`;0 为背景端点、255 为前景端点。组件声明 `foreground_category=hand`、`entity_id=null` 和双手合并语义,不使用区域编号映射。这里保留原始渲染 mask 强度,不把它称为经过校准的概率。若任务需要二值 mask,阈值化属于任务层派生操作,记录阈值;共享层不丢弃中间灰度。不同 schema 的数值含义不同,不能将该文件按整数类别图解码。 + +FreiHAND 训练集的 JPEG mask 使用 `segment/foreground_intensity/v1`,逐像素保留 JPEG 解码后的灰度,`entity_id=hand_right`。该 schema 不限定双手合并:单手或合并范围由 `entity_id` 与 `coverage` 明确声明。评估集整数区域图仍用 `segment/uint16_labels/v1`,两者不能仅凭文件名使用同一种解码语义。 + +#### 5.5.4 coverage 与有效性 + +`coverage.kind=full/selected_entities/partial/unknown`。full 指声明的标注范围完整;selected_entities 还应列出目标范围。无论哪种,0 本身不自动成为背景;背景要有明确类别映射,未标注区域不能用于构造负样本。保留源逐类/逐实例 exhaustive 信息,未知不可改写为完整。 + +三种表示的帧级有效性均为 `[T]`,表示该帧是否提供此分割标注;对应 valid_ref 在组件中登记,仍用小型 bool `.pt` 数组。栅格 mask 必须登记 storage,格式见 3.1.2,所有帧的整数编码或强度逐值完全相同。编码语义由 schema_id 决定,读取器不能仅依据 mask.mkv 文件名选择解码方式。 + +### 5.6 contact:接触、抓取、区域与距离 + +#### 5.6.1 relations.jsonl 与 relations_valid.pt + +`annotation/contact/relations.jsonl`,schema contact/relations/v1,每帧一行含 frame_index、relations。每条记录含 relation_type(contact/grasp)、subject_id(手槽或登记实体)、object_id、status、source_locator、provenance。status 固定为 positive/negative/unknown/target_unannotated:positive 必须有可解析目标,negative 表示源明确否定该关系,unknown 为不确定,target_unannotated 为确有接触但目标未标注。非 positive 的 object_id 可 null,不能用 null 冒充“不接触”。稀疏源无记录的帧不自动补 negative。 + +VISOR 的对象 mask ID 必须先按同帧 source_instance_id 解析成 object_id;hand-not-in-contact、none-of-the-above、inconclusive 分别映射 negative、target_unannotated、unknown,保留原始字符串。Dex ycb_grasp_ind 通过 ycb_ids 映射到登记物体,以 relation_type=grasp 保存;不得当作逐顶点接触。 + +relations 组件的 valid_ref 指向 `relations_valid.pt [T] bool`,表示该帧是否有可用源关系标注。有效帧中可以存在 status=unknown 的明确不确定标注;无源标注的帧为 valid=false、relations=[]。组件仍声明 available/provenance/source_locator。 + +#### 5.6.2 实体对的顶点区域与距离 + +已发布的接触区域/距离按参与关系的 subject_id 与 object_id 组织,每对实体保留选定的一套结果,以精确 geometry_ref/topology_id 关联到手或物体/部件;不要求每套数据都有。顶点区域 schema contact/vertex_region/v1:bool `[T,V]` 加同形 valid;顶点距离 schema contact/vertex_distance/v1:float32 `[T,V]`、米、同形 valid,声明 source/target geometry_ref、distance_definition(signed/unsigned、测量到点集或表面等明确源定义)。geometry_ref 必须指向已登记 mesh 或由固定 MANO 模型配置确定的拓扑;拓扑/顶点数变化时按拓扑拆分片段。其他源区域表示只有在实际接入并登记 schema 后才可转换,不能随意栅格化宣称等价。 + +顶点区域/距离已有存储定义,但尚未完成真实输入试点;接入时必须提供源语义与几何验收证据,不因已经登记 schema 就视为通过。 + +## 附录:任务范围 + +不强制收录 2D bbox、完整高频动捕、动作程序、身体 SMPL-X、点云或网络特征。范围内的接触、visibility、选定手关键点、物体几何不能因不便处理而静默丢弃。分割采用的物理编码由第 5.5 节决定,存在重叠时不能以单层标签图声称无损。 + +不设置 entities_ref/segment/entities.json,不要求与 object_id 重复的 track_id。MediaPipe 不在当前关键点定义中;旧版本迁移必须保留可追溯关系,不能直接删表。手部共享表示不含独立 hand_mesh。 + +schema.json 是普通注册表,不是 JSON Schema 文档或可执行验收器;定义存在不代表真实数据已验证。验收须保留实测范围与未决项。 + +本存储约定只更新标准,不代表既有 FFV1/depth.pt 试点已迁移。新发布必须显式写 storage 配置;旧产物按其旧定义读取,不能只改文件后缀或版本标识伪装为合规。 diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/docs/h2o-RAW_TO_SHARED.md b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/docs/h2o-RAW_TO_SHARED.md new file mode 100644 index 0000000000000000000000000000000000000000..1f5cd6670065ebca7e08a8f0c0864e2474f2dbc5 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/docs/h2o-RAW_TO_SHARED.md @@ -0,0 +1,48 @@ +# H2O raw → shared-v1.0 + +## 范围与来源 + +本版本仅转换 `raw/data/subject{1,2,3,4}_v1_1.tar.gz` 的真实五视角 (`cam0`–`cam4`) 序列;`h2o_CASA.tar` 是单独的扩展,不与标准序列混合。每个原始序列存于 `data/subjectN__/cam{0..4}/`。源压缩包保持不变,不合成源不存在的标注。输出仅在本地制作;完整序列试点及人工检查通过、更新全量预估之前,不启动全量。 + +| 源包/字段 | shared 文件/处理 | +| --- | --- | +| `subjectN_v1_1.tar.gz`: `camX/rgb/.png` | `observation/rgb.mkv`:逐帧源 RGB 解码为 RGB24,FFV1 直接编码;输出**每帧**解码与源 RGB 字节摘要完全一致。`rgb_valid.pt` 记录存在性,源帧号和每组件的包成员及 SHA256 写入 `camera/frames.jsonl`。不再额外编码未采用的 H.264 RGB 候选;FFV1 编码器进程失败时才尝试 H.264。 | +| 同包 `camX/depth/.png` | `observation/depth.mkv` 和 `depth_valid.mkv`;按源毫米单位除以 1000 转米,保留无效深度与全帧时间轴,深度位串以 FFV1 保真封装并逐帧校验。既不做 3 米裁剪也不造出缺失的深度。 | +| `camX/cam_intrinsics.txt`、`camX/cam_pose/.txt` | `camera/intrinsic.pt`、`extrinsic.pt`:保留源内参;逐帧源 `T_world_from_camera` 求逆后存 `T_camera_from_world`;声明变换约定与有效性。 | +| `camX/hand_pose_mano/.txt` | `annotation/mano/motion.pt`、`motion_valid.pt`:源左/右手标志各自判断有效性;姿态与平移保持源数值,声明 MANO 模型配置,缺模型则明确标依赖缺失,不伪造网格或掩码。 | +| `camX/hand_pose/.txt` | `annotation/keypoints/xyz.pt`、`xyz_valid.pt`:源双手 21 点,相机坐标系米制,与 MANO 有效性彼此独立。HTML 中的投影仅用于人工预览,不写回训练数据。 | +| `camX/obj_pose/.txt`、`obj_pose_rt/.txt` | `annotation/object//keypoints/xyz.pt`、`pose.pt`:按源类号关联 21 个物体点及物体→相机位姿;仅源存在时登记组件及有效性。 | +| `object.zip` | `annotation/object//assets/` 与源 OBJ、MTL、纹理;静态形状预览不等于所有帧网格位姿的投影证明。 | +| `label_split.zip` 的 `action_{train,val,test}.txt` | 序列元数据的官方划分及来源;未知映射明确记 `unknown`,不自行编排。 | + +`cam4` 是 ego,`cam0`–`cam3` 是 exo。真实时间/FPS 缺乏可靠来源时使用 null,不把 MKV 封装帧率冒充采集时钟。源 `action_label`、`verb_label`、pose 任务帧列表和 `manolabel_v1.1.tar.gz` 保留在 raw;当前契约没有相应动作组件,本发布不宣称它们已转换。源没有像素分割,本版本不投影网格生成替代分割。 + +## 源资产文件名修复 + +源 `object/cocoa/cocoa.obj` 引用 `ovomaltine.mtl`,材质内写的是 `map_Kd cocoa.png`,但原 ZIP 只提供 `ovomaltine.png`。仅在临时解压目录为该已确认的纹理增加**字节相同**的 `cocoa.png` 别名,保留原 PNG、OBJ、MTL 不变;在网格 `source_locator.texture_aliases` 中记录别名、原始包成员和 SHA256。别名与已保留的旧 cocoa 资产一致,不替换图像、标注或网格。全部八类物体的材质依赖在读取大 subject 包之前预检,其他缺失/越界依赖仍报错。 + +## 加速与验收 + +四个互不依赖的 subject 压缩包可由 `--workers 1..4` 并行顺序读取,各 worker 一次只处理一个序列。数值库保持单线程;FFV1 编码支持 `--codec-threads 1|2|4|8|10`,当前全量按用户要求使用 10;`--decode-threads 10` 通过现有 `HAND_WAREHOUSE_FFMPEG_THREADS` 控制源 RGB PNG→RGB24、完整视频解码摘要、深度/有效性语义校验与 RGB 索引抽取的解码线程,完整校验仍保留。深度 PNG 使用 `--depth-threads 4` 有序分批读取,每批最多读取 4 帧,避免缓存整条序列,缺帧仍按原时间轴写 NaN;不并行改写姿态、标注或原始包。并发数由相同输入实测吞吐量决定,记录 OS 线程峰值和磁盘占用,不以 CPU 线程数本身作为提速证据。RGB 源为 PNG,不适用 ARCTIC/HOT3D 的 JPEG 包直封和 16 帧抽查:RGB、深度、有效性与数值模态仍逐帧精确校验。临时文件在 `/data` 上隔离放置,历史 62 条目录不复用、不覆盖;调整并发时,在新的运行目录复用本次全量已经原子发布的完整序列,并从源重新核对帧号及逐组件 SHA256;已发布视图只读源包并核对摘要,不再把源 PNG/标注写入临时目录,待转换视图才正常暂存。未完成的临时序列不复用,原运行的脚本、配置及 QC 保留用于溯源。 + +先运行不截帧的代表性完整序列试点,保存自动 QC、真实耗时和 `doc/validation/index.html`(RGB、深度、源 3D 关键点投影、原生物体网格和全组件数值/有效性)。试点由人工核查之后再决定全量;全量后再次抽样人工核查。报告须区分数据完整性、源未提供的模态与仅供人工判断的几何对齐。 + +2026-09-29 完整序列试点已获人工确认,用户已授权本地全量。2026-09-30 用户取消 CPU 使用量上限,指定 4 个独立压缩包 worker、每个 FFV1 编码器 10 线程、每个校验解码器 10 线程、每 worker 深度 PNG 读取 4 线程;Python worker、读取及校验子进程不计入这最多 40 个编码线程,因此总线程数不固定为 40。该配置不代表已证明加速倍数。源包和旧产物保留;代码变化使用独立运行目录,已完成序列保留原始构建记录及生产脚本快照。 + + +## 多线程解码测速(2026-09-30) + +在 101 上以真实 `subject4/h1/0/cam0` 的完整 RGB、深度和有效性视频,以及源头 100 帧 PNG 测试;采用 1、10、10、1 的解码线程顺序,源深度 PNG 另比较 1/2/4 线程。逐字节摘要和输出长度必须相同,测速脚本、全部轮次及结果保存在 `script/provenance/operations/` 和 `doc/validation/`。测速期间旧全量任务仍运行,磁盘负载和缓存会影响结果;不得将阶段加速比冒充整套转换加速比。四个 gzip 包已经独立并行读取,暂不引入多进程重构或增加数值库线程;小矩阵及标注处理没有已测得的进一步并行收益。 + + +本次同输入结果(解码后长度和 SHA256 全部相同): + +| 阶段 | 1 线程(秒) | 新配置(秒) | 范围 | +| --- | ---: | ---: | --- | +| FFV1 RGB 解码与摘要 | 39.46 | 8.70(10 线程) | 完整 501 帧,中位数 | +| FFV1 深度位串解码与摘要 | 34.91 | 11.56(10 线程) | 完整 501 帧,中位数 | +| 有效性视频解码与摘要 | 2.24 | 2.27(10 线程) | 完整 501 帧;未获提速 | +| 源 RGB PNG 解码 | 2.67 | 1.49(10 线程) | 100 帧,1 线程使用热缓存轮次,不使用冷缓存较慢轮次来夸大提速 | +| 源深度 PNG 读取及毫米→米 | 4.67 | 2.61(4 线程) | 100 帧,中位数;帧序与数值相同 | + +这些结果只代表相应阶段;全流程还包括顺序 gzip 扫描、文件创建、源 SHA256、资产复制和磁盘读写,实际全量 ETA 待稳定吞吐后再更新。 diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/docs/schema.json b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/docs/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..d904a34272de7f3fd4428c8dc68a919e94a68fca --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/docs/schema.json @@ -0,0 +1,869 @@ +{ + "schema_version": "hand-warehouse/1.0", + "validity_revision": "usable-annotation-2026-09-20", + "annotation_validity": { + "meaning": "annotation usable for supervision, not merely record presence", + "formula": "source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass AND NOT explicitly_reviewed_local_exclusion", + "without_official_qa": "omit QA term; declare source rules; do not fabricate QA", + "policy_field": "components..valid_policy", + "visibility_is_independent": true, + "invalid_float_value": "NaN", + "hot3d": "broadcast per-camera frame manual QA conservatively to hand/object labels and pose-derived visibility; retain RGB and source calibration; keep native QA in raw and review report", + "hot3d_visibility": "native visibility_ratio[%] already ranges from 0 to 1; do not divide by 100" + }, + "hand_slots": [ + "left", + "right" + ], + "keypoints": { + "mano21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map": null, + "note": "adapter maps official MANO joint and fingertip convention" + }, + "rhd21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map_per_hand": [ + 0, + 4, + 3, + 2, + 1, + 8, + 7, + 6, + 5, + 12, + 11, + 10, + 9, + 16, + 15, + 14, + 13, + 20, + 19, + 18, + 17 + ] + } + }, + "camera": { + "opencv_fisheye4": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "k3", + "k4" + ], + "projection": "theta=atan(r); theta_d=theta*(1+k1*theta^2+k2*theta^4+k3*theta^6+k4*theta^8); source ReInterHand" + }, + "pinhole": { + "K": [ + 3, + 3 + ] + }, + "fisheye624": { + "parameters": [ + "f", + "cx", + "cy", + "k0", + "k1", + "k2", + "k3", + "k4", + "k5", + "p0", + "p1", + "s0", + "s1", + "s2", + "s3" + ] + }, + "rational8": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "p1", + "p2", + "k3", + "k4", + "k5", + "k6" + ] + } + }, + "segmentation": { + "segment/uint16_labels/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "polygons.jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "note": "Registry for hand-warehouse/1.0. Read CONTRACT.md for field semantics. This is not a JSON Schema document or executable validator.", + "components": { + "mano/axis_angle61/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 61 + ], + "valid_shape": [ + "T", + 2 + ], + "unit": "m", + "angle_unit": "rad", + "coordinate_frame": "camera", + "layout": { + "pose_axis_angle": [ + 0, + 48 + ], + "shape": [ + 48, + 58 + ], + "translation": [ + 58, + 61 + ] + } + }, + "keypoints/uv/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 2 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "pixel", + "required_metadata": [ + "keypoint_schema" + ] + }, + "keypoints/xyz/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 3 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "m", + "required_metadata": [ + "keypoint_schema" + ] + }, + "depth/z_float32/v1": { + "storage": "mkv", + "dtype": "float32", + "shape": [ + "T", + "H", + "W" + ], + "valid_shape": [ + "T", + "H", + "W" + ], + "unit": "m", + "depth_type": "z", + "pixel_grid": "current_rgb", + "coordinate_frame": "current_rgb_camera", + "valid_storage": "mkv", + "allowed_storage_profiles": [ + "mkv/depth_float32_bits/v1" + ], + "allowed_valid_storage_profiles": [ + "mkv/bool_ffv1/v1" + ], + "required_metadata": [ + "storage", + "valid_storage", + "depth_origin" + ], + "depth_origin_values": [ + "measured", + "rendered", + "unknown" + ] + }, + "transform/se3/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention" + ] + }, + "object/rigid/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention" + ] + }, + "camera/pinhole/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/rational8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/opencv_fisheye4/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/fisheye624/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 15 + ], + "valid_shape": [ + "T" + ] + }, + "camera/distortion8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 8 + ], + "valid_shape": [ + "T" + ] + }, + "camera/fisheye4_distortion/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4 + ], + "valid_shape": [ + "T" + ] + }, + "object/joint_state/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "J" + ], + "valid_shape": [ + "T", + "J" + ], + "required_metadata": [ + "joint_order" + ], + "unit_rule": "revolute radians; prismatic metres; mixed types declared per joint" + }, + "object_keypoints/camera/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "K", + 3 + ], + "valid_shape": [ + "T", + "K" + ], + "unit": "m", + "coordinate_frame": "camera", + "required_metadata": [ + "keypoint_schema" + ] + }, + "object/dimensions/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "dimensions_semantics" + ], + "axis_order": [ + "length", + "width", + "height" + ], + "scale_rule": "do not apply to mesh without source-supported size/scale relation" + }, + "object_keypoints/template/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "K", + 3 + ], + "valid_shape": [ + "K" + ], + "unit": "m", + "coordinate_frame": "object", + "static": true, + "required_metadata": [ + "keypoint_schema" + ] + }, + "mesh/obj/v1": { + "storage": "obj", + "unit": "m", + "static": true, + "valid_shape": [], + "dependencies": "MTL and textures retained under owning object" + }, + "rgb/uint8/v1": { + "storage": "mkv", + "dtype": "uint8", + "shape": [ + "T", + "H", + "W", + 3 + ], + "valid_shape": [ + "T" + ], + "color_order": "RGB", + "allowed_storage_profiles": [ + "mkv/mjpeg_copy/v1", + "mkv/source_copy/v1", + "mkv/h264_rgb_lossless/v1", + "mkv/ffv1_rgb/v1" + ], + "required_metadata": [ + "storage" + ] + }, + "contact/relations/v1": { + "storage": "jsonl", + "valid_shape": [ + "T" + ], + "frame_keys": [ + "frame_index", + "relations" + ], + "absence_semantics": "no record is not a negative contact annotation" + }, + "contact/vertex_region/v1": { + "storage": "pt", + "dtype": "bool", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id" + ], + "pilot_status": "defined_not_empirically_validated" + }, + "contact/vertex_distance/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "unit": "m", + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id", + "distance_definition" + ], + "pilot_status": "defined_not_empirically_validated" + }, + "object/articulated/v1": { + "storage": "json", + "required_keys": [ + "parts", + "joints" + ], + "part_keys": [ + "part_id", + "parent_id", + "has_model", + "mesh_ref" + ], + "hierarchy_semantics": "declare mechanical articulation or semantic containment; containment alone does not imply joints", + "acyclic": true + }, + "segment/uint16_labels/v1": { + "storage": "mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "storage_revision": "lossless-video-2026-09-18", + "sampling": { + "image": { + "single": { + "T": 1 + }, + "independent": { + "T": ">=2", + "required_frame_fields": [ + "sample_id", + "source_locator" + ], + "temporal_relationship": false + }, + "source_fps": null + }, + "video": { + "sampling_types": [ + "dense", + "sparse" + ] + } + }, + "storage_profiles": { + "mkv/mjpeg_copy/v1": { + "container": "matroska", + "codec": "mjpeg", + "method": "stream_copy_from_source_jpeg", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "source_jpeg_packet_sha256_exact", + "all_packet_count_order_and_dimensions_exact", + "deterministic_decoded_rgb_sample_exact", + "pilot_and_final_selected_whole_sequences_decoded_rgb_exact" + ], + "validation_policy": { + "id": "jpeg-packets-all-rgb-sample16/v1", + "sample_count_per_view": 16, + "short_views": "all_frames_if_T_less_than_16", + "fixed_indices": "0,T-1,T//4,T//2,3*T//4, deduplicated", + "remaining_indices": "sample without replacement to min(T,16) using Python random.Random(seed)", + "seed": "first 8 bytes of SHA256(sequence_id/camera_id/20260920), big-endian integer", + "report": "policy, exact selected frame indices, seed, separate packet and pixel coverage", + "legacy_all_frame_pixel_proofs": "still accepted; preserve historical evidence" + } + }, + "mkv/source_copy/v1": { + "container": "matroska", + "codec": "source_codec_declared_in_metadata", + "method": "stream_copy_only", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "no_reencoding", + "all_decoded_rgb_frames_exact", + "presentation_frame_order_exact" + ] + }, + "mkv/h264_rgb_lossless/v1": { + "container": "matroska", + "codec": "h264", + "encoder": "libx264rgb", + "crf": 0, + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "gop": "declared_in_encoder_parameters", + "validation": [ + "all_decoded_rgb_frames_exact" + ], + "forbidden": [ + "lossy_rate_control", + "rgb_to_yuv420_subsampling" + ] + }, + "mkv/ffv1_rgb/v1": { + "container": "matroska", + "codec": "ffv1", + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "validation": [ + "all_decoded_rgb_frames_exact" + ] + }, + "mkv/depth_float32_bits/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray16le", + "logical_dtype": "float32", + "logical_shape": [ + "T", + "H", + "W" + ], + "encoded_shape": [ + "T", + "H", + "2*W" + ], + "packing": "IEEE754 little-endian float32 bits; low uint16 in first W columns, high uint16 in last W columns", + "decode": "reinterpret_float32(uint32(low) | (uint32(high) << 16))", + "validation": [ + "all_float32_bits_exact_including_nan" + ] + }, + "mkv/bool_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray", + "logical_dtype": "bool", + "stored_values": [ + 0, + 1 + ], + "validation": [ + "all_bool_values_exact" + ] + }, + "mkv/uint16_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_formats": [ + "gray", + "gray16le" + ], + "logical_dtype": "uint16", + "gray_condition": "all values <=255; decode by exact uint8-to-uint16 promotion", + "validation": [ + "all_integer_values_exact" + ] + } + }, + "video_metadata": { + "required": [ + "profile", + "codec", + "pixel_format", + "encoded_size", + "decoder", + "encoder_parameters", + "source_lossy" + ], + "source_lossy_values": [ + true, + false, + "unknown" + ], + "timebase_role": "index_only", + "lossless_reference": "source compressed packets or fixed-decoder source pixels; depth uses normalized standard float32 bits", + "selection": "choose smaller complete candidate only after exact roundtrip validation" + } +} diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/full.log b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/full.log new file mode 100644 index 0000000000000000000000000000000000000000..7786507d0c59ad7f165cdc1b215d8d50ab9bd02d --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/full.log @@ -0,0 +1,61 @@ +Verified existing subject1/h1/0 +Verified existing subject4/h1/0 +Verified existing subject3/h1/0 +Verified existing subject1/h1/6 +Verified existing subject2/h1/0 +Verified existing subject1/h1/3 +Verified existing subject2/h1/6 +Verified existing subject1/h1/7 +Converted subject3/h1/6 +Converted subject4/h1/6 +Verified existing subject1/h1/4 +Verified existing subject1/h1/2 +Verified existing subject2/h1/3 +Verified existing subject1/h1/1 +Verified existing subject1/h1/5 +Verified existing subject1/o1/0 +Converted subject3/h1/3 +Verified existing subject2/h1/7 +Verified existing subject1/o1/6 +Converted subject4/h1/3 +Verified existing subject1/o1/3 +Verified existing subject2/h1/4 +Verified existing subject1/o1/7 +Verified existing subject1/o1/4 +Verified existing subject2/h1/2 +Verified existing subject1/o1/2 +Converted subject3/h1/7 +Converted subject4/h1/7 +Verified existing subject1/o1/1 +Verified existing subject2/h1/1 +Verified existing subject1/o1/5 +Verified existing subject1/o2/0 +Converted subject3/h1/4 +Verified existing subject2/h1/5 +Verified existing subject1/o2/6 +Verified existing subject1/o2/3 +Verified existing subject2/o1/0 +Converted subject4/h1/4 +Verified existing subject1/o2/7 +Verified existing subject1/o2/4 +Converted subject3/h1/2 +Verified existing subject2/o1/6 +Converted subject4/h1/2 +Verified existing subject1/o2/2 +Verified existing subject2/o1/3 +Converted subject3/h1/1 +Verified existing subject1/o2/1 +Verified existing subject1/o2/5 +Verified existing subject1/k1/0 +Verified existing subject1/k1/6 +Verified existing subject2/o1/4 +Verified existing subject1/k1/3 +Converted subject3/h1/5 +Converted subject4/h1/1 +Verified existing subject1/k1/7 +Verified existing subject2/o1/2 +Converted subject4/h1/5 +Converted subject3/o1/0 +Converted subject1/k1/4 +Converted subject4/o1/0 +Verified existing subject2/o1/1 diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/full.status b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/full.status new file mode 100644 index 0000000000000000000000000000000000000000..e8e02acf783f15b30d41ed45d921baf847c4db74 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/full.status @@ -0,0 +1,7 @@ +START=2026-09-30T11:03:05+08:00 +WORKERS=4 CODEC_THREADS=10 DECODE_THREADS=10 DEPTH_THREADS=4 SUBJECTS=1,2,3,4 CASA=false +CPU_LIMIT=none +CGROUP=/user.slice/user-25044.slice/user@25044.service/app.slice/h2o-full-d10-20260930.scope +CPU_MAX=max controller_disabled + +RECONFIGURE=2026-09-30T15:47:55+08:00 REASON=process16_camera_pipeline_ram32_streaming diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/run-full.sh b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/run-full.sh new file mode 100644 index 0000000000000000000000000000000000000000..eefa21bbb201a5ad30462ad7548f980793d762b0 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/run-full.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -u +base="$HOME/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10" +raw="$HOME/Datasets/Hand-Datasets-Raw/H2O" +cd "$HOME/Projects/uni-hoi-dataset" || exit 1 +mkdir -p "$base/scratch" +export TMPDIR="$base/scratch" PYTHONUNBUFFERED=1 +for n in 1 2 3 4; do test -s "$raw/raw/data/subject${n}_v1_1.tar.gz" || exit 2; done +test ! -e "$base/full.status" || exit 3 +cg=$(awk -F: '$1=="0" {print $3}' /proc/self/cgroup) +if [[ -f "/sys/fs/cgroup$cg/cpu.max" ]]; then + read -r quota period < "/sys/fs/cgroup$cg/cpu.max" +else + quota=max + period=controller_disabled +fi +printf 'START=%s\nWORKERS=4 CODEC_THREADS=10 DECODE_THREADS=10 DEPTH_THREADS=4 SUBJECTS=1,2,3,4 CASA=false\nCPU_LIMIT=none\nCGROUP=%s\nCPU_MAX=%s %s\n' "$(date -Is)" "$cg" "$quota" "$period" > "$base/full.status" +if [[ "$quota" != max ]]; then + printf 'EXIT=4 ERROR=UNEXPECTED_CPU_QUOTA\n' >> "$base/full.status" + exit 4 +fi +/usr/bin/time -v .venv/bin/python "$base/frozen-code/scripts/convert_h2o_v1.0.py" --root "$raw" --out "$base" --release-id shared-v1.0 --workers 4 --codec-threads 10 --decode-threads 10 --depth-threads 4 --mano-dir "$HOME/Projects/WiLoR/mano_data" > "$base/full.log" 2>&1 +code=$? +printf 'EXIT=%s END=%s\n' "$code" "$(date -Is)" >> "$base/full.status" +if [[ -f "/sys/fs/cgroup$cg/cpu.stat" ]]; then cat "/sys/fs/cgroup$cg/cpu.stat" >> "$base/full.status"; fi +exit "$code" diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/check_dexycb_projection.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/check_dexycb_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..2774c004fc1359dea582135ec7171f600b33b336 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/check_dexycb_projection.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Check saved Dex-YCB source 3D joints against saved source 2D joints in sampled views.""" +import json +from pathlib import Path +import sys + +import numpy as np +import torch + +root = Path(sys.argv[1]) +report = json.loads((root / 'doc/validation/STRUCTURAL_AUDIT.json').read_text()) +checks = [] +for name in report['sampled_views']: + view = root / name + load = lambda path: torch.load(view / path, weights_only=True, map_location='cpu').numpy() + k = load('camera/intrinsic.pt') + xyz = load('annotation/keypoints/xyz.pt') + uv = load('annotation/keypoints/uv.pt') + valid = load('annotation/keypoints/xyz_valid.pt') & load('annotation/keypoints/uv_valid.pt') + z = xyz[..., 2] + valid &= np.isfinite(xyz).all(axis=-1) & np.isfinite(uv).all(axis=-1) & (z > 0) + z = np.where(valid, z, 1) + pred = np.stack((k[:, 0, 0, None, None] * xyz[..., 0] / z + k[:, 0, 2, None, None], + k[:, 1, 1, None, None] * xyz[..., 1] / z + k[:, 1, 2, None, None]), axis=-1) + errors = np.linalg.norm(pred[valid] - uv[valid], axis=-1) + checks.append(dict(view=name, points=int(errors.size), median_px=float(np.median(errors)) if errors.size else None, + p95_px=float(np.percentile(errors, 95)) if errors.size else None)) +(root / 'doc/validation/KEYPOINT_PROJECTION_QC.json').write_text(json.dumps({ + 'scope': 'Saved source 3D joints projected with saved color intrinsics vs saved source 2D joints; independent of hand mesh rendering.', + 'views': checks}, ensure_ascii=False, indent=2) + '\n') +print(json.dumps(checks, ensure_ascii=False), flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/config.json b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/config.json new file mode 100644 index 0000000000000000000000000000000000000000..9254fc637be8ba8821d246948787c09c5cb890c4 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/config.json @@ -0,0 +1,17 @@ +{ + "root": "/home/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O", + "out": "/home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10", + "release_id": "shared-v1.0", + "limit": null, + "max_frames": null, + "mano_dir": "/home/xuzhefeng/Projects/WiLoR/mano_data", + "views": null, + "jpeg_full_check": false, + "workers": 4, + "codec_threads": 10, + "decode_threads": 10, + "depth_threads": 4, + "subjects": null, + "include_casa": false, + "archive": null +} diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/convert_dexycb_v1.0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/convert_dexycb_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..ed3f479787fae378b3d3b51ce2f58ccaebfd3d0f --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/convert_dexycb_v1.0.py @@ -0,0 +1,349 @@ +#!/usr/bin/env python3 +"""Dex-YCB source annotations → CONTRACT.md v1.0. No derived annotations.""" +import io +import re +import shutil +import tarfile +import tempfile +from pathlib import Path + +import numpy as np +from PIL import Image +import yaml + +from warehouse_v1_0 import (View, build_record, find_file, locator, mano_models, mesh_asset, + model_profile, parser, pca_to_axis_angle, release, roots, safe_member, sequence_dir) + +IMG_W, IMG_H = 640, 480 + +class _Loader(yaml.SafeLoader): + pass + + +_Loader.add_constructor("tag:yaml.org,2002:python/tuple", + lambda l, n: tuple(l.construct_sequence(n))) + + +def yaml_load_bytes(data: bytes): + return yaml.load(io.BytesIO(data), Loader=_Loader) + + +class Calibration: + def __init__(self, dexycb_root: Path): + self.intrinsics = {} # serial -> {fx,fy,cx,cy,w,h} + self.extrinsics = {} # group -> {serial: [12] 行优先 3×4 cam→world} + self.betas = {} # mano_calib_name -> [10] + calib_dir = dexycb_root / "calibration" + if calib_dir.is_dir(): + self._load((p.as_posix(), p.read_bytes()) + for p in sorted(calib_dir.rglob("*")) if p.is_file()) + else: + tar_path = dexycb_root / "calibration.tar.gz" + if not tar_path.exists(): + raise FileNotFoundError(f"no calibration/ nor calibration.tar.gz in {dexycb_root}") + with tarfile.open(tar_path, "r:gz") as tf: + self._load((m.name, tf.extractfile(m).read()) for m in tf if m.isfile()) + + _RE_INTR = re.compile(r"(?:^|/)intrinsics/(\d+)_\d+x\d+\.yml$") + _RE_EXTRA = re.compile(r"(?:^|/)extrinsics_(\d{8}_\d{6})/extrinsics\.yml$") + _RE_MANO = re.compile(r"(?:^|/)mano_(\d{8}_\d{6}_subject-\d{2}_right)/mano\.yml$") + + def _load(self, files): + for rel, data in files: + m = self._RE_INTR.search(rel) + if m: + c = yaml_load_bytes(data)["color"] + self.intrinsics[m.group(1)] = {"fx": float(c["fx"]), "fy": float(c["fy"]), + "cx": float(c["ppx"]), "cy": float(c["ppy"]), + "w": IMG_W, "h": IMG_H} + continue + m = self._RE_EXTRA.search(rel) + if m: + raw = yaml_load_bytes(data)["extrinsics"] + self.extrinsics[m.group(1)] = { + str(s): [float(x) for x in np.asarray(v).ravel()] for s, v in raw.items()} + continue + m = self._RE_MANO.search(rel) + if m: + self.betas[m.group(1)] = [float(b) for b in yaml_load_bytes(data)["betas"]] + + + +def calibration_locator(path, member, **extra): + if path.is_dir(): + return locator(path / member.removeprefix('calibration/'), **extra) + return locator(path, member, **extra) + + +def prepare_models(root, destination): + archive = find_file(root, 'models.tar.gz') + if archive is None: + return {}, None + pattern = re.compile(r'^models/(\d{3}_[a-z0-9_]+)/(textured_simple\.obj(?:\.mtl)?|texture_map\.png)$') + names = set() + with tarfile.open(archive, 'r|gz') as tf: + for member in tf: + match = pattern.fullmatch(member.name) + if member.isfile() and match: + names.add(match[1]) + path = safe_member(destination, '/'.join(match.groups())) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(tf.extractfile(member).read()) + if len(names) != 21: + raise ValueError('expected all 21 source YCB model directories') + return {i: destination / name for i, name in enumerate(sorted(names), 1)}, archive + + +def convert_view(path, args, seq, serial, frames, meta, meta_loc, calib, calib_path, models, assets, asset_archive): + total = int(meta.get('num_frames', max(frames) + 1)) + ids = list(range(min(total, args.max_frames) if args.max_frames else total)) + for f in ids: + frames.setdefault(f, {}) + if not ids: + raise ValueError('no RGB frames') + source_rows = [] + for f in ids: + row = frames[f] + source_rows.append(dict(source_frame_id=f, sync_id=f'{seq}:{f}', + source_locator=row['color'][1] if 'color' in row else (meta_loc | {'source_frame_id': f, 'missing_rgb': True}), annotation_matches={ + 'labels': {'source_frame_id': f, 'source_timestamp_ns': None, 'clock_domain': None, + 'match_method': 'index_map', 'delta_ns': None, 'source_locator': row['labels'][1]} + for _ in [0] if 'labels' in row}, + component_sources={k: v[1] for k, v in row.items()})) + view = View(path, 'dex-ycb', args.release_id, seq, serial, source_rows, + sampling='dense' if ids == list(range(ids[0], ids[-1] + 1)) else 'sparse') + view.valid_rules = { + 'mano': 'Source pose_m present and not all zero; side model/calibration available', + 'keypoints': 'Corresponding joint_2d/joint_3d present; whole-hand all -1 is missing, broadcast to its 21 points', + 'pose': 'Source pose_y for this ycb_ids slot present and not an all-zero matrix', + 'segment': 'Source seg array provided for this frame; region codes and entity references validated', + 'relations': 'Source sequence ycb_grasp_ind resolves through ycb_ids; broadcast sequence grasp to selected frames', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'exo' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} + subject = re.search(r'subject-(\d+)', seq) + if subject and 1 <= int(subject[1]) <= 10: + index = int(subject[1]) + view.meta.update(split='val' if index == 7 else 'test' if index in (8, 9) else 'train', + split_scheme='Dex-YCB/s1', split_source_locator={ + 'url': 'https://github.com/NVlabs/dex-ycb-toolkit/blob/master/dex_ycb_toolkit/dex_ycb.py', + 'rule': 's1 unseen-subject: 01-06/10 train, 07 val, 08-09 test'}) + view.meta.pop('split_reason', None) + view.rgb([frames[f]['color'][0] if 'color' in frames[f] else None for f in ids], {'frames_ref': 'camera/frames.jsonl'}) + n = len(ids) + intr = calib.intrinsics.get(serial) + K = None if intr is None else np.array([[intr['fx'], 0, intr['cx']], [0, intr['fy'], intr['cy']], [0, 0, 1]]) + ext = calib.extrinsics.get(str(meta['extrinsics']), {}).get(serial) + E = None + if ext is not None: + E = np.eye(4) + E[:3] = np.asarray(ext).reshape(3, 4) + E = np.linalg.inv(E) + view.camera(K, calibration_locator(calib_path, f'calibration/intrinsics/{serial}_640x480.yml'), E, + calibration_locator(calib_path, f'calibration/extrinsics_{meta["extrinsics"]}/extrinsics.yml', + conversion='inverse of source T_world_from_camera')) + sides = meta.get('mano_sides') + if sides not in (['left'], ['right']): + raise ValueError(f'expected exactly one anatomical source hand: {sides}') + side = sides[0] + slot = ['left', 'right'].index(side) + cal_name = meta['mano_calib'][0] if isinstance(meta['mano_calib'], list) else meta['mano_calib'] + labels = [dict(np.load(frames[f]['labels'][0])) if 'labels' in frames[f] else {} for f in ids] + label_loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources.labels'} + motion = np.full((n, 2, 61), np.nan, np.float32) + mv = np.zeros((n, 2), bool) + if side in models and any('pose_m' in lab for lab in labels): + for i, lab in enumerate(labels): + if 'pose_m' not in lab: + continue + pose = np.asarray(lab['pose_m']).reshape(51) + if not np.any(pose): # Official Dex-YCB missing-pose sentinel, independent of joints/seg. + continue + motion[i, slot] = np.r_[pose[:3], pca_to_axis_angle(pose[3:48], models[side]), + calib.betas[cal_name], pose[48:51]] + mv[i, slot] = True + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], label_loc, model_profile=model_profile(models), + calibration_source=calibration_locator(calib_path, f'calibration/mano_{cal_name}/mano.yml'), + provenance={'kind': 'format_conversion', 'method': 'source PCA @ hands_components + hands_mean; explicit axis-angle consumed with flat_hand_mean=true'}) + elif any('pose_m' in lab for lab in labels): + view.absent('mano', 'Source PCA exists; provide --mano-dir to expand it', 'dependency_missing') + else: + view.absent('mano', 'No source pose_m field') + for source_key, key, dim, unit in [('joint_2d', 'uv', 2, 'pixel'), ('joint_3d', 'xyz', 3, 'm')]: + if not any(source_key in x for x in labels): + view.absent('keypoints_' + key, 'No source ' + source_key) + continue + points = np.full((n, 2, 21, dim), np.nan, np.float32) + valid = np.zeros((n, 2, 21), bool) + for i, lab in enumerate(labels): + if source_key not in lab: + continue + p = np.asarray(lab[source_key]).reshape(21, dim) + points[i, slot] = p + valid[i, slot] = not np.all(p == -1) # Official sentinel covers the whole source hand. + # An individual off-image point (-1, -1) is not evidence of missing annotation. + view.tensor('keypoints_' + key, f'keypoints/{key}/v1', f'annotation/keypoints/{key}.pt', + points, valid, ['T', 'hand', 'keypoint', 'coordinate'], label_loc, + keypoint_schema='mano21/v1', unit=unit) + ycb_ids = [int(x) for x in meta['ycb_ids']] + for j, oid in enumerate(ycb_ids): + entity = f'ycb_{oid:02d}' + view.object(entity, meta_loc, source_object_id=oid, category_id=oid) + poses = np.full((n, 4, 4), np.nan, np.float32) + valid = np.zeros(n, bool) + for i, lab in enumerate(labels): + if 'pose_y' in lab: + pose = np.asarray(lab['pose_y']) + if pose.shape != (len(ycb_ids), 3, 4): + raise ValueError('pose_y shape differs from ycb_ids') + if np.any(pose[j]): # Official all-zero missing object pose sentinel. + poses[i] = np.eye(4) + poses[i, :3] = pose[j] + valid[i] = True + if any('pose_y' in lab for lab in labels): + view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', + poses, valid, ['T', 'row', 'column'], label_loc, + convention='T_camera_from_object', unit='m') + else: + view.absent('pose_' + entity, 'No source pose_y field') + if oid in assets: + mesh_asset(view, entity, assets[oid], assets[oid] / 'textured_simple.obj', + locator(asset_archive, f'models/{assets[oid].name}/textured_simple.obj')) + else: + view.absent('mesh_' + entity, 'models.tar.gz unavailable', 'not_downloaded') + if any('seg' in lab for lab in labels): + mask_rows = [] + width, height = view.meta['camera']['image_size'] + for i, lab in enumerate(labels): + values = np.unique(lab.get('seg', np.zeros((height, width), np.uint8))) + mappings = [] + for value in values: + value = int(value) + if value == 0: + continue + if value != 255 and value not in ycb_ids: + raise ValueError(f'unknown Dex-YCB region value {value}') + mappings.append(dict(mask_value=value, category_id='hand' if value == 255 else value, + entity_id='hand_' + side if value == 255 else f'ycb_{value:02d}', part_id=None, + source_instance_id=value)) + mask_rows.append(dict(frame_index=i, labels=mappings)) + view.raster('segment', (lab.get('seg', np.zeros((height, width), np.uint16)) for lab in labels), + ['seg' in lab for lab in labels], label_loc, mask_rows) + view.meta['components']['segment'].update(coverage={'kind': 'selected_entities', + 'entities': ['hand_' + side] + [f'ycb_{o:02d}' for o in ycb_ids]}, source_zero_meaning='background') + else: + view.absent('segment', 'No source seg field') + if any('aligned_depth_to_color' in frames[f] for f in ids): + def depths(): + width, height = view.meta['camera']['image_size'] + for f in ids: + item = frames[f].get('aligned_depth_to_color') + if item is None: + yield np.full((height, width), np.nan, np.float32) + else: + with Image.open(item[0]) as im: + yield np.asarray(im).astype(np.float32) / 1000.0 + view.raster('depth', depths(), None, {'frames_ref': 'camera/frames.jsonl', + 'source_field': 'component_sources.aligned_depth_to_color', 'conversion': 'millimetres to metres'}) + else: + view.absent('depth', 'No source aligned_depth_to_color frames') + grasp = meta.get('ycb_grasp_ind') + if grasp is not None: + if not 0 <= int(grasp) < len(ycb_ids): + raise ValueError('invalid ycb_grasp_ind') + relation = dict(relation_type='grasp', subject_id='hand_' + side, + object_id=f'ycb_{ycb_ids[int(grasp)]:02d}', status='positive', source_locator=meta_loc, + provenance={'kind': 'source', 'method': 'sequence ycb_grasp_ind resolved through ycb_ids; not per-frame contact'}) + view.relations([{'frame_index': i, 'relations': [relation]} for i in range(n)], np.ones(n, bool), meta_loc) + else: + view.absent('relations', 'No source grasp/contact relation') + return view.finish() + + +MEMBER = re.compile(r'^([^/]+)/(\d{8}_\d{6})/(meta\.yml|(\d{12})/(color|labels|aligned_depth_to_color)_(\d+)\.(jpg|npz|png))$') + + +def convert_archive(archive, args, out, calib, calib_path, models, assets, asset_archive): + selected_views = set(args.views.split(',')) if args.views else None + done = 0 + current, meta, meta_loc, rows = None, None, None, {} + with tempfile.TemporaryDirectory(prefix='dex-source-') as wd: + work = Path(wd) + def flush(): + nonlocal done + if not rows: + return + seq = archive.name.split('.tar')[0] + '_' + current + reports = {} + with sequence_dir(out, seq) as target: + for serial, frames in sorted(rows.items()): + reports[serial] = convert_view(target / serial, args, seq, serial, frames, meta, + meta_loc, calib, calib_path, models, assets, asset_archive) + build_record(out, seq, reports) + for staged in list(work.iterdir()): + if staged.is_dir(): + shutil.rmtree(staged) + else: + staged.unlink() + done += 1 + print(f'Converted {seq}', flush=True) + with tarfile.open(archive, 'r|gz') as tf: + for member in tf: + match = MEMBER.fullmatch(member.name) + if not member.isfile() or not match: + continue + seq = match[2] + if seq != current: + flush() + if args.limit and done >= args.limit: + break + current, meta, meta_loc, rows = seq, None, None, {} + data_kind = match[3] + if data_kind == 'meta.yml': + data = tf.extractfile(member).read() + meta = yaml_load_bytes(data) + meta_loc = locator(archive, member.name, data) + continue + serial, kind, f = match[4], match[5], int(match[6]) + if selected_views and serial not in selected_views or args.max_frames and f >= args.max_frames: + continue + data = tf.extractfile(member).read() + dest = safe_member(work, member.name) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(data) + row = rows.setdefault(serial, {}).setdefault(f, {}) + if kind in row: + raise ValueError('duplicate archive frame') + row[kind] = (dest, locator(archive, member.name, data)) + else: + flush() + return done + + +def main(argv=None): + p = parser('dex-ycb', __doc__) + p.add_argument('--subjects') + args = p.parse_args(argv) + archives = sorted({a for r in roots(args.root) for a in r.glob('*-subject-*.tar.gz')}) + if args.subjects: + subjects = {s.strip().zfill(2) for s in args.subjects.split(',')} + archives = [a for a in archives if re.search(r'subject-(\d+)', a.name)[1] in subjects] + if not archives: + p.error('no Dex-YCB subject archives found') + cp = find_file(args.root, 'calibration.tar.gz') or find_file(args.root, 'calibration') + if cp is None: + p.error('calibration source missing') + calib = Calibration(cp.parent) + models = mano_models(args.mano_dir) + out = release(args, 'dex-ycb') + with tempfile.TemporaryDirectory(prefix='dex-models-') as wd: + assets, asset_archive = prepare_models(args.root, Path(wd)) + for archive in archives: + convert_archive(archive, args, out, calib, cp, models, assets, asset_archive) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/convert_h2o_v1.0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/convert_h2o_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..18418915638cf2f536e14fd1069b8441d10ea082 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/convert_h2o_v1.0.py @@ -0,0 +1,545 @@ +#!/usr/bin/env python3 +"""H2O native RGB-D, MANO, joints and objects → CONTRACT.md v1.0 (no rendered masks).""" +from concurrent.futures import ThreadPoolExecutor +import json +import os +import re +import shutil +import tarfile +import tempfile +from pathlib import Path +import zipfile + +# Bound native libraries before loading NumPy/Torch; each worker still uses independent FFmpeg processes. +for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + +import numpy as np +from PIL import Image +import torch + +from warehouse_v1_0 import (View, build_record, check_mesh, find_file, locator, mano_models, mesh_asset, + model_profile, parser, release, roots, safe_member, sequence_dir, sha256) + +OBJECTS = {1: 'book', 2: 'espresso', 3: 'lotion', 4: 'spray', + 5: 'milk', 6: 'cocoa', 7: 'chips', 8: 'cappuccino'} +MEMBER = re.compile(r'^(?:h2o_CASA/)?(subject\d+)/([^/]+)/(\d+)/(cam\d)/(.+)$') +FRAME = re.compile(r'(rgb|depth|cam_pose|hand_pose|hand_pose_mano|obj_pose|obj_pose_rt)/(\d+)\.(png|jpg|txt)$') + + +def load_splits(root): + archive = find_file(root, 'label_split.zip') + result = {} + if archive is not None: + with zipfile.ZipFile(archive) as z: + for split in ('train', 'val', 'test'): + member = f'label_split/action_{split}.txt' + for line_no, line in enumerate(z.read(member).decode().splitlines(), 1): + fields = line.split() + if len(fields) < 2 or fields[1] == 'path': + continue + key = fields[1] + if key in result and result[key][0] != split: + raise ValueError('conflicting official splits') + result[key] = (split, locator(archive, member, record=line_no)) + return result + + +def load_assets(root, work): + archive = find_file(root, 'object.zip') + if archive is None: + return {}, None + with zipfile.ZipFile(archive) as z: + for member in z.infolist(): + if member.is_dir(): + continue + path = safe_member(work, member.filename) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(z.read(member)) + result = {} + for oid, name in OBJECTS.items(): + directory = work / 'object' / name + aliases = [] + # Source cocoa.obj -> ovomaltine.mtl -> cocoa.png, but the ZIP names the + # supplied texture ovomaltine.png. Keep all originals and add a byte-identical alias. + if name == 'cocoa' and not (directory / 'cocoa.png').exists(): + mtl = directory / 'ovomaltine.mtl' + if mtl.is_file() and 'map_Kd cocoa.png' in mtl.read_text().splitlines(): + texture = directory / 'ovomaltine.png' + shutil.copyfile(texture, directory / 'cocoa.png') + aliases.append({'file': 'cocoa.png', 'sha256': sha256(texture), + 'source': locator(archive, 'object/cocoa/ovomaltine.png')}) + candidates = list(directory.glob('*.obj')) + if len(candidates) != 1: + raise ValueError(f'expected one source OBJ for {name}') + check_mesh(candidates[0], directory) # Fail before decoding any large subject archive. + result[oid] = (directory, candidates[0], aliases) + return result, archive + + +def convert_view(path, args, seq, cam, rows, intr, splits, models, assets, asset_archive): + codec_threads = getattr(args, 'codec_threads', 1) + ids = list(range(min(rows), max(rows) + 1)) + for f in ids: + rows.setdefault(f, {}) + n = len(ids) + if not n: + raise ValueError('no RGB frames') + split, split_loc = splits.get(seq, ('unknown', None)) + frame_rows = [dict(source_frame_id=f, sync_id=f'{seq}:{f}', source_locator=rows[f]['rgb'][1] if 'rgb' in rows[f] else {'sequence': seq, 'camera': cam, 'source_frame_id': f, 'missing_rgb': True}, + component_sources={k: item[1] for k, item in rows[f].items()}, + annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None) + for k in rows[f] if k != 'rgb'}) for f in ids] + view = View(path, 'H2O', args.release_id, seq.replace('/', '_'), cam, frame_rows, split=split) + view.valid_rules = { + 'mano': 'Per-hand hand_pose_mano flag equals 1; corresponding side model available', + 'keypoints': "Per-hand hand_pose flag equals 1, broadcast to that hand's 21 source points independently of MANO", + 'pose': 'Source obj_pose_rt class equals this nonzero object class', + 'points': 'Source obj_pose class equals this nonzero object class, broadcast to its 21 points', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'ego' if cam == 'cam4' else 'exo' if cam in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} + if split_loc: + view.meta.update(split_scheme='official_action_split', split_source_locator=split_loc) + # In the measured 275 H2O views, exact FFV1 was always smaller than exact H.264. + view.rgb([rows[f]['rgb'][0] if 'rgb' in rows[f] else None for f in ids], + {'frames_ref': 'camera/frames.jsonl'}, ffv1_first=True, codec_threads=codec_threads) + loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} + if intr is not None: + fx, fy, cx, cy, width, height = np.loadtxt(intr[0]).ravel() + if [int(width), int(height)] != view.meta['camera']['image_size']: + raise ValueError('source intrinsics resolution mismatch') + K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) + view.camera(K, intr[1]) + camps = np.full((n, 4, 4), np.nan, np.float32) + cv = np.zeros(n, bool) + data = [] + for i, f in enumerate(ids): + lab = {k: np.loadtxt(item[0]).ravel() for k, item in rows[f].items() if k not in ('rgb', 'depth')} + data.append(lab) + if 'cam_pose' in lab: + camps[i] = np.linalg.inv(lab['cam_pose'].reshape(4, 4)) + cv[i] = True + if cv.any(): + view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', camps, cv, + ['T', 'row', 'column'], loc, convention='T_camera_from_world', + source_convention='T_world_from_camera') + motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) + points, pv = np.full((n, 2, 21, 3), np.nan, np.float32), np.zeros((n, 2, 21), bool) + object_ids = set() + for i, lab in enumerate(data): + if 'hand_pose_mano' in lab: + hands = lab['hand_pose_mano'].reshape(2, 62) + for side, row in enumerate(hands): + if row[0] not in (0, 1): + raise ValueError('unexpected H2O MANO presence flag') + if row[0] == 1: + motion[i, side] = np.r_[row[4:52], row[52:62], row[1:4]] + mv[i, side] = True + if 'hand_pose' in lab: + hands = lab['hand_pose'].reshape(2, 64) + for side, row in enumerate(hands): + if row[0] not in (0, 1): + raise ValueError('unexpected H2O keypoint presence flag') + if row[0] == 1: + points[i, side] = row[1:].reshape(21, 3) + pv[i, side] = True + for key in ('obj_pose', 'obj_pose_rt'): + if key in lab and lab[key][0] != 0: + object_ids.add(int(lab[key][0])) + if any('hand_pose_mano' in lab for lab in data): + if len(models) == 2: + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) + else: + view.absent('mano', 'Source parameters exist; --mano-dir must identify both model profiles', 'dependency_missing') + if any('hand_pose' in lab for lab in data): + view.tensor('keypoints_xyz', 'keypoints/xyz/v1', 'annotation/keypoints/xyz.pt', points, pv, + ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='m') + for oid in sorted(object_ids): + if oid not in OBJECTS: + raise ValueError(f'unknown H2O object class {oid}') + entity = OBJECTS[oid] + view.object(entity, loc, category_id=oid, source_object_id=oid) + poses, ov = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + pts, kv = np.full((n, 21, 3), np.nan, np.float32), np.zeros((n, 21), bool) + for i, lab in enumerate(data): + if 'obj_pose_rt' in lab and lab['obj_pose_rt'][0] == oid: + poses[i] = lab['obj_pose_rt'][1:].reshape(4, 4) + ov[i] = True + if 'obj_pose' in lab and lab['obj_pose'][0] == oid: + pts[i] = lab['obj_pose'][1:].reshape(21, 3) + kv[i] = True + if ov.any(): + view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', + poses, ov, ['T', 'row', 'column'], loc, convention='T_camera_from_object', unit='m') + if kv.any(): + view.tensor('points_' + entity, 'object_keypoints/camera/v1', + f'annotation/object/{entity}/keypoints/xyz.pt', pts, kv, + ['T', 'keypoint', 'coordinate'], loc, keypoint_schema='H2O_official_object21', + keypoint_names=['center'] + [f'corner_{i}' for i in range(8)] + [f'edge_midpoint_{i}' for i in range(12)], + source_order='official obj_point_order.jpg: center, 8 corners, 12 edge midpoints', unit='m') + if oid in assets: + directory, obj, aliases = assets[oid] + asset_loc = locator(asset_archive, f'object/{entity}/{obj.name}') + if aliases: + asset_loc['texture_aliases'] = aliases + mesh_asset(view, entity, directory, obj, asset_loc) + else: + view.absent('mesh_' + entity, 'Source object.zip unavailable', 'not_downloaded') + if any('depth' in rows[f] for f in ids): + width, height = view.meta['camera']['image_size'] + depth_threads = getattr(args, 'depth_threads', 1) + def read_depth(f): + item = rows[f].get('depth') + if item: + with Image.open(item[0]) as im: + return np.asarray(im).astype(np.float32) / 1000.0 + return np.full((height, width), np.nan, np.float32) + def depths(): + if depth_threads == 1: + yield from map(read_depth, ids) + else: + with ThreadPoolExecutor(max_workers=depth_threads) as pool: + # Ordered batches bound decoded arrays to depth_threads frames per view. + for start in range(0, len(ids), depth_threads): + yield from pool.map(read_depth, ids[start:start + depth_threads]) + view.raster('depth', depths(), None, loc | {'source_field': 'component_sources.depth', + 'definition': 'https://github.com/taeinkwon/h2oplayer/blob/main/utils.py', + 'conversion': 'registered millimetre camera-Z to metres; no viewer range clipping'}, + codec_threads=codec_threads) + else: + view.absent('depth', 'No source depth frames') + view.absent('segment', 'H2O provides no native segmentation; rendering deferred to v2.0') + view.absent('relations', 'No source contact/grasp annotation') + return view.finish() + + +def convert_archive(archive, args, out, splits, models, assets, asset_archive): + selected_views = set(args.views.split(',')) if args.views else None + subjects = {'subject' + s.strip() for s in args.subjects.split(',')} if args.subjects else None + current, rows, intrinsics, done = None, {}, {}, 0 + published_views = set() + with tempfile.TemporaryDirectory(prefix='h2o-source-') as wd: + work = Path(wd) + def flush(): + nonlocal done + if not rows: + return + seq = '/'.join(current) + reports, pending = {}, {} + for cam, frames in sorted(rows.items()): + existing = out / 'data' / seq.replace('/', '_') / cam + if (existing / 'metainfo.json').is_file(): + old_frames = [json.loads(line) for line in (existing / 'camera/frames.jsonl').read_text().splitlines()] + if [f['source_frame_id'] for f in old_frames] != list(range(min(frames), max(frames) + 1)): + raise ValueError('existing view has different sampling; choose a new release-id') + for frame in old_frames: + incoming = frames.get(frame['source_frame_id'], {}) + previous = frame.get('component_sources', {}) + if set(previous) != set(incoming) or any(previous[k].get('sha256') != v[1].get('sha256') for k, v in incoming.items()): + raise ValueError('duplicate H2O view differs from the published source; choose a new release-id') + else: + pending[cam] = frames + if pending: + with sequence_dir(out, seq.replace('/', '_')) as target: + for cam, frames in pending.items(): + reports[cam] = convert_view(target / cam, args, seq, cam, frames, + intrinsics.get(cam), splits, models, assets, asset_archive) + build_record(out, seq.replace('/', '_'), reports) + for staged in list(work.iterdir()): + if staged.is_dir(): + shutil.rmtree(staged) + else: + staged.unlink() + done += 1 + print(f'{"Converted" if pending else "Verified existing"} {seq}', flush=True) + # Uncompressed CASA supports seeking over large frames; gzip is single-pass. + mode = 'r:' if archive.suffix == '.tar' else 'r|gz' + with tarfile.open(archive, mode) as tf: + for member in tf: + match = MEMBER.fullmatch(member.name) + if not member.isfile() or not match: + continue + subj, scene, seq, cam, tail = match.groups() + if subjects and subj not in subjects: + continue + key = (subj, scene, seq) + if key != current: + flush() + if args.limit and done >= args.limit: + break + current, rows, intrinsics = key, {}, {} + published_views = {view.name for view in + (out / 'data' / '_'.join(key)).glob('cam*') + if (view / 'metainfo.json').is_file()} + if selected_views and cam not in selected_views: + continue + frame = FRAME.fullmatch(tail) + if tail != 'cam_intrinsics.txt' and not frame: + continue + if frame and args.max_frames and int(frame[2]) >= args.max_frames: + continue + data = tf.extractfile(member).read() + dest = safe_member(work, member.name) + if cam not in published_views: + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(data) + # Published views still verify source bytes, but never read their staging paths. + item = (dest, locator(archive, member.name, data)) + if tail == 'cam_intrinsics.txt': + intrinsics[cam] = item + else: + kind, f = frame[1], int(frame[2]) + row = rows.setdefault(cam, {}).setdefault(f, {}) + if kind in row: + raise ValueError('duplicate H2O frame') + row[kind] = item + else: + flush() + return done + + +def main(argv=None): + p = parser('H2O', __doc__) + p.set_defaults(release_id='shared-v1.0') + p.add_argument('--workers', type=int, choices=range(1, 5), default=1, + help='Independent subject archives in parallel, 1..4; benchmark before using >2') + p.add_argument('--codec-threads', type=int, choices=(1, 2, 4, 8, 10), default=4, + help='FFV1 slice threads per encode; default 4, use 10 for the current full run') + p.add_argument('--decode-threads', type=int, choices=(1, 2, 4, 8, 10), default=1, + help='FFmpeg threads for source RGB decoding and decoded-media checks') + p.add_argument('--depth-threads', type=int, choices=(1, 2, 4), default=1, + help='Bounded ordered source depth PNG loading per worker') + p.add_argument('--subjects') + p.add_argument('--include-casa', action='store_true') + p.add_argument('--archive', type=Path, help='Convert one explicit source archive') + args = p.parse_args(argv) + os.environ['HAND_WAREHOUSE_FFMPEG_THREADS'] = str(args.decode_threads) + if args.include_casa and args.workers != 1: + p.error('CASA can share sequence IDs with subject archives; convert it sequentially in a separate release') + archives = [args.archive.expanduser()] if args.archive else sorted( + {a for root in roots(args.root) for a in root.glob('subject*_v1_1.tar.gz')}) + if args.subjects and not args.archive: + requested = {'subject' + s.strip() for s in args.subjects.split(',')} + archives = [arc for arc in archives if arc.name.split('_', 1)[0] in requested] + if args.include_casa: + casa = find_file(args.root, 'h2o_CASA.tar') + if casa: + archives.append(casa) + if not archives: + p.error('no H2O archives found') + out = release(args, 'H2O') + source_mapping = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/h2o-RAW_TO_SHARED.md', + Path(__file__).resolve().parents[1] / 'doc/RAW_TO_SHARED.md', + out / 'doc/RAW_TO_SHARED.md') if p.is_file()) + mapping = out / 'doc/RAW_TO_SHARED.md' + if mapping.exists() and mapping.read_bytes() != source_mapping.read_bytes(): + raise ValueError('RAW_TO_SHARED.md changed; choose a new release-id') + if not mapping.exists(): + shutil.copyfile(source_mapping, mapping) + torch.set_num_threads(1) + models, splits = mano_models(args.mano_dir), load_splits(args.root) + with tempfile.TemporaryDirectory(prefix='h2o-assets-') as wd: + assets, asset_archive = load_assets(args.root, Path(wd)) + def convert_one(archive): + return convert_archive(archive, args, out, splits, models, assets, asset_archive) + if args.workers == 1: + for archive in archives: + convert_one(archive) + else: + with ThreadPoolExecutor(max_workers=args.workers) as pool: + for archive, count in zip(archives, pool.map(convert_one, archives), strict=True): + print(f'Archive {archive.name}: {count} sequences', flush=True) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) + +# TODO(v2.0): 以下旧 MANO 网格和渲染分割代码仅保留备查;v1.0 不生成标注。 +# def load_mano_model(path: Path): +# """MPI MANO pkl → numpy 字典。shapedirs 在 pkl 内为 chumpy Select(对 (778,3,20) 基 +# 底 flat 选取前 10 个 shape 分量;idxs 已核实等价于 base[:,:,:10])。""" +# with open(path, "rb") as f: +# d = _ManoUnpickler(f, encoding="latin1").load() +# sd = d["shapedirs"] +# base = np.asarray(sd.a.x, np.float64) # (778, 3, 20) +# shapedirs = base.reshape(-1)[np.asarray(sd.idxs)].reshape(base.shape[0], 3, -1) +# jreg = d["J_regressor"] +# jreg = np.asarray(jreg.todense()) if hasattr(jreg, "todense") else np.asarray(jreg) +# return {"v_template": np.asarray(d["v_template"], np.float64), +# "shapedirs": shapedirs, +# "posedirs": np.asarray(d["posedirs"], np.float64), +# "weights": np.asarray(d["weights"], np.float64), +# "J_regressor": np.asarray(jreg, np.float64), +# "kintree": np.asarray(d["kintree_table"], np.int64), +# "faces": np.asarray(d["f"], np.int64)} +# +# +# def rodrigues(r): +# """axis-angle (N,3) → 旋转矩阵 (N,3,3)。公式 I + sinθ·K + (1−cosθ)·K²(已对 scipy 核验)。""" +# r = np.asarray(r, np.float64).reshape(-1, 3) +# th = np.linalg.norm(r, axis=1) +# R = np.zeros((len(r), 3, 3)) +# nz = th > 1e-12 +# R[~nz] = np.eye(3) +# k = r[nz] / th[nz, None] +# K = np.zeros((len(k), 3, 3)) +# K[:, 0, 1], K[:, 0, 2], K[:, 1, 2] = -k[:, 2], k[:, 1], -k[:, 0] +# K[:, 1, 0], K[:, 2, 0], K[:, 2, 1] = k[:, 2], -k[:, 1], k[:, 0] +# s, c = np.sin(th[nz])[:, None, None], np.cos(th[nz])[:, None, None] +# R[nz] = np.eye(3) + s * K + (1 - c) * (K @ K) +# return R +# +# +# def _mano_chain(model, betas, pose): +# """返回 (v_shaped, J, Rs, G):G 为 16 个关节的全局变换(平移列 = 关节位置)。""" +# v = model["v_template"] + np.einsum("nkc,c->nk", model["shapedirs"], betas) +# J = model["J_regressor"] @ v +# Rs = rodrigues(np.asarray(pose, np.float64).reshape(16, 3)) +# kt = model["kintree"] +# G = np.zeros((16, 4, 4)) +# for j in range(16): +# p = kt[0, j] if j else -1 +# loc = np.eye(4) +# loc[:3, :3] = Rs[j] +# loc[:3, 3] = J[j] - (J[p] if j else 0.0) +# G[j] = loc if not j else G[p] @ loc +# return v, J, Rs, G +# +# +# def mano_forward(model, betas, pose, transl): +# """MANO LBS 前向(经典蒙皮 M_j = G_j·G0_j⁻¹;对 hand_pose 21 关节实证 0.0 mm)。 +# pose: 48 axis-angle([0:3] 全局);返回相机系米顶点 (778,3)。""" +# v, J, Rs, G = _mano_chain(model, betas, pose) +# lrot = (Rs[1:] - np.eye(3)).ravel() +# v_posed = v + np.einsum("nkc,c->nk", model["posedirs"], lrot) +# kt = model["kintree"] +# G0 = np.zeros((16, 4, 4)) +# for j in range(16): +# p = kt[0, j] if j else -1 +# loc = np.eye(4) +# loc[:3, 3] = J[j] - (J[p] if j else 0.0) +# G0[j] = loc if not j else G0[p] @ loc +# M = np.einsum("nj,jab->nab", model["weights"], G @ np.linalg.inv(G0)) +# out = np.einsum("nab,nb->na", M[:, :3, :3], v_posed) + M[:, :3, 3] +# return out + np.asarray(transl, np.float64) +# +# +# def mano_chain_joints(model, betas, pose, transl): +# """16 个关节位置(相机系米)= 链平移列;自检用。""" +# _, _, _, G = _mano_chain(model, betas, pose) +# return G[:, :3, 3] + np.asarray(transl, np.float64) +# +# +# def rasterize(verts_cam, faces, labels, W, H, fx, fy, cx, cy): +# z = verts_cam[:, 2] +# P = faces +# ok = (z[P] > 0.02).all(1) # 任一顶点在相机后 → 丢弃该三角形 +# P, labels = P[ok], labels[ok] +# if len(P) == 0: +# return np.zeros((H, W), np.uint16), np.zeros(0, np.int64) +# x = verts_cam[:, 0] / z * fx + cx +# y = verts_cam[:, 1] / z * fy + cy +# xa = np.maximum(0, np.minimum(np.floor(x[P[:, 0]]), np.minimum( +# np.floor(x[P[:, 1]]), np.floor(x[P[:, 2]]))).astype(np.int64)) +# xb = np.minimum(W - 1, np.maximum(np.ceil(x[P[:, 0]]), np.maximum( +# np.ceil(x[P[:, 1]]), np.ceil(x[P[:, 2]]))).astype(np.int64)) +# ya = np.maximum(0, np.minimum(np.floor(y[P[:, 0]]), np.minimum( +# np.floor(y[P[:, 1]]), np.floor(y[P[:, 2]]))).astype(np.int64)) +# yb = np.minimum(H - 1, np.maximum(np.ceil(y[P[:, 0]]), np.maximum( +# np.ceil(y[P[:, 1]]), np.ceil(y[P[:, 2]]))).astype(np.int64)) +# xa, ya = np.minimum(xa, xb), np.minimum(ya, yb) # 完全出画的三角形 → 空 bbox +# wdt, hgt = xb - xa + 1, yb - ya + 1 +# cnt = wdt * hgt +# tot = int(cnt.sum()) +# tri = np.repeat(np.arange(len(P)), cnt) +# k = np.arange(tot) - (np.cumsum(cnt) - cnt)[tri] +# px = xa[tri] + k % wdt[tri] + 0.5 +# py = ya[tri] + k // wdt[tri] + 0.5 +# ax, ay = x[P[tri, 0]], y[P[tri, 0]] +# bx, by = x[P[tri, 1]], y[P[tri, 1]] +# cx_, cy_ = x[P[tri, 2]], y[P[tri, 2]] +# area = ((x[P[:, 1]] - x[P[:, 0]]) * (y[P[:, 2]] - y[P[:, 0]]) +# - (y[P[:, 1]] - y[P[:, 0]]) * (x[P[:, 2]] - x[P[:, 0]])) +# areat = area[tri] +# e0 = (bx - ax) * (py - ay) - (by - ay) * (px - ax) +# e1 = (cx_ - bx) * (py - by) - (cy_ - by) * (px - bx) +# e2 = (ax - cx_) * (py - cy_) - (ay - cy_) * (px - cx_) +# s = np.sign(areat) +# inside = (np.abs(areat) > 1e-9) & ((e0 * s >= 0) & (e1 * s >= 0) & (e2 * s >= 0)) +# px, py, tri = px[inside], py[inside], tri[inside] +# at = areat[inside] +# w0, w1, w2 = e1[inside] / at, e2[inside] / at, e0[inside] / at +# zz = w0 * z[P[tri, 0]] + w1 * z[P[tri, 1]] + w2 * z[P[tri, 2]] +# pix = py.astype(np.int64) * W + px.astype(np.int64) +# order = np.lexsort((zz, pix)) # 同像素按深度升序 → 首条即最近 +# pix, tri = pix[order], tri[order] +# first = np.unique(pix, return_index=True)[1] +# mask = np.zeros(H * W, np.uint16) +# win = tri[first] +# mask[pix[first]] = labels[win] + 1 # 临时标签 +1(0=背景) +# return mask.reshape(H, W), np.bincount(labels[win] + 1) +# +# +# # ============================================================================ +# # ffmpeg 写出与核验(与 convert_dexycb.py 同构) +# # ============================================================================ +# verts, faces_all, labels = [], [], [] +# for ti, (tid, kind) in enumerate(tracks): +# if kind == "hand_left" and b["mano"][0] > 0.5: +# verts.append(mano_forward(mano_models["left"], b["mano"][52:62], +# b["mano"][4:52], b["mano"][1:4])) +# faces_all.append(mano_models["left"]["faces"]) +# elif kind == "hand_right" and b["mano"][62] > 0.5: +# verts.append(mano_forward(mano_models["right"], b["mano"][114:124], +# b["mano"][66:114], b["mano"][63:66])) +# faces_all.append(mano_models["right"]["faces"]) +# elif isinstance(kind, tuple) and int(b["objp"][0]) == kind[1]: +# M = np.asarray(b["objrt"][1:17], np.float64).reshape(4, 4) +# V0, F0 = meshes[kind[1]] +# verts.append(V0 @ M[:3, :3].T + M[:3, 3]) +# faces_all.append(F0) +# else: +# continue +# labels.append(np.full(len(faces_all[-1]), ti)) +# if verts: +# V = np.concatenate(verts) +# offs = np.cumsum([0] + [len(v) for v in verts[:-1]]) +# F = np.concatenate([fa + o for fa, o in zip(faces_all, offs)]) +# mask, counts = rasterize(V, F, np.concatenate(labels), +# IMG_W, IMG_H, fx, fy, cx, cy) +# else: +# mask, counts = np.zeros((IMG_H, IMG_W), np.uint16), np.zeros(0, np.int64) +# lut = np.zeros(n_tracks + 1, np.uint16) +# for ti in range(n_tracks): +# present = ti + 1 < len(counts) and counts[ti + 1] > 0 +# if present: +# presence[tracks[ti][0]][f] = True +# if active_id[ti] is None: +# pid = next(i for i in range(1, 65535) if i not in used) +# used.add(pid) +# active_id[ti], seg_start[ti] = pid, f +# frame_maps[ti].append({"id": pid}) +# lut[ti + 1] = active_id[ti] +# elif active_id[ti] is not None: +# frame_maps[ti][-1]["frames"] = [seg_start[ti], f - 1] +# segments[ti].append([seg_start[ti], f - 1]) +# used.discard(active_id[ti]) +# active_id[ti] = None +# mw.write(lut[mask]) + + +# TODO(v2.0): 旧物体尺寸派生代码;v1.0 仅保留源物体关键点。 +# pts = np.asarray(b["objp"][1:64], np.float64).reshape(21, 3) +# half = np.abs((pts[1:9] - pts[0]) @ M[:3, :3]).max(0) +# obj_recs.append({ +# "track_id": f"o{classes.index(c)}", "frame": f, +# "mesh_ref": f"h2o/{OBJ_CLASSES[c]}.obj", +# "pose": {"quat": rotmat_to_quat_wxyz(M[:3, :3])[0].tolist(), +# "trans": M[:3, 3].tolist()}, +# "bbox_center3d": pts[0].tolist(), +# "bbox_size": (2 * half).tolist()}) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/convert_hoi4d_v1.0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/convert_hoi4d_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..9d5914d64ae72ee62564897743dfe5a41923e08d --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/convert_hoi4d_v1.0.py @@ -0,0 +1,595 @@ +#!/usr/bin/env python3 +"""HOI4D native observations and annotations → CONTRACT.md v1.0.""" +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from contextlib import ExitStack +from functools import lru_cache +import gzip +import io +import json +import os +from pathlib import Path +import pickle +import re +import shutil +import shlex +import posixpath +import subprocess +import tempfile +import tarfile +import threading +import zipfile + +# Each worker owns one Python thread; prevent native libraries spawning CPU pools. +for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + +import numpy as np +from PIL import Image +from scipy.spatial.transform import Rotation + +import torch + +from warehouse_v1_0 import (View, build_record, check_mesh, decode_args, find_file, json_write, locator, + mano_models, model_profile, parser, probe, release, run, safe_member, sequence_dir) + +CATEGORIES = { + 1: dict(cad="rigid/ToyCar", groups=[("main", [1], "Toy Car", 1)], + hands={2: "right"}, objmap={"Toycar": "main"}), + 2: dict(cad="rigid/Mug", groups=[("a", [1], "Mug", 2), ("b", [3], "Mug", 2)], + hands={2: "right"}, objmap={"Watercup": "a"}), + 3: dict(cad="articulated/Laptop", groups=[("main", [1, 3], "Laptop", 3)], + hands={2: "right"}, + objmap={"Laptopdisplay": "main", "Laptopkeyboard": "main"}), + 4: dict(cad="articulated/StorageFurniture", + groups=[("main", [1, 3, 4], "Storage Furniture", 4), + ("bottle", [5], "Bottle", 5)], + hands={2: "right"}, + objmap={"Lockerbody": "main", "Lockersldingdoor": "main", + "Lockerdrawer": "main", "Safebox": "main"}), + 5: dict(cad="rigid/Bottle", groups=[("main", [1], "Bottle", 5), + ("mug", [3], "Mug", 2)], + hands={2: "right"}, objmap={"bottleddrinks": "main"}), + 6: dict(cad="articulated/Safe", groups=[("main", [1, 3], "Safe", 6), + ("bottle", [4], "Bottle", 5)], + hands={2: "right"}, objmap={"Safebox": "main", "Safedoor": "main"}), + 7: dict(cad="rigid/Bowl", groups=[("main", [1], "Bowl", 7), + ("ball", [3], "Ball", None)], + hands={2: "right"}, objmap={"bowl": "main"}), + 8: dict(cad="articulated/Bucket", + groups=[("a", [1, 3], "Bucket", 8), ("b", [4, 5], "Bucket", 8)], + hands={2: "right", 6: "left"}, + objmap={"bucket": "a", "Buckethandle": "a"}), + 9: dict(cad="articulated/Scissors", groups=[("main", [1, 3], "Scissors", 9)], + hands={2: "right"}, + objmap={"scissors": "main", "scissors2": None}), # scissors2:场景道具,无掩码 + 11: dict(cad="articulated/Pliers", groups=[("main", [1, 3], "Pliers", 11)], + hands={2: "right"}, objmap={"Pliersleft": "main", "Pliersright": "main"}), + 12: dict(cad="rigid/Kettle", groups=[("main", [1], "Kettle", 12), + ("mug", [3], "Mug", 2)], + hands={2: "right"}, objmap={"kettle": "main"}), + 13: dict(cad="rigid/Knife", groups=[("main", [1], "Knife", 13), + ("apple", [3], "Apple", None)], + hands={2: "right"}, objmap={"knife": "main"}), + 14: dict(cad="articulated/TrashCan", + groups=[("main", [1, 3], "Trash Can", 14), ("bottle", [4], "Bottle", 5)], + hands={2: "right"}, objmap={"Dustbinbase": "main", "Dustbincover": "main"}), + 17: dict(cad="articulated/Lamp", groups=[("main", [1, 3, 4, 5], "Lamp", 17)], + hands={2: "right", 6: "left"}, + objmap={"Lampbase": "main", "Tablelampfirstjoint": "main", + "Tablelampsecondjoint": "main", "Thirdjointoftablelamp": "main"}), + 18: dict(cad="articulated/Stapler", + groups=[("main", [1, 3, 4], "Stapler", 18), ("paper", [5], "Paper", None)], + hands={2: "right", 6: "left"}, # 6=左手:官方 label.csv 缺列,实测修正 + objmap={"Staplerbase": "main", "Staplercover": "main"}), + 20: dict(cad="rigid/Chair", groups=[("main", [1], "Chair", 20)], + hands={2: "right", 3: "left"}, objmap={"chair": "main"}), +} + + +# Official HOI4D definitions/motion segmentation/label.csv; no spatial side inference. +REGION_NAMES = {1: {1: 'Toy Car', 2: 'Right Hand'}, 2: {1: 'Mug', 2: 'Right Hand', 3: 'Mug'}, 3: {1: 'Screen', 2: 'Right Hand', 3: 'Keyboard'}, 4: {1: 'Door', 2: 'Right Hand', 3: 'Body of the Cabinet', 4: 'Drawer', 5: 'Bottle'}, 5: {1: 'Bottle', 2: 'Right Hand', 3: 'Mug'}, 6: {1: 'Body of the Safe', 2: 'Right Hand', 3: 'Door', 4: 'Bottle'}, 7: {1: 'Bowl', 2: 'Right Hand', 3: 'Ball'}, 8: {1: 'Body of the Bucket', 2: 'Right Hand', 3: 'Handle', 4: 'Body of the Bucket', 5: 'Handle', 6: 'Left Hand'}, 9: {1: 'Left Part of the Scissors', 2: 'Right Hand', 3: 'Right Part of the Scissors'}, 11: {1: 'Left Part of the Pliers', 2: 'Right Hand', 3: 'Right Part of the Pliers'}, 12: {1: 'Kettle', 2: 'Right Hand', 3: 'Mug'}, 13: {1: 'Knife', 2: 'Right Hand', 3: 'Apple'}, 14: {1: 'Body of the Trash Can', 2: 'Right Hand', 3: 'Lid', 4: 'Bottle'}, 17: {1: 'Base', 2: 'Right Hand', 3: 'Tube', 4: 'Top Link', 5: 'Bottom Link', 6: 'Left Hand'}, 18: {1: 'Base', 2: 'Right Hand', 3: 'Slot', 4: 'Lid', 5: 'Paper'}, 20: {1: 'Chair', 2: 'Right Hand', 3: 'Left Hand'}} + + +class SplitFiles(io.RawIOBase): + """Read concatenated source gzip parts without concatenating 119 GB on disk.""" + def __init__(self, paths): + self.paths = iter(paths) + self.current = None + + def readable(self): + return True + + def readinto(self, buffer): + while True: + if self.current is None: + path = next(self.paths, None) + if path is None: + return 0 + self.current = path.open('rb') + n = self.current.readinto(buffer) + if n: + return n + self.current.close() + self.current = None + + def close(self): + if self.current is not None: + self.current.close() + super().close() + + +def extract_depths(root, sequences, work): + directory = find_file(root, 'DEPTH') + if directory is None: + return {}, [] + parts = sorted(directory.glob('HOI4D_depth_video.tar.gz*'), key=lambda p: int(p.name.split('.gz')[1] or 0)) + if not parts: + return {}, [] + wanted = {f'HOI4D_depth_video/{seq}/align_depth/depth_video.avi': seq for seq in sequences} + found = {} + with SplitFiles(parts) as joined, io.BufferedReader(joined) as inp, gzip.GzipFile(fileobj=inp) as gz: + with tarfile.open(fileobj=gz, mode='r|') as tf: + for member in tf: + if member.isfile() and member.name in wanted: + seq = wanted[member.name] + dest = work / (seq.replace('/', '_') + '.avi') + with tf.extractfile(member) as src, dest.open('wb') as dst: + shutil.copyfileobj(src, dst) + found[seq] = (dest, {'files': [str(p.resolve()) for p in parts], 'member': member.name}) + if len(found) == len(wanted): + break + return found, parts + + +def palette_mask(data): + with Image.open(io.BytesIO(data)) as im: + arr = np.asarray(im) + if arr.ndim == 2: + return arr.astype(np.uint16) + if arr.shape[-1] != 3: + raise ValueError('unsupported HOI4D mask representation') + # VOC's 256-color palette interleaves eight label bits into the high RGB bits. + # Invert it directly instead of sorting every pixel with np.unique. + if np.any(arr & np.array([31, 31, 63], dtype=np.uint8)): + raise ValueError('source mask has colors outside official VOC palette') + mask = np.zeros(arr.shape[:2], dtype=np.uint16) + for bit in range(8): + mask |= ((arr[..., bit % 3] >> (7 - bit // 3)) & 1).astype(np.uint16) << bit + return mask + + +# Four workers each reuse annotation and hand indices instead of rebuilding the ZIP directory. +@lru_cache(maxsize=8) +def index_frames(z): + index = {} + for name in z.namelist(): + parent, _, filename = name.rpartition('/') + stem, dot, suffix = filename.rpartition('.') + if not dot or not stem.isdigit() or suffix not in ('png', 'json', 'pickle'): + continue + entries = index.setdefault((parent + '/', '.' + suffix), {}) + f = int(stem) + if f in entries: + raise ValueError(f'duplicate frame number under {parent}') + entries[f] = name + return index + + +def frame_members(z, prefix, suffix): + return index_frames(z).get((prefix, suffix), {}) + + +def convert_sequence(seq, args, target, rgbz, annz, hpz, calz, cadz, paths, models, depth): + # ponytail: cache only one sequence's encoded annotation bytes; no decoded masks or CAD cache. + @lru_cache(maxsize=None) + def read_annotation(archive, name): + return archive.read(name) + + category = int(re.search(r'/C(\d+)/', seq)[1]) + definition = CATEGORIES.get(category) + if definition is None: + raise ValueError(f'category mapping unavailable: {category}') + prefix = f'HOI4D_annotations/{seq}' + mask_members = frame_members(annz, prefix + '/2Dseg/mask/', '.png') + shifted = frame_members(annz, prefix + '/2Dseg/shift_mask/', '.png') + if not mask_members: + mask_members = shifted + pose_members = frame_members(annz, prefix + '/objpose/', '.json') + hand_members = {side: frame_members(hpz, f'Hand_pose/handpose_{side}_hand/{seq}/', '.pickle') + for side in ('left', 'right')} if hpz else {'left': {}, 'right': {}} + with tempfile.TemporaryDirectory(prefix='hoi4d-source-') as wd: + work = Path(wd) + member = f'HOI4D_release/{seq}/align_rgb/image.mp4' + video = work / 'rgb.mp4' + with rgbz.open(member) as src, video.open('wb') as dst: + shutil.copyfileobj(src, dst) + info = probe(video) + if 'nb_frames' not in info: + info['nb_frames'] = json.loads(run(['ffprobe', '-v', 'error', '-count_frames', '-select_streams', 'v:0', + '-show_entries', 'stream=nb_read_frames', '-of', 'json', str(video)], stdout=subprocess.PIPE).stdout)['streams'][0]['nb_read_frames'] + n = int(info['nb_frames']) + if args.max_frames: + n = min(n, args.max_frames) + if shifted and mask_members != shifted and any(f not in mask_members and f in shifted for f in range(n)): + raise ValueError('shift_mask has frames absent from mask; correspondence unverified') + frames = [] + for f in range(n): + sources = {} + if f in mask_members: + sources['segment'] = locator(paths['annotations'], mask_members[f], read_annotation(annz, mask_members[f])) + if f in pose_members: + sources['object'] = locator(paths['annotations'], pose_members[f], read_annotation(annz, pose_members[f])) + for side in ('left', 'right'): + if f in hand_members[side]: + sources['hand_' + side] = locator(paths['hand'], hand_members[side][f], read_annotation(hpz, hand_members[side][f])) + frames.append(dict(source_frame_id=f, source_locator=locator(paths['release'], member, frame=f), + component_sources=sources, annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None) for k in sources})) + view = View(target, 'HOI4D', args.release_id, seq.replace('/', '_'), 'ego', frames) + view.valid_rules = { + 'mano': 'Matched side pickle contains poseCoeff, beta, trans and corresponding model available; zero angles are not missing', + 'keypoints': 'Matched side pickle contains kps2D; independently provided source points, no visibility gate', + 'pose': 'Matched source object record contains rotation and center; record identity retained', + 'dimensions': 'Matched source object record contains dimensions; size/mesh relation remains source_unspecified', + 'segment': 'Source mask or shift_mask present with verified palette codes and entity/part mapping', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'ego' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'source_sequence': seq} + view.rgb([], locator(paths['release'], member), video=video, count=n) + intr_name = f'camera_params/{seq.split("/")[0]}/intrin.npy' + if calz and intr_name in calz.namelist(): + view.camera(np.load(io.BytesIO(calz.read(intr_name))), locator(paths['camera'], intr_name)) + extr_name = prefix + '/3Dseg/output.log' + if extr_name in annz.NameToInfo: + lines = [line for line in annz.read(extr_name).decode().splitlines() if line.strip()] + if len(lines) % 5: + raise ValueError('invalid Open3D camera trajectory') + extr, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + for i in range(0, len(lines), 5): + idx = int(lines[i].split()[0]) + if idx < n: + if valid[idx]: + raise ValueError('duplicate trajectory index') + extr[idx] = np.linalg.inv(np.loadtxt(io.StringIO('\n'.join(lines[i + 1:i + 5])))) + valid[idx] = True + view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', extr, valid, + ['T', 'row', 'column'], locator(paths['annotations'], extr_name), + convention='T_camera_from_world', source_convention='Open3D LOG camera-to-world; inverted') + loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} + motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) + points, pv = np.full((n, 2, 21, 2), np.nan, np.float32), np.zeros((n, 2, 21), bool) + for slot, side in enumerate(('left', 'right')): + for f, name in hand_members[side].items(): + if f >= n: + continue + data = pickle.loads(read_annotation(hpz, name), encoding='latin1') + if all(k in data for k in ('poseCoeff', 'beta', 'trans')): + motion[f, slot] = np.r_[np.asarray(data['poseCoeff']).reshape(48), + np.asarray(data['beta']).reshape(10), np.asarray(data['trans']).reshape(3)] + mv[f, slot] = True # Zero angles are a valid pose, not a missing sentinel. + if 'kps2D' in data: + points[f, slot] = np.asarray(data['kps2D']).reshape(21, 2) + pv[f, slot] = True + if mv.any(): + if all(side in models for slot, side in enumerate(('left', 'right')) if mv[:, slot].any()): + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) + else: + view.absent('mano', 'Source MANO exists; provide --mano-dir to fix model identity', 'dependency_missing') + if pv.any(): + view.tensor('keypoints_uv', 'keypoints/uv/v1', 'annotation/keypoints/uv.pt', points, pv, + ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='pixel', + source_method='Upstream fitted MANO projection already present in kps2D') + objects = {} + groups = {key: (vals, name, cls) for key, vals, name, cls in definition['groups']} + def ensure_object(key, source_loc, category_id=None, frame=None, source_id=None): + if key not in objects: + view.object(key, source_loc, scope='frame' if frame is not None else 'sequence', + scope_id=f'{seq}:{frame}' if frame is not None else None, + category_id=category_id, source_object_id=source_id) + objects[key] = {} + mappings = [] + mask_valid = [f in mask_members for f in range(n)] + if any(mask_valid): + width, height = view.meta['camera']['image_size'] + def masks(): + for f in range(n): + labels = [] + if f in mask_members: + mask = palette_mask(read_annotation(annz, mask_members[f])) + for value in np.unique(mask): + value = int(value) + if value in (0, 255): + if value == 255: + raise ValueError('HOI4D 255 region semantics unverified') + continue + if REGION_NAMES[category].get(value) in ('Left Hand', 'Right Hand'): + entity, part, cls = 'hand_' + REGION_NAMES[category][value].split()[0].lower(), None, 'hand' + else: + group = next((k for k, (vals, _, _) in groups.items() if value in vals), None) + entity = group or f'unknown_region_{value}' + cls = groups[group][2] if group else None + part = f'region_{value}' if group and len(groups[group][0]) > 1 else None + ensure_object(entity, frames[f]['component_sources']['segment'], cls) + if part: + objects[entity].setdefault('parts', {})[part] = {'part_id': part, 'parent_id': None, + 'has_model': False, 'mesh_ref': None, 'source_region_code': value, 'name': REGION_NAMES[category].get(value)} + labels.append(dict(mask_value=value, category_id=cls, entity_id=entity, + part_id=part, source_instance_id=value, + source_attributes={'region_name': REGION_NAMES[category].get(value)})) + else: + mask = np.zeros((height, width), np.uint16) + mappings.append(dict(frame_index=f, labels=labels)) + yield mask + view.raster('segment', masks(), mask_valid, loc, mappings) + view.meta['components']['segment']['coverage'] = {'kind': 'unknown'} + if any(label['part_id'] for row in mappings for label in row['labels']): + view.meta['components']['segment']['segmentation_type'] = 'part' + else: + view.absent('segment', 'No native segmentation for this source sequence') + records = {} + for f, name in pose_members.items(): + if f >= n: + continue + data = json.loads(read_annotation(annz, name)) + # isEffective is not used to erase existing numerical annotations. + source_records = data.get('dataList', data.get('objects')) + if source_records is None: + raise ValueError('unrecognized source object annotation structure') + if category == 2 and source_records and (len(source_records) != 1 or + source_records[0].get('id') != 1 or source_records[0].get('label') != 'Watercup'): + raise ValueError('C2 native pose differs from the verified one-object target; cannot map to mask region 1') + label_counts = Counter(record['label'] for record in source_records) + per_frame = set() + for record_index, record in enumerate(source_records): + label = record['label'] + group = definition['objmap'].get(label) + # Pinned official ObjTracking reads dataList[0] with segmentation label 1. + source_primary = category == 2 and record_index == 0 and record.get('id') == 1 and group == 'a' + ambiguous = group is not None and sum(g[2] == groups[group][2] for g in groups.values()) > 1 and not source_primary + ambiguous = ambiguous or (label_counts[label] > 1 and not source_primary) or group is None + entity = f'pose_frame_{f}_{record_index}' if ambiguous else group + ensure_object(entity, locator(paths['annotations'], name, record=record_index), + groups[group][2] if group else None, frame=f if ambiguous else None, source_id=record.get('id')) + if ambiguous: + view.build['unresolved'].append({'component': entity, 'status': 'source_semantics_unverified', + 'reason': 'Source pose retained with frame identity; no guessed association to same-class mask instances'}) + label_key = (entity, label) + if label_key in per_frame: + raise ValueError(f'ambiguous repeated object label {label}; source identity must be resolved') + per_frame.add(label_key) + records.setdefault(label_key, {})[f] = (record, locator(paths['annotations'], name, record=record.get('id'))) + if category == 2 and any(entity == 'a' for entity, _ in records): + view.build['validation'].append({'component': 'C2_source_pose_mask_identity', + 'rule': 'Official ObjTracking process_data.py reads dataList[0] with semantic mask label 1', + 'source_revision': 'afa7bf37b02b7e33cf245acd08b98c207ccc175c', + 'source_pose_id': 1, 'mask_value': 1, 'matched_frames': sum(len(by_frame) for (entity, _), by_frame in records.items() if entity == 'a')}) + for (entity, label), by_frame in records.items(): + part_labels = [k[1] for k in records if k[0] == entity] + articulated = definition['cad'].startswith('articulated/') and entity == definition['groups'][0][0] + part = 'pose_' + re.sub(r'[^a-zA-Z0-9_]', '_', label) if articulated or len(part_labels) > 1 else None + base = f'annotation/object/{entity}' + if part: + base += '/parts/' + part + objects[entity].setdefault('parts', {})[part] = dict(part_id=part, parent_id=None, + has_model=False, mesh_ref=None, source_label=label) + poses, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + dimensions = np.full((n, 3), np.nan, np.float32) + dv = np.zeros(n, bool) + for f, (record, _) in by_frame.items(): + if all(k in record for k in ('rotation', 'center')): + poses[f] = np.eye(4) + poses[f, :3, :3] = Rotation.from_euler('XYZ', [record['rotation'][k] for k in ('x', 'y', 'z')]).as_matrix() + poses[f, :3, 3] = [record['center'][k] for k in ('x', 'y', 'z')] + valid[f] = True + if 'dimensions' in record: + dimensions[f] = [record['dimensions'][k] for k in ('length', 'width', 'height')] + dv[f] = True + key = entity + ('_' + part if part else '') + view.tensor('pose_' + key, 'transform/se3/v1' if part else 'object/rigid/v1', base + '/pose.pt', poses, valid, + ['T', 'row', 'column'], loc, convention='T_camera_from_part' if part else 'T_camera_from_object', + unit='m', source_label=label, source_euler_order='XYZ', + definition='https://github.com/hoi4d/ObjTracking/blob/main/process_data.py') + if dv.any(): + view.tensor('dimensions_' + key, 'object/dimensions/v1', base + '/dimensions.pt', dimensions, dv, + ['T', 'dimension'], loc, dimensions_semantics='source_unspecified', unit='m', scale_applied_to_mesh=False) + if cadz: + primary = definition['groups'][0][0] + if category != 2 and sum(g[2] == category for g in groups.values()) > 1: + primary = 'source_cad_instance' + instance = int(re.search(r'/N(\d+)/', seq)[1]) + mesh_prefix = f'HOI4D_CAD_Model_for_release/{definition["cad"]}/{instance:03d}' + candidates = [name for name in cadz.namelist() if not name.endswith('/') and + (name == mesh_prefix + '.obj' or name.startswith(mesh_prefix + '/'))] + if candidates: + # Retain OBJ material/texture dependencies beside their original names. + queue = list(candidates) + for name in queue: + if Path(name).suffix.lower() not in ('.obj', '.mtl'): + continue + for line in cadz.read(name).decode().splitlines(): + fields = shlex.split(line, comments=True) + if not fields: + continue + refs = fields[1:] if fields[0] == 'mtllib' else ([fields[-1]] if + fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal') else []) + for ref in refs: + dependency = posixpath.normpath(posixpath.join(posixpath.dirname(name), ref)) + if dependency not in cadz.NameToInfo: + raise ValueError(f'missing CAD dependency: {dependency}') + if dependency not in candidates: + candidates.append(dependency) + queue.append(dependency) + ensure_object(primary, locator(paths['cad'], mesh_prefix), category) + asset_dir = view.path / f'annotation/object/{primary}/assets' + asset_refs = [] + for name in candidates: + relative = posixpath.relpath(name, mesh_prefix if definition['cad'].startswith('articulated/') else posixpath.dirname(mesh_prefix)) + dest = safe_member(asset_dir, relative) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(cadz.read(name)) + ref = dest.relative_to(view.path).as_posix() + if dest.suffix.lower() == '.obj': + asset_key = re.sub(r'[^a-zA-Z0-9_]', '_', relative) + view.component('mesh_' + primary + '_' + asset_key, 'mesh/obj/v1', ref, ['vertex'], + locator(paths['cad'], name), unit='m', valid=True, + scale_applied_to_mesh=False, dimensions_semantics='source_unspecified') + asset_refs.append(ref) + if definition['cad'].startswith('articulated/'): + part_id = 'asset_' + asset_key + objects[primary].setdefault('parts', {})[part_id] = dict(part_id=part_id, + parent_id=None, has_model=True, mesh_ref=ref, source_asset=relative, + note='Source asset; correspondence to motion part labels remains unverified') + for asset_ref in asset_refs: + mesh_check = check_mesh(view.path / asset_ref, asset_dir) + view.build['validation'].append({'component': asset_ref, **mesh_check, + 'unit_basis': 'official ObjTracking loads source canonical CAD without scaling in metre camera coordinates', + 'geometric_acceptance': 'physical dimensions-to-mesh relation remains source_unspecified'}) + metadata_path = view.path / f'annotation/object/{primary}/metainfo.json' + metadata = json.loads(metadata_path.read_text()) + metadata.update(has_model=bool(asset_refs), asset_refs=asset_refs) + if definition['cad'].startswith('rigid/') and len(asset_refs) == 1: + metadata['mesh_ref'] = asset_refs[0] + json_write(metadata_path, metadata) + if definition['cad'].startswith('articulated/'): + view.build['unresolved'].append({'component': 'object_part_asset_association', + 'status': 'source_semantics_unverified', + 'reason': 'All source assets and motion labels retained, but no guessed correspondence or joint_state'}) + for entity, info in objects.items(): + if 'parts' in info: + ref = f'annotation/object/{entity}/articulation.json' + json_write(view.path / ref, {'parts': list(info['parts'].values()), 'joints': [], + 'hierarchy_semantics': 'semantic_containment', + 'note': 'Unassociated source region, motion and asset nodes; original CAD trees retained in assets'}) + view.component('articulation_' + entity, 'object/articulated/v1', ref, [], loc) + meta_path = view.path / f'annotation/object/{entity}/metainfo.json' + metadata = json.loads(meta_path.read_text()) + metadata['articulation_ref'] = ref + json_write(meta_path, metadata) + if depth is not None: + dpath, dloc = depth + dmeta = probe(dpath) + if [dmeta['width'], dmeta['height']] != view.meta['camera']['image_size']: + raise ValueError('HOI4D depth grid differs from RGB') + if dmeta['pix_fmt'] != 'gray16le': + raise ValueError('unexpected HOI4D depth pixel format') + width, height = view.meta['camera']['image_size'] + raw = work / 'depth.raw' + limits = ['-frames:v', str(n)] if args.max_frames else [] + run(decode_args(dpath, 'gray16le') + limits + ['-y', str(raw)]) + if raw.stat().st_size != n * width * height * 2: + raise ValueError('depth/RGB frame count or grid mismatch') + def depths(): + with raw.open('rb') as inp: + for _ in range(n): + yield np.frombuffer(inp.read(width * height * 2), ' best_iou + 0.1 and i > 0.15: +# best, best_iou = s[0], i +# if best != gk: +# gk, iou_fixups = best, iou_fixups + 1 diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/convert_visor_v1.0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/convert_visor_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..8f0595bf5e89ae00c959472ff197dfda2d7a6ea6 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/convert_visor_v1.0.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +"""VISOR source polygons and contact → CONTRACT.md v1.0, without rasterization or side inference.""" +from collections import Counter +import hashlib +import json +import re +import shutil +import tempfile +from pathlib import Path +import zipfile + +import numpy as np +import torch + +from warehouse_v1_0 import (View, build_record, find_file, jsonl_write, locator, parser, + release, roots, sequence_dir, source) + +FRAME = re.compile(r'frame_(\d+)') +HAND = {300: 'left', 301: 'right'} +GLOVE = {303: 'left', 304: 'right'} +STATES = {'hand-not-in-contact': 'negative', 'glove-not-in-contact': 'negative', + 'none-of-the-above': 'target_unannotated', 'inconclusive': 'unknown'} + + +def hand_side(ann): + if ann['class_id'] in HAND: + return HAND[ann['class_id']] + if ann['class_id'] not in (60, 303, 304): + return None + raw = ann.get('on_which_hand') + raw = raw if isinstance(raw, list) else [raw] + sides = set() + for item in raw: + if item == 'left hand': + sides.add('left') + if item in ('right hand', 'rigth hand'): + sides.add('right') + if len(sides) == 1: + return next(iter(sides)) + if not sides and ann['class_id'] in GLOVE: + return GLOVE[ann['class_id']] + return None + + +def convert_video(video, split, annotation, ann_loc, rgb_zip, rgb_loc, mapping, args, target): + indexed = sorted(enumerate(annotation['video_annotations']), key=lambda row: int(FRAME.search(row[1]['image']['name'])[1])) + if args.max_frames: + indexed = indexed[:args.max_frames] + if len({row['image']['name'] for _, row in indexed}) != len(indexed): + raise ValueError('duplicate VISOR frame') + keys = lambda row, ann: (row['image']['subsequence'], ann['class_id'], ann['name']) + collisions = set() + for _, row in indexed: + collisions.update(key for key, number in Counter(keys(row, a) for a in row['annotations']).items() if number > 1) + frames, paths = [], [] + with tempfile.TemporaryDirectory(prefix='visor-rgb-') as wd, zipfile.ZipFile(rgb_zip) as z: + work = Path(wd) + for original_index, row in indexed: + name = row['image']['name'] + data = z.read(name) + path = work / Path(name).name + path.write_bytes(data) + paths.append(path) + loc = rgb_loc | {'nested_member': name, 'sha256': hashlib.sha256(data).hexdigest()} + frames.append(dict(source_frame_id=int(FRAME.search(name)[1]), source_locator=loc, + source_image=row['image'], original_frame_name=mapping.get(name), + annotation_matches={'segment': dict(source_frame_id=name, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None, + source_locator=ann_loc | {'record': f'video_annotations[{original_index}]'})})) + view = View(target, 'EPIC-KITCHENS-VISOR', args.release_id, video, 'ego', frames, sampling='sparse', split=split) + view.valid_rules = { + 'segment': 'Selected sparse annotation frame present; all source polygons finite with at least three vertices and entity mapping valid', + 'relations': 'At least one source in_contact_object value present; positive targets resolve in the same frame; unknown is an explicit usable status', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta.update(view_type='ego', split_scheme='VISOR_GroundTruth_SparseAnnotations', split_source_locator=ann_loc) + view.meta['sampling']['selection'] = {'representation': 'official sparse annotations', 'max_frames': args.max_frames} + view.rgb(paths, rgb_loc) + entities = {} + polygons, mappings, relations, relation_valid = [], [], [], [] + for f, (original_index, row) in enumerate(indexed): + frame_loc = ann_loc | {'record': f'video_annotations[{original_index}]'} + id_map, labels, polys = {}, [], [] + for code, ann in enumerate(row['annotations'], 1): + if code >= 65535: + raise ValueError('too many source instances') + sid = ann['id'] + if sid in id_map: + raise ValueError('duplicate source instance ID within a frame') + side = hand_side(ann) + if side is not None: + entity = 'hand_' + side + else: + key = keys(row, ann) + identity = key + (sid, row['image']['name']) if key in collisions else key + entity = 'object_' + hashlib.sha256(json.dumps(identity).encode()).hexdigest()[:20] + if entity not in entities: + scope = 'frame' if key in collisions else 'subsequence' + scope_id = f'{video}:{row["image"]["name"]}' if scope == 'frame' else f'{video}:{key[0]}' + view.object(entity, frame_loc | {'source_instance_id': sid}, scope, scope_id, + category_id=ann['class_id'], name=ann['name'], + association_basis='source_frame_instance' if scope == 'frame' else 'official_subsequence_entity_name') + entities[entity] = True + id_map[sid] = entity + for polygon in ann.get('segments', []): + p = np.asarray(polygon) + if p.ndim != 2 or p.shape[1] != 2 or len(p) < 3 or not np.isfinite(p).all(): + raise ValueError(f'invalid source polygon {sid}') + polys.append(dict(mask_value=code, polygons=ann.get('segments', []))) + labels.append(dict(mask_value=code, category_id=ann['class_id'], entity_id=entity, + part_id=None, source_instance_id=sid, + source_attributes={k: v for k, v in ann.items() if k != 'segments'})) + rr = [] + provided = False + for ann in row['annotations']: + raw = ann.get('in_contact_object') + values = raw if isinstance(raw, list) else [raw] + for value in values: + if value is None: + continue + provided = True + status = STATES.get(value) + obj = None + if status is None: + if value not in id_map: + raise ValueError(f'unresolved source contact target {value} in {video} frame {f}') + status, obj = 'positive', id_map[value] + rr.append(dict(relation_type='contact', subject_id=id_map[ann['id']], object_id=obj, + status=status, source_value=value, source_locator=frame_loc | {'source_instance_id': ann['id']}, + provenance=source('Resolve source contact ID against instances in this frame'))) + polygons.append(dict(frame_index=f, instances=polys)) + mappings.append(dict(frame_index=f, labels=labels)) + relations.append(dict(frame_index=f, relations=rr)) + relation_valid.append(provided) + jsonl_write(view.path / 'annotation/segment/polygons.jsonl', polygons) + jsonl_write(view.path / 'annotation/segment/instances.jsonl', mappings) + torch.save(torch.ones(len(frames), dtype=torch.bool, device='cpu'), view.path / 'annotation/segment/mask_valid.pt') + view.component('segment', 'segment/instance_polygons/v1', 'annotation/segment/polygons.jsonl', ['T'], ann_loc, + valid_ref='annotation/segment/mask_valid.pt', valid_axes=['T'], segmentation_type='instance', + mapping_ref='annotation/segment/instances.jsonl', coverage={'kind': 'unknown', 'exhaustive_ref': 'annotation/segment/instances.jsonl'}) + view.relations(relations, relation_valid, ann_loc) + for component in ('depth', 'mano', 'keypoints_uv', 'keypoints_xyz', 'intrinsic', 'extrinsic'): + view.absent(component, 'Not provided by VISOR sparse source annotations') + return view.finish() + + +def main(argv=None): + p = parser('EPIC-KITCHENS-VISOR', __doc__) + p.add_argument('--videos', help='Comma-separated video names') + p.add_argument('--splits', default='train,val') + args = p.parse_args(argv) + wanted = set(args.videos.split(',')) if args.videos else None + splits = set(args.splits.split(',')) + if not splits <= {'train', 'val'}: + p.error('only annotated train/val splits are available') + out = release(args, 'EPIC-KITCHENS-VISOR') + archive = find_file(args.root, 'EPIC-KITCHENS VISOR.zip') + with tempfile.TemporaryDirectory(prefix='visor-source-') as wd: + work = Path(wd) + if archive: + with zipfile.ZipFile(archive) as z: + suffix = 'GroundTruth-SparseAnnotations/annotations/' + members = [n for n in z.namelist() if suffix in n and n.endswith('.json')] + prefix = members[0].split(suffix)[0] + fm = json.loads(z.read(prefix + 'frame_mapping.json')) + done = 0 + for member in sorted(members): + split, filename = member.split(suffix)[1].split('/') + video = Path(filename).stem + if split not in splits or wanted and video not in wanted: + continue + data = z.read(member) + rgb_member = prefix + f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' + rgb_zip = work / (video + '.zip') + with z.open(rgb_member) as inp, rgb_zip.open('wb') as dest: + shutil.copyfileobj(inp, dest) + with sequence_dir(out, video) as dest: + report = convert_video(video, split, json.loads(data), locator(archive, member, data), + rgb_zip, locator(archive, rgb_member), fm.get(video, {}), args, dest / 'ego') + build_record(out, video, {'ego': report}) + rgb_zip.unlink() + done += 1 + print(f'Converted {video}', flush=True) + if args.limit and done >= args.limit: + break + else: + root = next((r for r in roots(args.root) if (r / 'GroundTruth-SparseAnnotations').is_dir()), None) + if root is None: + p.error('VISOR outer ZIP or extracted source directory not found') + fm = json.loads((root / 'frame_mapping.json').read_text()) if (root / 'frame_mapping.json').exists() else {} + done = 0 + for split in sorted(splits): + for ann in sorted((root / 'GroundTruth-SparseAnnotations/annotations' / split).glob('*.json')): + video = ann.stem + if wanted and video not in wanted: + continue + rgb = root / f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' + with sequence_dir(out, video) as dest: + report = convert_video(video, split, json.loads(ann.read_text()), locator(ann), rgb, + locator(rgb), fm.get(video, {}), args, dest / 'ego') + build_record(out, video, {'ego': report}) + done += 1 + if args.limit and done >= args.limit: + return 0 + if not done: + p.error('no matching annotated videos found') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) + +# TODO(v2.0): 旧距离猜侧和单层掩码生成仅注释保留;v1.0 不执行。 +# if side is None and len(frame_hands) == 1: +# # 空间门槛:脱下放在远处的手套不并入(实测双峰 0..25px / ≥44px) +# hb = frame_hands[0][1] +# gb = _bbox_of(polys) +# if hb and gb and _bbox_dist(gb, hb) <= GLOVE60_MERGE_BBOX_DIST: +# side = frame_hands[0][0] +# stats["glove60_merged_into_sole_hand"] += 1 +# if side is None: +# stats["dropped_glove60_unresolved"] += 1 +# id_disp[mid] = ("dropped", "glove60") +# continue +# def rasterize_and_encode(vdir, frames, frame_draw, zip_path, n, stats): +# """流式读 zip 内 jpg + 光栅化多边形 → rgb.mkv / mask.mkv;返回 (w, h)。""" +# from PIL import Image, ImageDraw +# +# with zipfile.ZipFile(zip_path) as zf: +# member_of = {} +# for nm in zf.namelist(): +# member_of[os.path.basename(nm)] = nm +# names = [im["name"] for im in frames] +# missing = [nm for nm in names if nm not in member_of] +# if missing: +# raise RuntimeError(f"{len(missing)} annotated frames missing in zip, " +# f"e.g. {missing[:3]}") +# stats["zip_extra_members"] = len(member_of) - len(names) +# +# # 首帧定分辨率(官方 1920×1080,实测每帧校验) +# img0 = Image.open(io.BytesIO(zf.read(member_of[names[0]]))).convert("RGB") +# w, h = img0.size +# +# bin_img = Image.new("L", (w, h), 0) +# bin_draw = ImageDraw.Draw(bin_img) +# canvas = np.zeros((h, w), np.uint16) +# with VideoPipe(vdir / "mask.mkv", w, h, FPS, "mask") as mw, \ +# VideoPipe(vdir / "rgb.mkv", w, h, FPS, "rgb") as rw: +# for f in range(n): +# canvas[:] = 0 +# for pid, polys in frame_draw[f]: +# bin_draw.rectangle((0, 0, w, h), fill=0) +# for poly in polys: +# bin_draw.polygon([(float(x), float(y)) for x, y in poly], fill=255) +# arr = np.asarray(bin_img) +# canvas[arr > 0] = pid # 后画覆盖先画:物体→手(modal) +# mw.write(canvas) +# img = img0 if f == 0 else Image.open( +# io.BytesIO(zf.read(member_of[names[f]]))).convert("RGB") +# if img.size != (w, h): +# raise RuntimeError(f"frame {names[f]}: size {img.size} != {(w, h)}") +# rw.write(np.asarray(img)) +# n_mask, n_rgb = mw.n, rw.n +# if (n_rgb, n_mask) != (n, n): +# raise RuntimeError(f"wrote rgb={n_rgb} mask={n_mask} != {n}") +# got = (count_frames(vdir / "rgb.mkv"), count_frames(vdir / "mask.mkv")) +# if got != (n, n): +# raise RuntimeError(f"encoded rgb={got[0]} mask={got[1]} != {n} (decode verify)") +# return w, h +# +# diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/operations/h2o-benchmark-decode.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/operations/h2o-benchmark-decode.py new file mode 100644 index 0000000000000000000000000000000000000000..f647011c5e5b0ce0a155f1ba6438e2802672db0e --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/operations/h2o-benchmark-decode.py @@ -0,0 +1,74 @@ +"""Benchmark full FFV1 decodes, PNG RGB decodes, and source depth PNG loading; preserve every byte.""" +import hashlib +import json +import os +from pathlib import Path +import statistics +import subprocess +import time +from concurrent.futures import ThreadPoolExecutor +import numpy as np +from PIL import Image + +old = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10') +bench = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-decode-bench-20260930') +bench.mkdir(exist_ok=True) +media = next((old / 'H2O/shared-v1.0/data').glob('subject4_h1_0*/cam0/observation/rgb.mkv')).parent +inputs = bench / 'inputs' +inputs.mkdir(exist_ok=True) +for name in ('rgb.mkv', 'depth.mkv', 'depth_valid.mkv'): + dest = inputs / name + if not dest.exists(): + os.link(media / name, dest) +source = next((old / 'scratch').glob('h2o-source-*/subject4/h1/0/cam0/rgb')).parent +for kind in ('rgb', 'depth'): + dest = inputs / kind + dest.mkdir(exist_ok=True) + for frame in sorted((source / kind).glob('*.png'))[:100]: + if not (dest / frame.name).exists(): + os.link(frame, dest / frame.name) +records = [] +expected = {} +def record(stage, threads, digest, size, seconds): + assert expected.setdefault(stage, (digest, size)) == (digest, size), stage + row = dict(stage=stage, threads=threads, seconds=seconds, sha256=digest, bytes=size) + records.append(row) + print(json.dumps(row), flush=True) + (bench / 'report.json').write_text(json.dumps(records, indent=2) + '\n') +def decode(stage, arguments, threads, pix_fmt): + cmd = ['ffmpeg','-v','error','-nostdin','-filter_threads',str(threads),'-threads',str(threads), + '-noautorotate',*arguments,'-map','0:v:0','-vsync','0','-threads',str(threads), + '-f','rawvideo','-pix_fmt',pix_fmt,'pipe:1'] + digest = hashlib.sha256() + size = 0 + start = time.monotonic() + with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc: + while chunk := proc.stdout.read(1024*1024): + digest.update(chunk) + size += len(chunk) + stderr = proc.stderr.read() + assert proc.wait() == 0, stderr.decode() + record(stage, threads, digest.hexdigest(), size, time.monotonic()-start) +for threads in (1,10,10,1): + for name, pix in (('rgb','rgb24'),('depth','gray16le'),('depth_valid','gray')): + decode('ffv1_'+name, ['-i',str(inputs/(name+'.mkv'))], threads, pix) + decode('source_rgb_png_100', ['-framerate','30','-i',str(inputs/'rgb/%06d.png')], threads, 'rgb24') + files = sorted((inputs/'depth').glob('*.png')) + def read(path): + with Image.open(path) as im: + return np.asarray(im).astype(np.float32)/1000.0 + for depth_threads in (1,2,4): + digest = hashlib.sha256() + start = time.monotonic() + size = 0 + with ThreadPoolExecutor(max_workers=depth_threads) as pool: + # Bound decoded arrays to one small batch, as the production candidate would. + for begin in range(0,len(files),depth_threads): + for arr in pool.map(read,files[begin:begin+depth_threads]): + digest.update(arr.tobytes()) + size += arr.nbytes + record('source_depth_png_100', depth_threads, digest.hexdigest(), size, time.monotonic()-start) +print('MEDIANS',flush=True) +for stage in expected: + for threads in sorted({r['threads'] for r in records if r['stage']==stage}): + print(stage,threads,statistics.median(r['seconds'] for r in records if r['stage']==stage and r['threads']==threads),flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/operations/h2o-prepare-d10.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/operations/h2o-prepare-d10.py new file mode 100644 index 0000000000000000000000000000000000000000..69589418bb01420d8954893a9d19096062daf2c7 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/operations/h2o-prepare-d10.py @@ -0,0 +1,55 @@ +"""Reuse only atomically published sequences; preserve previous runtime provenance.""" +import datetime +import json +import os +from pathlib import Path +import shutil + +old = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10') +new = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10') +snapshot = Path('/tmp/h2o-w4-c10-d10-recovery') +new.mkdir() +shutil.copytree(snapshot, new / 'frozen-code') +release = new / 'H2O/shared-v1.0' +for directory in ('data', 'doc/validation', 'script/provenance/previous-run', 'script/provenance/operations'): + (release / directory).mkdir(parents=True, exist_ok=True) +history = release / 'script/provenance/previous-run' +shutil.copytree(old / 'H2O/shared-v1.0/script', history / 'script') +shutil.copytree(old / 'frozen-code/docs', history / 'docs') +for name in ('full.log', 'full.status', 'run-full.sh'): + shutil.copy2(old / name, history / name) +records = [] +for record in sorted((old / 'H2O/shared-v1.0/doc').glob('*.build.json')): + build = json.loads(record.read_text()) + seq = build['sequence_id'] + assert Path(seq).name == seq and seq not in ('.', '..') + assert set(build['views']) == {f'cam{i}' for i in range(5)}, seq + data = old / 'H2O/shared-v1.0/data' / seq + frames = {} + for cam in build['views']: + json.loads((data / cam / 'metainfo.json').read_text()) + frames[cam] = sum(1 for _ in (data / cam / 'camera/frames.jsonl').open()) + assert frames[cam] > 0 + shutil.copytree(data, release / 'data' / seq, copy_function=os.link) + shutil.copy2(record, release / 'doc' / record.name) + records.append({'sequence_id': seq, 'frames_by_camera': frames, + 'original_script_sha256': build['scripts']}) +manifest = {'time': datetime.datetime.now().astimezone().isoformat(), + 'source_run': str(old), 'destination_run': str(new), + 'configuration': {'workers': 4, 'codec_threads': 10, 'decode_threads': 10, + 'depth_threads': 4, 'cpu_limit': None}, + 'reuse': 'Hard-linked immutable completed views; source timeline/SHA256 still rechecked without staging published source frames', + 'excluded': 'Unpublished .tmp directories; historical 62-sequence output', + 'original_runtime_provenance': 'script/provenance/previous-run', 'sequences': records} +(release / 'doc/RESTART_PROVENANCE.json').write_text(json.dumps(manifest, indent=2) + '\n') +operations = release / 'script/provenance/operations' +for name in ('h2o-prepare-d10.py', 'h2o-switch-d10.sh', 'h2o-benchmark-decode.py'): + shutil.copy2(Path('/tmp') / name, operations / name) +for src, dest in (('/tmp/h2o-run-d10.sh', new / 'run-full.sh'), + ('/tmp/h2o-run-d10.sh', release / 'script/run-full.sh'), + ('/tmp/h2o-decode-bench.log', release / 'doc/validation/DECODE_THREAD_BENCHMARK.log'), + ('/data/xuzhefeng/Datasets/uni-hoi-h2o-decode-bench-20260930/report.json', release / 'doc/validation/DECODE_THREAD_BENCHMARK.json'), + ('/tmp/h2o-d10-final-tests.log', operations / 'worker4-encode10-decode10-depth4-regression.log'), + ('/tmp/h2o-io-sample.log', release / 'doc/validation/IO_SAMPLE.log')): + shutil.copy2(src, dest) +print(f'REUSED_SEQUENCES={len(records)} REUSED_VIEWS={sum(len(r["frames_by_camera"]) for r in records)}', flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/operations/h2o-switch-d10.sh b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/operations/h2o-switch-d10.sh new file mode 100644 index 0000000000000000000000000000000000000000..16de8391f6058e7c0d16ab02070a6f8da8d5bb55 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/operations/h2o-switch-d10.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +set -euo pipefail +cd /home/xuzhefeng/Projects/uni-hoi-dataset +test "$(cat /tmp/h2o-d10-final-tests.exit)" = 0 +test "$(cat /tmp/h2o-decode-bench.exit)" = 0 +test ! -e /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10 +old=/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10 +# Let the already nearly complete fifth camera publish, instead of discarding four completed cameras. +while test ! -s "$old/H2O/shared-v1.0/doc/subject4_h1_0.build.json"; do + test "$(systemctl --user show --no-pager h2o-full-w4c10-r2-20260930.scope -p ActiveState --value)" = active + sleep 20 +done +printf '\nRECONFIGURE=%s REASON=decoder10_depth4_no_resume_png_writes\n' "$(date -Is)" >> "$old/full.status" +systemctl --user stop h2o-full-w4c10-r2-20260930.scope +.venv/bin/python /tmp/h2o-prepare-d10.py +systemd-run --user --scope --unit=h2o-full-d10-20260930 -p CPUAccounting=yes /bin/bash /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10/run-full.sh diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/operations/worker4-encode10-decode10-depth4-regression.log b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/operations/worker4-encode10-decode10-depth4-regression.log new file mode 100644 index 0000000000000000000000000000000000000000..622982e748cfa8ca9981b3ce48c3e0b5c07c7acd --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/operations/worker4-encode10-decode10-depth4-regression.log @@ -0,0 +1,37 @@ +Converted subject1/h1/0 +Converted subject2/h1/0 +Converted subject3/h1/0 +Converted subject4/h1/0 +Converted subject2/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Archive subject4_v1_1.tar.gz: 1 sequences +Verified existing subject2/h1/0 +Verified existing subject1/h1/0 +Verified existing subject4/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Verified existing subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +PASS H2O four archive workers, codec/decode 1/4/10, ordered depth 1/2/4 and missing-depth preservation, no resume PNG writes, RGB FFV1-only, depth and persistent QC diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/operations/workspace-regression.log b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/operations/workspace-regression.log new file mode 100644 index 0000000000000000000000000000000000000000..964660aa6c3b8130c1bf9bb607cf9762f9ca59a2 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/operations/workspace-regression.log @@ -0,0 +1,37 @@ +Converted subject1/h1/0 +Converted subject2/h1/0 +Converted subject3/h1/0 +Converted subject4/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Converted subject2/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +Verified existing subject4/h1/0 +Verified existing subject3/h1/0 +Verified existing subject1/h1/0 +Verified existing subject2/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Archive subject3_v1_1.tar.gz: 1 sequences +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +PASS H2O four archive workers, codec/decode 1/4/10, ordered depth 1/2/4 and missing-depth preservation, no resume PNG writes, RGB FFV1-only, depth and persistent QC diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/docs/CONTRACT.md b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/docs/CONTRACT.md new file mode 100644 index 0000000000000000000000000000000000000000..f756d711647e109b6bb732ce1b9c84111730489d --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/docs/CONTRACT.md @@ -0,0 +1,457 @@ +# 手物数据仓库统一约定 v1.0 + +格式版本:`hand-warehouse/1.0`。存储约定:`lossless-video-2026-09-18`。 + +范围限于手物交互重建。按本任务纳入的源模态转换,不要求每个数据集填满所有组件。缺失模态、尚未下载、语义未核实分别报告,不能互相替代。 + +本文定义各字段的含义与使用规则,机器可读注册表见 [schema.json](schema.json)。两者互相补充;如有冲突,应先核实并统一定义。 + +## 1. 目录 + +```text +hand-datasets/ + / + raw/ + doc/ # 官方说明、来源与校验记录 + script/ # 官方下载脚本、必要包装脚本 + data/ # 保留原始包,不原地解压或改写 + / + doc/ # 发布说明、schema、来源清单 + script/ # 转换、校验脚本及运行配置 + data/ + / + / + metainfo.json + observation/ + rgb.mkv + rgb_valid.pt + depth.mkv # float32 深度的可逆视频编码 + depth_valid.mkv # 逐像素 bool 的无损视频编码 + camera/ + frames.jsonl + intrinsic.pt + intrinsic_valid.pt + extrinsic.pt + extrinsic_valid.pt + annotation/ + mano/ + motion.pt + motion_valid.pt + visibility.pt + keypoints/ + uv.pt + uv_valid.pt + xyz.pt + xyz_valid.pt + visibility.pt # 源数据有时提供 + object/ + / + assets/ # 该物体的网格、材质、纹理及部件资产 + .obj + pose.pt + pose_valid.pt + visibility.pt + metainfo.json # 物体身份、类别、mesh、尺寸与部件引用 + articulation.json + keypoints/ + vertex_part_ids.pt + joint_state.pt + joint_state_valid.pt + parts//pose.pt + parts//pose_valid.pt + segment/ + mask.mkv + mask_valid.pt + instances.jsonl + contact/ + relations.jsonl + __/ # 对应实体间的距离/接触区域 +``` + +目录展示可能存在的组件,不要求填满。具体文件、字段和缺省规则分别见后续对应小节。原始包的解压发生在临时工作区,raw 内原始包保持不变。 + +## 2. 相机视图的 metainfo.json + +### 2.1 顶层字段与发布信息 + +每个相机视图必须有 `metainfo.json`。以下字段除另行说明外均为必填: + +| 字段 | 填写内容 | +|---|---| +| schema_version | 结构版本,本版为 `hand-warehouse/1.0` | +| dataset_id | 数据集的逻辑标识 | +| release_id | 本次数据发布版本,对应目录中的 dataset_version | +| sequence_id | 所属序列或独立图片样本的标识 | +| camera_id | 当前相机视图标识 | +| sample_type | `image` 或 `video`,规则见 2.2 | +| num_frames | 当前视图帧数 T,所有随帧组件按同一时间轴组织 | +| hand_slots | 固定为 `["left", "right"]`;解剖学左右的使用规则见 5.1 | +| sampling | 采样类型、源 FPS、帧索引引用及选择策略,见 2.2 | +| camera | 当前相机模型与图像尺寸,见 2.3 | +| components | 实际提供的组件及其文件、schema、有效性和来源,见 2.5 | +| split | `train/val/test/unknown`,划分协议见 2.4 | +| view_type | 可选,`ego/exo/unknown` | + +`dataset_version` 是数据发布版本;`schema_version` 是结构版本,两者独立。原始包校验摘要、官方来源和转换配置应记录在发布清单中。解压发生在临时工作区,原始包保持不变。 + +### 2.2 图片、视频与 sampling + +`sample_type=image`:允许单图 T=1、`sampling.type=single`,也允许将独立图片批量装入一个视频容器,T>1 时 `sampling.type=independent`、`source_fps=null`。分片大小按数据集选择;FreiHAND 默认每片最多 4096 张,训练与评估分开,尾片不补帧。该数量不是其他数据集的强制要求;同批分辨率、相机模型类型及划分协议一致。每行 frames 必须有稳定且唯一的 `sample_id`、原始文件定位;内参、手形状等仍逐帧保留,不能因打包而共享错误的标定或身份。`sequence_id` 在这里仅是批次标识,不代表真实序列;不得按相邻帧推断跟踪、同步或接触延续。源 camera_id、image_variant、split 等随样本变化时放在 frames 的对应字段中。真实采集时间未知则 timestamp_ns=null。合成背景变体不视为真实多相机。 + +`sample_type=video`:`sampling.type=dense/sparse`;`source_fps` 是真实采集 FPS,未知为 null。非连续取样必须保留源帧号和已知源时间,不可用采样后索引除以 FPS 冒充源时间。可另记采样策略与步长。 + +shared 可以仅存所选 RGB 帧对应的数据。OakInk2 图像/动捕不同采样率时用 annotation_matches 明确映射;不要求将未采样动捕点硬塞进 T。多视角身份和源同步关系要保留;选择了哪些帧/相机及原因写在 sampling 中。 + +`sampling.frames_ref` 指向 `camera/frames.jsonl`。帧号、逐帧时间、同步与标注匹配记录的结构见 4.1;MKV 封装时间的约定见 3.1。 + +### 2.3 camera 模型声明 + +`camera` 至少包含 `model`、`schema_id`、`image_size:[W,H]`。模型未知使用 `unknown` 和 `null`,不猜成针孔。实际内参、畸变及外参数组放在 `camera/`,各模型的固定结构见第 4 节。 + +### 2.4 split 与划分协议 + +保留上游划分,不将同一采集序列的相邻帧随意拆到不同集合。 + +有官方划分时必填 split_scheme 和 split_source_locator,split_scheme 区分如 Dex-YCB s0/s1、ARCTIC P1/P2 等选定协议;不知道时 split=unknown 并给理由,不凭空分配。每发布可选择一种协议;存在逐帧差异时 frames 中的 split 覆盖视图默认值,并登记其来源。 + +### 2.5 components 组件登记 + +组件表的键是本发布内唯一名称,例如 `rgb`、`depth`、`mano`、`keypoints_uv`。每个已提供组件声明以下信息;模态特有参数在第 3–5 节对应小节中定义。 + +| 字段 | 约定 | +|---|---| +| available | 本发布是否提供该组件;缺省也表示未提供 | +| schema_id | 已登记的具体存储与语义类型,不得临时创造未登记名称 | +| data_ref | 数据文件路径,相对当前相机视图根目录,使用 POSIX 路径 | +| axes | 数组各维度的含义 | +| valid_ref / valid_axes | 有效性文件及其维度;语义由所属组件规定 | +| storage / valid_storage | 视频数据/视频有效性的存储配置;包含已登记 profile、实际 codec、pixel_format、encoded_size,见 3.1;非视频组件按原数组规则 | +| provenance | source / format_conversion / derived,以及转换或生成方法 | +| source_locator | 原文件、压缩包成员和记录/帧的定位信息 | + +不存在的组件允许缺省或写作 `{ "available": false, "reason": "..." }`,不用引用不存在的文件。静态网格可声明标量有效性;具体见 5.4。观测的 valid 见第 3 节,标注的 valid 与 visibility 区分见 5.1。 + +`provenance.kind` 使用 source/format_conversion/derived,`method` 说明转换或生成方法;发布清单补充脚本版本、参数、输入摘要。`source_locator` 定位到原始文件/压缩包成员和记录、帧号;允许引用有完整溯源清单的前一发布,但链条最终应能回到 raw。不得仅写一个无法定位记录的数据集名字。 + +`.pt` 仅保存 CPU Tensor,不保存 Python 自定义对象;浮点默认 float32,有效性为 bool,浮点无效位置填 NaN。所有随帧数组保留首维 T,单帧也不 squeeze;静态资产按其 schema 单独声明。单位、坐标及固定形状见各组件小节。 + +机器注册表 `schema.json` 中,`components` 固定解码后的数据类型、形状、单位和语义;`storage_profiles` 固定视频内的编码/还原方式。不得临时创造未登记的 schema_id 或 storage.profile。同一语义允许选择其登记的不同无损存储 profile。 + +## 3. observation 观测数据 + +### 3.1 rgb.mkv 与 rgb_valid.pt + +RGB、深度和栅格 mask 在 shared 中统一使用 MKV 视频容器,不展开为逐帧图片或图像 tar。MANO、关键点、位姿等数值标注仍用数组;分割的重叠多边形仍用 JSONL,不为了视频化而有损栅格化。单图可为一帧视频,独立图批量封装规则见 2.2。 + +**无损指共享层不增加信息损失。** 源 JPEG/H.264 等本身可能已是有损编码,原样保留并不恢复已丢失信息;不得重新以有损 JPEG、H.264、H.265、AV1 参数编码。源视频/图片的色彩、位深、分辨率和几何关系不得被静默改变。RGB schema `rgb/uint8/v1` 的统一读取结果是 `[T,H,W,3] uint8`、RGB 通道,有效性仍为 `rgb_valid.pt [T] bool`。超出该 schema 的高位深或 HDR 源必须报告并扩展定义,不能降到 8 位冒充无损。 + +#### 3.1.1 允许的 RGB 存储 profile + +| storage.profile | 编码方式 | 适用规则 | +|---|---|---| +| mkv/mjpeg_copy/v1 | 源 JPEG 压缩帧直接封装成 MJPEG/MKV | 不解码重编码;保持每张 JPEG 码流字节;普通 8 位 JPEG 且 MKV/解码器支持时使用 | +| mkv/source_copy/v1 | 已有视频的 RGB 对应码流直接封装为 MKV | 仅源编码能被 MKV 和选定解码器支持时使用,不伪造帧;需维持正确的呈现顺序与依赖帧 | +| mkv/h264_rgb_lossless/v1 | libx264rgb 的真正无损模式 | 必须 RGB 路径、CRF=0,并通过全帧 RGB 字节比较;不能替换成默认 libx264 YUV420 路径 | +| mkv/ffv1_rgb/v1 | FFV1 的 RGB 可逆编码路径 | 作为通用候选;解码回 RGB 后必须逐字节相同,不做色度降采样 | + +优先尝试源码流直接封装;不能封装或需要选择稀疏帧时,比较 FFV1 与无损 RGB H.264。对完整待发布片段,只在通过无损验收的候选中选择文件较小者,不假设某个编码器总最小;编码时间和随机读取代价记入构建记录。中间候选不作为 shared 多份常驻。H.264 跨帧压缩允许较长 GOP,必须记录 GOP/关键帧间隔,随机取帧需从前一关键帧正确解码,不能把 seek 返回的近似帧当目标帧。 + +普通源视频可以保留它已有的有损码流,但不允许新增有损重编码。源是 VRS 等记录容器时,先查明图像流实际编码:已有兼容 JPEG/视频包可直接提取封装,否则解码后使用真正无损编码;不把整个 VRS 改后缀当 MKV。PNG 不要求直接塞进 MKV,可选上表两种无损重编码方式。 + +#### 3.1.2 视频配置与校验 + +每个视频组件在 metainfo 中登记 `storage`,至少包含: + +| 字段 | 内容 | +|---|---| +| profile | 上述登记的存储 profile;语义仍由组件 schema_id 指定 | +| codec | 文件中实际 codec,例如 mjpeg、h264、ffv1;source_copy 必须写实际 codec | +| pixel_format | 实际编码像素格式;不得仅凭编码器参数猜测 | +| encoded_size | 视频物理像素尺寸 `[width,height]`;深度可能不同于逻辑尺寸,见 3.2 | +| decoder | 解码器名称、版本,以及颜色矩阵/范围/旋转处理等实际像素解释配置;未知的源色彩声明 unknown,不擅自称为 sRGB | +| encoder_parameters | 重编码时的编码器、版本、无损模式和 GOP 等参数;直接封装时记录 stream_copy | +| source_lossy | 源是否已有损:true / false / unknown;不是共享层再有损编码的许可 | + +无损重新编码的 RGB 必须使用同一固定解码配置,比较**全部帧**的统一 RGB 字节、数量及顺序。MJPEG-copy 不重新编码,生产校验采用 `jpeg-packets-all-rgb-sample16/v1`:从 MKV 逐包取回,对全部源 JPEG 的 SHA256、数量、顺序和图像尺寸进行精确核对;每视图另用同一固定解码配置比较最多 16 帧的源与目标 RGB 字节(含首尾与四分位位置,其余由固定种子抽取)。记录策略、实际索引、种子与结果;不足 16 帧时全查。试点与最终完整序列随机抽查,对选中视图的全部帧复核解码 RGB。历史已做全帧像素检查的证明继续保留。 + +逐包一致与像素抽查的范围必须分别声明,不能将抽查写成全量像素检查。不能用 PSNR 高、视觉相似、编码器参数称为 lossless 等替代精确检查。同时保留源编码的色彩标记和必要元数据;原图有 EXIF/色彩/方向等元数据时保留 raw 和必要来源信息;不能静默自动旋转图像而不更新像素对应与标定。以上加速策略仅适用于原 JPEG 码流直接封装,不适用于深度、标签或重新编码的 RGB。 + +所有共享视频的呈现帧顺序与统一 frame_index 一一对应,每个栅格组件恰好 T 帧。MKV 的 `storage_fps` 只服务封装,声明 `timebase_role=index_only`;source_copy 可以保留源 PTS 以避免改坏码流,但真实时间与标注对齐仍以 frames 为准。未知真实时间保留 null。缺失某帧组件时保留索引位置并使用该组件的无效占位/valid 标识,不删帧;不能以重复相邻图像冒充已知观测。 + +### 3.2 depth.mkv 与 depth_valid.mkv + +深度语义仍是 `depth/z_float32/v1`:统一读取结果 `[T,H,W] float32`,米制相机 Z 分量,`depth_type=z`。有效深度有限且大于 0,无效位置为 NaN。`depth_origin=measured/rendered/unknown` 必填,来源不明时 unknown。默认与 RGB 共用像素网格及相机参考系,不处理未注册 RGB-D。射线距离必须依据源定义转换成 z,不能只改声明。 + +#### 3.2.1 float32 的可逆视频编码 + +采用 `mkv/depth_float32_bits/v1`:**不是把深度量化成 uint16**,而是将规范化后每个 IEEE-754 float32 的完整 32 位拆成两个 uint16,使用 FFV1 gray16le 保存。视频物理尺寸为 `[2W,H]`:每行前 W 列存原 float32 位串的低 16 位,后 W 列存高 16 位。读取时先合并为 uint32 位串,再按 float32 重新解释,不能数值 cast 成 float32。 + +```text +u = reinterpret_uint32(depth_float32) +encoded[:, :, :W] = uint16(u & 65535) +encoded[:, :, W:] = uint16(u >> 16) +u_restored = uint32(low) | (uint32(high) << 16) +depth_float32 = reinterpret_float32(u_restored) +``` + +统一采用 little-endian 原始字节接口。`camera.image_size` 始终是逻辑 RGB 尺寸 `[W,H]`,不能改成编码视频的 2W;`storage.encoded_size=[2W,H]`。包括 NaN 在内的 float32 位串必须全帧完全恢复,不允许改成 float16、整数毫米、归一化灰度或 RGB 伪彩色。这里的无损验收基准是完成既定米制/坐标转换后的标准 float32 数组,不声称消除 float64→float32 等原约定转换本身的舍入。 + +#### 3.2.2 逐像素有效性 + +`depth_valid.mkv` 使用 `mkv/bool_ffv1/v1`,FFV1 gray8(FFmpeg pixel_format=`gray`),物理尺寸 `[W,H]`。像素只能为 0 或 1,统一解码为 `[T,H,W] bool`,逐像素含义不变。这样不再把庞大的 bool 数组保存为未压缩 `.pt`;标注的帧级/手级 valid 仍保留原有小数组。 + +登记示例(W、H 以下取 640、480;decoder/encoder_parameters 的实际版本由转换器填写): + +```json +{ + "available": true, + "schema_id": "depth/z_float32/v1", + "data_ref": "observation/depth.mkv", + "axes": ["T", "height", "width"], + "valid_ref": "observation/depth_valid.mkv", + "valid_axes": ["T", "height", "width"], + "unit": "m", + "depth_type": "z", + "depth_origin": "measured", + "invalid_value": "NaN", + "storage": { + "profile": "mkv/depth_float32_bits/v1", + "codec": "ffv1", + "pixel_format": "gray16le", + "encoded_size": [1280, 480], + "source_lossy": false, + "decoder": {"name": "ffmpeg", "version": "填写实际版本"}, + "encoder_parameters": {"name": "ffv1", "level": 3, "version": "填写实际版本"} + }, + "valid_storage": { + "profile": "mkv/bool_ffv1/v1", + "codec": "ffv1", + "pixel_format": "gray", + "encoded_size": [640, 480], + "source_lossy": false, + "decoder": {"name": "ffmpeg", "version": "填写实际版本"}, + "encoder_parameters": {"name": "ffv1", "version": "填写实际版本"} + }, + "provenance": {"kind": "format_conversion", "method": "源深度转米制 z float32;逐位打包为 FFV1"}, + "source_locator": {"file": "raw/data/depth.zip", "member": "depth/0001.png"} +} +``` + +深度和有效性视频都必须逐帧解码验收:float32 位串相同、bool 相同、T 相同,并检查 valid=true 的正有限值和 valid=false 的 NaN。读取器必须按 profile 还原,不能把 depth.mkv 的编码像素直接当深度值。 + +## 4. camera 相机、帧索引与标定 + +### 4.1 frames.jsonl:索引、时间与对应关系 + +`camera/frames.jsonl` 每行对应统一帧号 `frame_index=0..T-1`,是所有组件的唯一行索引。至少包含 `frame_index`、`timestamp_ns`、`clock_domain`、`source_locator`;原始帧号/文件名保存在 `source_frame_id`,不能被新帧号替代。每行还可有 `annotation_matches`,按组件键保存 `source_frame_id`、`source_timestamp_ns`、`clock_domain`、`match_method` 和 `delta_ns`;方法为 exact/index_map/nearest/interpolated,索引映射无时间依据时 delta_ns=null。nearest 必须记录允许误差;interpolated 必须记录两端源标识和权重。delta_ns 仅在同一时间域中计算为源标注时间减图像时间。多相机共享 `sequence_id`;已知同步关系必须用 `sync_id` 或明确的源帧/时间映射表达,不能仅凭相同数组索引认定同步。 + +每个视图必须提供此文件。源时间使用整数纳秒及 `clock_domain`,未知写 JSON `null`;不同时间域不能直接比较。逐帧 split 可以覆盖 metainfo 的视图默认划分,并保留来源,见 2.4。 + +### 4.2 坐标系与标定通则 + +| 项目 | 统一约定 | +|---|---| +| 相机坐标 | 右手系,X 向右、Y 向下、Z 向前,长度单位米 | +| 齐次变换 | 列向量,`p_target = T_target_from_source @ p_source` | +| 图像坐标 | `(u,v)`;左上像素中心为 `(0,0)`,u 向右、v 向下,单位 pixel | +| 固定标定 | 本版展开为 T 份,同一 schema 不混用静态与动态形状 | +| 分辨率或模型变化 | 分开存储为视图/片段,不在同一组件中混装 | +| 未知标定 | 相机内外参允许缺省,不填单位阵冒充已知标定 | + +### 4.3 intrinsic.pt 与畸变参数 + +| model / schema_id | intrinsic.pt 的固定结构 | +|---|---| +| pinhole / camera/pinhole/v1 | `[T,3,3]`,标准 K,最后一行为 `[0,0,1]`;限无畸变或已校正图像 | +| fisheye624 / camera/fisheye624/v1 | `[T,15]`,`[f,cx,cy,k0,k1,k2,k3,k4,k5,p0,p1,s0,s1,s2,s3]`,采用 Project Aria Fisheye624 投影定义 | +| opencv_fisheye4 / camera/opencv_fisheye4/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件 `distortion_ref` 指向 `[T,4]`,顺序 `[k1,k2,k3,k4]`,使用 OpenCV fisheye 等距角度多项式;已由 ReInterHand 实际原始相机参数验证 | +| rational8 / camera/rational8/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件必需 `distortion_ref` 指向 `[T,8]`,顺序 `[k1,k2,p1,p2,k3,k4,k5,k6]` | +| unknown / null | 不提供可用 intrinsic,不声称可以投影 | + +有畸变的其他模型必须注册新 schema,固定参数名、顺序和投影公式;不能塞进针孔 K 后遗失畸变项。`metainfo.camera.schema_id` 必须与 intrinsic 组件一致。同一模型的别名不可隐式改变参数布局。 + +`opencv_fisheye4`:对前方点令 `x=X/Z, y=Y/Z, r=sqrt(x²+y²), theta=atan(r)`,`theta_d=theta*(1+k1*theta²+k2*theta⁴+k3*theta⁶+k4*theta⁸)`;`u=fx*x*theta_d/r+cx, v=fy*y*theta_d/r+cy`。光轴 r=0 时使用连续极限 `theta_d/r=1`。四系数不能按普通径向畸变解释,也不能补零冒充 Fisheye624。 + +rational8 对归一化坐标 x=X/Z、y=Y/Z,令 r²=x²+y²,径向项为 `(1+k1*r²+k2*r⁴+k3*r⁶)/(1+k4*r²+k5*r⁴+k6*r⁶)`;再加 p1/p2 切向项并经 K 得到像素。`distortion_ref` 与 intrinsic 共用 `[T]` valid,保存到 camera/distortion.pt。不得把这种畸变三维坐标当作真实相机系 xyz 保存。 + +内参有效性为 `intrinsic_valid.pt [T] bool`;有畸变时使用对应 `distortion_ref`。同一模型的参数名和顺序固定。 + +### 4.4 extrinsic.pt 与 extrinsic_valid.pt + +`extrinsic.pt` 为 `[T,4,4]`,schema `transform/se3/v1`,方向固定 `T_camera_from_world`,有效性 `[T]`。世界坐标含义及源坐标转换记录在 provenance 中;只有相机坐标标注不要求虚构世界坐标。旋转块须正交且 determinant≈1。 + +## 5. annotation 标注数据 + +### 5.1 标注通则:手槽、valid 与 visibility + +手槽固定为 0=left、1=right,指解剖学左右,不按画面位置或可见性重排。本阶段只处理左右手两槽,不处理更多手。实体引用使用 `hand_left`、`hand_right`;手槽不证明跨采集片段的个人身份。 + +#### 5.1.1 valid:标注是否可用于监督 + +标注的 `valid=true` 表示:有对应实际标注、通过本 schema 数值检查,且通过来源明确提供并适用于该组件的有效性/QA 条件。`valid=false` 可由缺标注、无法建立帧对应、源无效占位或官方 QA 不通过导致;不等于画面没有手或手不可见。各组件独立判断,MANO 按 `[T,2]` 标记左右手,关键点按 `[T,2,K]` 标记。 + +**2026-09-20 将标注 valid 从“仅表示存在”修订为“可用于监督”,字段形状不变。** 公式为 `source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass`。没有官方 QA 时省略最后一项,不伪造 QA;不能把未知当成已通过已存在的 QA。适配器在组件 `valid_policy` 中记录具体规则、来源、聚合/广播作用域。缺失官方必需 QA 的记录须明确处理为未知或暂停验收,不能静默通过。无效浮点项仍填 NaN,原始数据保留在 raw;被排除原值可用于 doc 中明确标识的诊断渲染,不能冒充 shared 有效监督。 + +本地筛选须依据明确的规则,并在 `valid_policy.local_excluded_frame_indices`、排除原因和正式报告中记录。单个可疑投影作为问题记录,不直接硬编码排除该帧。已确认的曝光异常须明确作用范围,不能把一个序列的“前两帧有问题”套到所有序列。RGB 编码完好与几何监督可用是两件事,允许保留原图及帧索引而屏蔽对应标注;未发现问题不等于完成全部人工审核,试点待确认时不能作为已验收发布使用。 + +源字段必须按官方语义映射,不能直接按名字复制: + +| 来源 | 官方含义 | 映射原则 | +|---|---|---| +| [H2O](https://github.com/taeinkwon/h2odataset) 的手标注首位 | 0 未标注、1 已标注 | 可作为对应手标注存在性的依据,不推断未标注原因 | +| [HOT3D](https://github.com/facebookresearch/hot3d#using-mask-files) 的 pose_available、visible、mask_qa_pass | 分别表达姿态存在、可见性、对画面中可见手物位姿的人工 QA | 逐手/物体记录决定存在性,再 AND 当前相机当前帧 QA;QA 是整帧聚合判定,保守排除该帧全部手物几何监督,不声称每个实体均有错误;源可见性基于位姿推导时,其自身 valid 同样受 QA 约束 | +| [Dex-YCB](https://github.com/NVlabs/dex-ycb-toolkit#loading-dataset-and-visualizing-samples) 的全零 pose_m、全 -1 joints | 不可见的手或缺标注共用占位表示 | 对应组件 valid=false;不能从该值判定 visibility=false,也不能声称原因是动捕缺失 | +| [ARCTIC](https://github.com/zc-alexfan/arctic/blob/master/docs/data/data_doc.md) 的 is_valid/left_valid/right_valid | 是否有效用于官方评估 | 核实每项筛选依据;不把可见性/评估选择直接等同 QA。本次原始 mano.npy 不含这些派生评估标记,按原记录与数值检查生成 valid,并声明没有额外官方 QA 输入 | + +源 valid=false 若代表评估筛选或其他条件,应检查实际标注和源约定后映射;不能一律清空坐标。反之,占位零或 -1 只有在源官方明确规定时才判为缺失,不泛化成所有数据的判断规则。 + +`valid=true` 的标注应通过其 schema 的数值与形状检查;检查失败必须报告或修复,不能静默隐藏。QA 不通过应报告排除数量与原因,并保留可追溯信息;不能把这类无效称为缺标注。RGB、深度等观测有效性仍按各自 schema;手物 QA 不自动否定 RGB、静态相机内参或物体资产。相机外参是否过滤须依据其自身来源规则;HOT3D 本次保留源外参用于溯源和诊断,不能用其存在性证明 QA 失败帧的几何监督正确。 + +#### 5.1.2 visibility:可见性属性 + +附加质量属性只保留 `visibility`,存放在对应模态或标注集内,不设 quality 目录。同一份可见性仅存一次;uv 与 xyz 共用时引用同一个文件。 + +visibility 通过所属组件 attributes 登记 data_ref、axes、dtype、visibility_type、meaning、provenance、source_locator;未知值通过属性 valid_ref 标识,全已知可声明 valid=true。比例与布尔值不相互强转,也不按任意阈值二值化。没有 MANO 时,整手可见性挂在 keypoints 组件,使用独立的 whole_hand_visibility.pt,明确 meaning=whole_hand,不与逐关键点可见性混用。 + +`valid` 回答“这项标注能否用于监督”,`visibility` 回答“在当前图像中是否可见(或可见多少)”。不可见的手或关键点仍可有有效标注;不能因 visibility=0 就清空坐标。源没有 visibility 时缺省或标为未知,不由 valid 推断。 + +| 情况 | 手标注 valid | visibility | +|---|---|---| +| RGB 已开始录制,动捕尚未开始,没有其他对应手标注 | false | 以独立源可见性标注为准;没有则未知 | +| 手被遮挡,但源有标注且通过适用有效性检查 | true | 若源声明不可见,则 false 或源可见比例 | +| 手可见且有对应标注,通过适用 QA | true | 若源有此信息,则 true 或源可见比例 | +| 手可见,但该帧漏标或动捕中断 | false | 可以为 true,但必须有独立来源依据 | +| 有手部参数,但官方 QA 明确不通过 | false | 不据此断言不可见;源可见比例若基于不可靠位姿,其属性 valid 也为 false | + +visibility 自己的 valid_ref 表示该可见性标注是否可用,不复用 MANO 或关键点坐标的 valid_ref;明确记录源存在性及适用的 QA 条件。上述例子不要求凭图像自动生成可见性。 + +不设 quality 组件或目录,不另存拟合误差、曝光、截断比例等通用质量数组。适用的官方 QA 合并进对应 valid,在 `valid_policy` 记录来源与规则;正式校验报告保留原始 QA 时间区间及排除统计。原始 QA 文件仍在 raw,官方 split 保留。 + +### 5.2 mano:参数与整手可见性 + +MANO schema `mano/axis_angle61/v1`:`motion.pt [T,2,61]`,顺序为完整 16 关节 axis-angle 48、shape betas 10、全局平移 3。姿态使用弧度,平移米,位于当前相机系。有效性 `[T,2]`;缺少一侧整槽 NaN。PCA 必须先按对应模型展开,不能将 PCA 系数直接填入 axis-angle。 + +`model_profile` 必须固定 MANO 版本、`flat_hand_mean=true`、左手 shapedirs 修正状态。平移表示模型输出顶点所加的全局平移,不是某个腕关节的坐标;源语义不同须转换。shape 无量纲。模型权重不作为共享数据附带上传。 + +`mano/visibility.pt [T,2]` 保存源整手可见比例时使用 float32 [0,1],`visibility_type=ratio`;只有实际采用 0–100 的百分比才除以100,不能只凭表头判断。HOT3D 的 `visibility_ratio[%]` 实值已经是0–1,官方读取器原样读取,必须保留原值。通过 MANO 组件 attributes 登记,使用独立有效性,不复用 motion_valid。 + +手部共享表示仅保留 MANO 参数与选定关键点,不发布独立手表面几何。需要渲染或接触计算时由 MANO 参数生成,几何引用使用固定 MANO 模型配置与顶点顺序;不影响 object 下的物体模型和材质资产。 + +### 5.3 keypoints:二维点、三维点与逐点可见性 + +关键点独立于 MANO 参数存在;没有 motion 也可有关键点。`uv.pt [T,2,K,2]` 与 `xyz.pt [T,2,K,3]`,有效性 `[T,2,K]`,分别采用 `keypoints/uv/v1` 和 `keypoints/xyz/v1`。K 由 `keypoint_schema` 固定,不能在同一数组中逐帧变化;同体系统一顺序。数值使用像素坐标或米制相机系。 + +| keypoint_schema | K 与固定索引 | +|---|---| +| mano21/v1 | 21;wrist 后依次 thumb/index/middle/ring/little,每指由近端至指尖 | +| rhd21/v1 | 21;保持 wrist,然后五指由近端至指尖;原始每指 tip→palm 反序。只统一顺序,不宣称解剖学位置等价于 MANO | + +具体名称与源索引映射见 `schema.json`。当前只登记 MANO21 与 RHD21;不登记 MediaPipe、ReInterHand capture21 或 fit24 中间关键点。 + +每个发布中的每个视图只提供一套标准手关键点,直接放在 keypoints 下,不设 annotation_set_id 字段或目录。uv 与 xyz 是这套关键点的二维与三维表示,不是两套标注。provenance 分别记录二者来自原始标注还是计算结果;不要求已有 2D 必须由当前 xyz 重新投影覆盖。 + +ReInterHand 的 Original keypoints、Original fits keypoints 及带前臂关键点不纳入 shared;如需手关键点,从选定 MANO 参数生成 MANO21 并记录模型/指尖回归约定。其他数据集默认使用选定的官方关键点,不额外生成平行的 MANO 派生集合。后续主动更换生成方法或结果时发布新的 dataset_version,不在同一版本内增设方法分支。 + +manual/projection/fitting 只记录在 provenance,不作为目录或类型分支。不得通过坐标为零、是否出画或 visibility 判断标注是否存在。派生标注仅在实际生成并通过数值检查后声明 valid=true;没有生成的项为 false,不伪造坐标。 + +`keypoints/visibility.pt [T,2,K]` 保存源逐点可见性,布尔表示使用 `visibility_type=boolean`。uv 与 xyz 共用时引用同一份文件。整手比例属性没有 MANO 可挂载时使用 `whole_hand_visibility.pt [T,2]`,`meaning=whole_hand`;它与逐点可见性分开,通用登记规则见 5.1。 + +不使用 annotation_set_id;ReInterHand 中间关键点集合不进入 shared,raw 保留来源文件。 + +### 5.4 object:身份、资产、位姿与几何 + +#### 5.4.1 metainfo.json:物体身份与跟踪作用域 + +手用 `hand_left`、`hand_right` 及槽位 0、1 表示,不再另存 entities.json。物体身份登记在 `annotation/object//metainfo.json`,必填 `object_id`、`identity_scope`、`scope_id`、`source_locator`;可含 `category_id`、`source_object_id`、`mesh_ref`、`has_model`、部件引用。即使只有分割、没有 pose/mesh,也可只有这份物体元信息。 + +`identity_scope` 为 frame/subsequence/sequence,`scope_id` 指定具体作用域;跨相机共享身份只在已有源对应证据时使用。VISOR 按官方 subsequence 与实体名关联时记录 `association_basis=official_subsequence_entity_name`,不能声称这是全视频物理实例跟踪。无需与 object_id 一一对应的标准 track_id;官方独立轨迹标识存在时保留为 source_track_id,并声明作用域。手槽不证明跨采集片段的个人身份。 + +#### 5.4.2 assets:网格、材质与纹理 + +资产属于物体,统一存放在 `annotation/object//` 内,可用 `assets/` 子目录组织网格、材质、纹理和部件资产。序列层不设共享 assets。所有引用采用视图根目录为基准;其中物体资产组件的 `data_ref` 与部件的 `mesh_ref` 采用相对于当前视图目录的 POSIX 路径,例如 `annotation/object/cup_01/assets/cup.obj`,且必须指向所属物体目录内的资产。OBJ 内部的材质、纹理引用遵循文件格式自身的相对路径规则,依赖文件一并保留。不同相机视图允许各自保存物体资产,不要求跨视图去重;下载物体时包含其资产依赖。 + +网格 schema 为 `mesh/obj/v1`,顶点米制,静态有效性可直接声明标量 `valid`,或通过 `valid_ref` 指向标量 bool Tensor;不按 T 重复静态资产。由物体/部件通过引用关联,不仅凭文件名猜测。 + +#### 5.4.3 pose.pt、pose_valid.pt 与 visibility.pt + +刚体 schema 为 `object/rigid/v1`,`pose.pt [T,4,4]` 固定为 `T_camera_from_object`,平移米制,有效性 `[T]`。物体坐标原点、轴向必须与 mesh 一致;旋转块为正交矩阵且 determinant≈1。 + +`object//visibility.pt [T]` 保存源物体可见比例,float32 [0,1],`visibility_type=ratio`。通过所属物体组件 attributes 登记,独立表达其有效性。 + +#### 5.4.4 articulation.json、部件位姿与 joint_state.pt + +关节物体:schema `object/articulated/v1`,`articulation.json` 登记 `parts` 与 `joints`。每个 part 有 `part_id`、`parent_id`(根为 null)、`has_model`、`mesh_ref`;has_model=false 时 mesh_ref=null,结构节点允许没有网格。父链不得成环。每个 joint 有唯一 `joint_id`、`parent_part`、`child_part`、`type`;fixed 单位 null、revolute 弧度、prismatic 米。有源限位时保存 `limits:[lower,upper]`;没有时 null,不伪造上下限。部件姿态统一为 `T_camera_from_part [T,4,4]`,不与父局部变换混装。 + +若提供 `joint_state.pt [T,J]`,必须登记固定 joint_order、轴在父部件系的表达、零位变换与正方向,valid 为 `[T,J]`;缺少这些运动学定义时只发布部件位姿与已有来源信息,不伪造可驱动的关节模型。关节值与部件位姿同时存在时需验证一致性。 + +部件层级应声明语义:纯语义包含树允许 `joints=[]`,不将包含关系推断为机械关节。关节状态 schema 为 `object/joint_state/v1`;转动用弧度、移动用米,混合类型按 joint_order 对应的关节定义解释。 + +#### 5.4.5 dimensions、几何关键点与顶点部件标签 + +`dimensions.pt [T,3]` 采用 `object/dimensions/v1`,有效性为 `[T]`。 + +物体/部件 `dimensions` 为 `[length,width,height]` 米,轴顺序与该 mesh 的局部坐标关联,登记 `dimensions_semantics` 和来源。HOI4D dimensions 与 mesh 的具体尺度关系未验证前标为 source_unspecified,保留源值并暂停依赖该关系的几何验收,不能默认为待施加缩放。需要施加缩放时明确 scale_applied_to_mesh,禁止重复应用。 + +源物体关键点放 `object//keypoints/xyz.pt [T,K,3]`(相机系)或 `template_xyz.pt [K,3]`(物体系),schema 分别为 object_keypoints/camera/v1 和 object_keypoints/template/v1。明确 keypoint_schema、keypoint_names、单位及有效性;模板点配合 pose 可投影,无须重复生成全部帧。H2O 中心/角点/棱中点,以及 ARCTIC 部件点分别登记具体源顺序,不套用手的 21 点 schema。每个发布选择一套源几何点并记录选择,不另建方法分支。 + +`vertex_part_ids.pt [V] int64` 绑定 `mesh_ref` 与 topology_id,登记整数到 part_id 的映射;未知用 -1。ARCTIC 不同拓扑的资产分别绑定,不能共用未经转换的顶点标签。部件层级中 is_instance/has_model 等源属性保留,几何文件仍全部归 object。 + +### 5.5 segment:分割类别、编码与覆盖范围 + +每个发布选择一套任务使用的分割表示,不建立方法/标注集分支。没有分割就不创建 segment 目录,不为其他模态创建空的实体表。 + +| schema_id | 文件与数值语义 | +|---|---| +| segment/uint16_labels/v1 | mask.mkv;整数区域编号,通过 instances.jsonl 解释 | +| segment/instance_polygons/v1 | polygons.jsonl;实例多边形,可重叠;当前不支持孔洞拓扑 | +| segment/foreground_intensity/v1 | mask.mkv;0–255 前景强度,不是区域编号或经过校准的概率 | + +#### 5.5.1 uint16 标签图与 instances.jsonl + +组件声明 `segmentation_type=semantic/instance/part`;同一组件固定一种类型。`mask.mkv` 解码为 `[T,H,W] uint16`,schema `segment/uint16_labels/v1`,使用 `mkv/uint16_ffv1/v1`,FFV1 gray16le 无损;只有所有区域编码均 ≤255 时允许 gray8(pixel_format=gray),读取后转 uint16,数值不变。禁止调色板和有损编码。有效性 `[T]`,表示该帧有可用分割标注。数值 0 固定为 unassigned,65535 固定为 ignore,1–65534 为区域编码,不能直接等同 entity_id。 + +`instances.jsonl` 每帧一行,包含 `frame_index` 与 `labels`。每条标签包含 `mask_value`、`category_id`、`entity_id`、`part_id`;无意义或未知字段为 null。semantic 允许 entity_id=null;instance 必须引用 hand_left/hand_right 或登记的 object_id;part 还须关联登记部件。源实例 ID 和其他属性分别保存在 `source_instance_id`、`source_attributes`。mask 中每个非保留编码必须有且仅有一个映射。 + +FreiHAND 的试点按本任务需要,统一到手/背景类别,保留每个原生区域编码;不要求给原生细分区域猜测手指名称。需要细部件监督时,尚未核实的部件名称必须保持未知,不能因粗粒度手类别已核实便声称部件语义也已统一。 + +#### 5.5.2 重叠实例多边形 + +每发布选择一套任务使用的分割表示,不建立方法/标注集分支。VISOR 的实际试点存在重叠实例多边形,单层标签图不能无损表达。对此补充 `segment/instance_polygons/v1`:`segment/polygons.jsonl` 每帧包含 `frame_index` 和 `instances`,每实例包含 `mask_value` 与 `polygons`(列表,每个多边形为源图像像素坐标顶点序列,保留原始精度)。身份和类别仍由同一 `instances.jsonl` 映射,有效性仍为 `[T]`,通过 schema 区分物理编码。允许多实例重叠,不采用后画覆盖前画。消费者按需栅格化为独立实例二值 mask;不能声称合并的单层 mask 无损。 + +#### 5.5.3 灰度前景强度 + +ReInterHand 的官方渲染 mask 为双手合并的灰度前景掩码,实测存在 0–255 的中间值,不是左右手实例编号。登记 `segment/foreground_intensity/v1`:仍存 `segment/mask.mkv`,解码为 `[T,H,W] uint16`,使用 `mkv/uint16_ffv1/v1`,此类数据优先编码为 FFV1 gray8(pixel_format=gray),读取后转 uint16。有效值范围 0–255,归一化值为 `float32(value)/255`;0 为背景端点、255 为前景端点。组件声明 `foreground_category=hand`、`entity_id=null` 和双手合并语义,不使用区域编号映射。这里保留原始渲染 mask 强度,不把它称为经过校准的概率。若任务需要二值 mask,阈值化属于任务层派生操作,记录阈值;共享层不丢弃中间灰度。不同 schema 的数值含义不同,不能将该文件按整数类别图解码。 + +FreiHAND 训练集的 JPEG mask 使用 `segment/foreground_intensity/v1`,逐像素保留 JPEG 解码后的灰度,`entity_id=hand_right`。该 schema 不限定双手合并:单手或合并范围由 `entity_id` 与 `coverage` 明确声明。评估集整数区域图仍用 `segment/uint16_labels/v1`,两者不能仅凭文件名使用同一种解码语义。 + +#### 5.5.4 coverage 与有效性 + +`coverage.kind=full/selected_entities/partial/unknown`。full 指声明的标注范围完整;selected_entities 还应列出目标范围。无论哪种,0 本身不自动成为背景;背景要有明确类别映射,未标注区域不能用于构造负样本。保留源逐类/逐实例 exhaustive 信息,未知不可改写为完整。 + +三种表示的帧级有效性均为 `[T]`,表示该帧是否提供此分割标注;对应 valid_ref 在组件中登记,仍用小型 bool `.pt` 数组。栅格 mask 必须登记 storage,格式见 3.1.2,所有帧的整数编码或强度逐值完全相同。编码语义由 schema_id 决定,读取器不能仅依据 mask.mkv 文件名选择解码方式。 + +### 5.6 contact:接触、抓取、区域与距离 + +#### 5.6.1 relations.jsonl 与 relations_valid.pt + +`annotation/contact/relations.jsonl`,schema contact/relations/v1,每帧一行含 frame_index、relations。每条记录含 relation_type(contact/grasp)、subject_id(手槽或登记实体)、object_id、status、source_locator、provenance。status 固定为 positive/negative/unknown/target_unannotated:positive 必须有可解析目标,negative 表示源明确否定该关系,unknown 为不确定,target_unannotated 为确有接触但目标未标注。非 positive 的 object_id 可 null,不能用 null 冒充“不接触”。稀疏源无记录的帧不自动补 negative。 + +VISOR 的对象 mask ID 必须先按同帧 source_instance_id 解析成 object_id;hand-not-in-contact、none-of-the-above、inconclusive 分别映射 negative、target_unannotated、unknown,保留原始字符串。Dex ycb_grasp_ind 通过 ycb_ids 映射到登记物体,以 relation_type=grasp 保存;不得当作逐顶点接触。 + +relations 组件的 valid_ref 指向 `relations_valid.pt [T] bool`,表示该帧是否有可用源关系标注。有效帧中可以存在 status=unknown 的明确不确定标注;无源标注的帧为 valid=false、relations=[]。组件仍声明 available/provenance/source_locator。 + +#### 5.6.2 实体对的顶点区域与距离 + +已发布的接触区域/距离按参与关系的 subject_id 与 object_id 组织,每对实体保留选定的一套结果,以精确 geometry_ref/topology_id 关联到手或物体/部件;不要求每套数据都有。顶点区域 schema contact/vertex_region/v1:bool `[T,V]` 加同形 valid;顶点距离 schema contact/vertex_distance/v1:float32 `[T,V]`、米、同形 valid,声明 source/target geometry_ref、distance_definition(signed/unsigned、测量到点集或表面等明确源定义)。geometry_ref 必须指向已登记 mesh 或由固定 MANO 模型配置确定的拓扑;拓扑/顶点数变化时按拓扑拆分片段。其他源区域表示只有在实际接入并登记 schema 后才可转换,不能随意栅格化宣称等价。 + +顶点区域/距离已有存储定义,但尚未完成真实输入试点;接入时必须提供源语义与几何验收证据,不因已经登记 schema 就视为通过。 + +## 附录:任务范围 + +不强制收录 2D bbox、完整高频动捕、动作程序、身体 SMPL-X、点云或网络特征。范围内的接触、visibility、选定手关键点、物体几何不能因不便处理而静默丢弃。分割采用的物理编码由第 5.5 节决定,存在重叠时不能以单层标签图声称无损。 + +不设置 entities_ref/segment/entities.json,不要求与 object_id 重复的 track_id。MediaPipe 不在当前关键点定义中;旧版本迁移必须保留可追溯关系,不能直接删表。手部共享表示不含独立 hand_mesh。 + +schema.json 是普通注册表,不是 JSON Schema 文档或可执行验收器;定义存在不代表真实数据已验证。验收须保留实测范围与未决项。 + +本存储约定只更新标准,不代表既有 FFV1/depth.pt 试点已迁移。新发布必须显式写 storage 配置;旧产物按其旧定义读取,不能只改文件后缀或版本标识伪装为合规。 diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/docs/h2o-RAW_TO_SHARED.md b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/docs/h2o-RAW_TO_SHARED.md new file mode 100644 index 0000000000000000000000000000000000000000..431eeb6d59885c914d340d24e9ebe8b207ec84b3 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/docs/h2o-RAW_TO_SHARED.md @@ -0,0 +1,30 @@ +# H2O raw → shared-v1.0 + +## 范围与来源 + +本版本仅转换 `raw/data/subject{1,2,3,4}_v1_1.tar.gz` 的真实五视角 (`cam0`–`cam4`) 序列;`h2o_CASA.tar` 是单独的扩展,不与标准序列混合。每个原始序列存于 `data/subjectN__/cam{0..4}/`。源压缩包保持不变,不合成源不存在的标注。输出仅在本地制作;完整序列试点及人工检查通过、更新全量预估之前,不启动全量。 + +| 源包/字段 | shared 文件/处理 | +| --- | --- | +| `subjectN_v1_1.tar.gz`: `camX/rgb/.png` | `observation/rgb.mkv`:逐帧源 RGB 解码为 RGB24,FFV1 直接编码;输出**每帧**解码与源 RGB 字节摘要完全一致。`rgb_valid.pt` 记录存在性,源帧号和每组件的包成员及 SHA256 写入 `camera/frames.jsonl`。不再额外编码未采用的 H.264 RGB 候选;FFV1 编码器进程失败时才尝试 H.264。 | +| 同包 `camX/depth/.png` | `observation/depth.mkv` 和 `depth_valid.mkv`;按源毫米单位除以 1000 转米,保留无效深度与全帧时间轴,深度位串以 FFV1 保真封装并逐帧校验。既不做 3 米裁剪也不造出缺失的深度。 | +| `camX/cam_intrinsics.txt`、`camX/cam_pose/.txt` | `camera/intrinsic.pt`、`extrinsic.pt`:保留源内参;逐帧源 `T_world_from_camera` 求逆后存 `T_camera_from_world`;声明变换约定与有效性。 | +| `camX/hand_pose_mano/.txt` | `annotation/mano/motion.pt`、`motion_valid.pt`:源左/右手标志各自判断有效性;姿态与平移保持源数值,声明 MANO 模型配置,缺模型则明确标依赖缺失,不伪造网格或掩码。 | +| `camX/hand_pose/.txt` | `annotation/keypoints/xyz.pt`、`xyz_valid.pt`:源双手 21 点,相机坐标系米制,与 MANO 有效性彼此独立。HTML 中的投影仅用于人工预览,不写回训练数据。 | +| `camX/obj_pose/.txt`、`obj_pose_rt/.txt` | `annotation/object//keypoints/xyz.pt`、`pose.pt`:按源类号关联 21 个物体点及物体→相机位姿;仅源存在时登记组件及有效性。 | +| `object.zip` | `annotation/object//assets/` 与源 OBJ、MTL、纹理;静态形状预览不等于所有帧网格位姿的投影证明。 | +| `label_split.zip` 的 `action_{train,val,test}.txt` | 序列元数据的官方划分及来源;未知映射明确记 `unknown`,不自行编排。 | + +`cam4` 是 ego,`cam0`–`cam3` 是 exo。真实时间/FPS 缺乏可靠来源时使用 null,不把 MKV 封装帧率冒充采集时钟。源 `action_label`、`verb_label`、pose 任务帧列表和 `manolabel_v1.1.tar.gz` 保留在 raw;当前契约没有相应动作组件,本发布不宣称它们已转换。源没有像素分割,本版本不投影网格生成替代分割。 + +## 源资产文件名修复 + +源 `object/cocoa/cocoa.obj` 引用 `ovomaltine.mtl`,材质内写的是 `map_Kd cocoa.png`,但原 ZIP 只提供 `ovomaltine.png`。仅在临时解压目录为该已确认的纹理增加**字节相同**的 `cocoa.png` 别名,保留原 PNG、OBJ、MTL 不变;在网格 `source_locator.texture_aliases` 中记录别名、原始包成员和 SHA256。别名与已保留的旧 cocoa 资产一致,不替换图像、标注或网格。全部八类物体的材质依赖在读取大 subject 包之前预检,其他缺失/越界依赖仍报错。 + +## 加速与验收 + +四个互不依赖的 subject 压缩包可由 `--workers 1..4` 并行顺序读取,各 worker 一次只处理一个序列。数值库保持单线程;FFV1 编码支持 `--codec-threads 1|2|4|8|10`,当前全量按用户要求使用 10,逐帧解码校验仍保留。并发数由相同输入实测吞吐量决定,记录 OS 线程峰值和磁盘占用,不以 CPU 线程数本身作为提速证据。RGB 源为 PNG,不适用 ARCTIC/HOT3D 的 JPEG 包直封和 16 帧抽查:RGB、深度、有效性与数值模态仍逐帧精确校验。临时文件在 `/data` 上隔离放置,历史 62 条目录不复用、不覆盖;调整并发时,在新的运行目录复用本次全量已经原子发布的完整序列,并从源重新核对帧号及逐组件 SHA256。未完成的临时序列不复用,原运行的脚本、配置及 QC 保留用于溯源。 + +先运行不截帧的代表性完整序列试点,保存自动 QC、真实耗时和 `doc/validation/index.html`(RGB、深度、源 3D 关键点投影、原生物体网格和全组件数值/有效性)。试点由人工核查之后再决定全量;全量后再次抽样人工核查。报告须区分数据完整性、源未提供的模态与仅供人工判断的几何对齐。 + +2026-09-29 完整序列试点已获人工确认,用户已授权本地全量。2026-09-30 用户取消 CPU 使用量上限,指定 4 个独立压缩包 worker、每个 FFV1 编码器 10 线程;Python worker、读取及校验子进程不计入这最多 40 个编码线程,因此总线程数不固定为 40。该配置不代表已证明加速倍数。源包和旧产物保留;代码变化使用独立运行目录,已完成序列保留原始构建记录及生产脚本快照。 diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/docs/schema.json b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/docs/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..d904a34272de7f3fd4428c8dc68a919e94a68fca --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/docs/schema.json @@ -0,0 +1,869 @@ +{ + "schema_version": "hand-warehouse/1.0", + "validity_revision": "usable-annotation-2026-09-20", + "annotation_validity": { + "meaning": "annotation usable for supervision, not merely record presence", + "formula": "source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass AND NOT explicitly_reviewed_local_exclusion", + "without_official_qa": "omit QA term; declare source rules; do not fabricate QA", + "policy_field": "components..valid_policy", + "visibility_is_independent": true, + "invalid_float_value": "NaN", + "hot3d": "broadcast per-camera frame manual QA conservatively to hand/object labels and pose-derived visibility; retain RGB and source calibration; keep native QA in raw and review report", + "hot3d_visibility": "native visibility_ratio[%] already ranges from 0 to 1; do not divide by 100" + }, + "hand_slots": [ + "left", + "right" + ], + "keypoints": { + "mano21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map": null, + "note": "adapter maps official MANO joint and fingertip convention" + }, + "rhd21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map_per_hand": [ + 0, + 4, + 3, + 2, + 1, + 8, + 7, + 6, + 5, + 12, + 11, + 10, + 9, + 16, + 15, + 14, + 13, + 20, + 19, + 18, + 17 + ] + } + }, + "camera": { + "opencv_fisheye4": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "k3", + "k4" + ], + "projection": "theta=atan(r); theta_d=theta*(1+k1*theta^2+k2*theta^4+k3*theta^6+k4*theta^8); source ReInterHand" + }, + "pinhole": { + "K": [ + 3, + 3 + ] + }, + "fisheye624": { + "parameters": [ + "f", + "cx", + "cy", + "k0", + "k1", + "k2", + "k3", + "k4", + "k5", + "p0", + "p1", + "s0", + "s1", + "s2", + "s3" + ] + }, + "rational8": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "p1", + "p2", + "k3", + "k4", + "k5", + "k6" + ] + } + }, + "segmentation": { + "segment/uint16_labels/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "polygons.jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "note": "Registry for hand-warehouse/1.0. Read CONTRACT.md for field semantics. This is not a JSON Schema document or executable validator.", + "components": { + "mano/axis_angle61/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 61 + ], + "valid_shape": [ + "T", + 2 + ], + "unit": "m", + "angle_unit": "rad", + "coordinate_frame": "camera", + "layout": { + "pose_axis_angle": [ + 0, + 48 + ], + "shape": [ + 48, + 58 + ], + "translation": [ + 58, + 61 + ] + } + }, + "keypoints/uv/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 2 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "pixel", + "required_metadata": [ + "keypoint_schema" + ] + }, + "keypoints/xyz/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 3 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "m", + "required_metadata": [ + "keypoint_schema" + ] + }, + "depth/z_float32/v1": { + "storage": "mkv", + "dtype": "float32", + "shape": [ + "T", + "H", + "W" + ], + "valid_shape": [ + "T", + "H", + "W" + ], + "unit": "m", + "depth_type": "z", + "pixel_grid": "current_rgb", + "coordinate_frame": "current_rgb_camera", + "valid_storage": "mkv", + "allowed_storage_profiles": [ + "mkv/depth_float32_bits/v1" + ], + "allowed_valid_storage_profiles": [ + "mkv/bool_ffv1/v1" + ], + "required_metadata": [ + "storage", + "valid_storage", + "depth_origin" + ], + "depth_origin_values": [ + "measured", + "rendered", + "unknown" + ] + }, + "transform/se3/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention" + ] + }, + "object/rigid/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention" + ] + }, + "camera/pinhole/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/rational8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/opencv_fisheye4/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/fisheye624/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 15 + ], + "valid_shape": [ + "T" + ] + }, + "camera/distortion8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 8 + ], + "valid_shape": [ + "T" + ] + }, + "camera/fisheye4_distortion/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4 + ], + "valid_shape": [ + "T" + ] + }, + "object/joint_state/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "J" + ], + "valid_shape": [ + "T", + "J" + ], + "required_metadata": [ + "joint_order" + ], + "unit_rule": "revolute radians; prismatic metres; mixed types declared per joint" + }, + "object_keypoints/camera/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "K", + 3 + ], + "valid_shape": [ + "T", + "K" + ], + "unit": "m", + "coordinate_frame": "camera", + "required_metadata": [ + "keypoint_schema" + ] + }, + "object/dimensions/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "dimensions_semantics" + ], + "axis_order": [ + "length", + "width", + "height" + ], + "scale_rule": "do not apply to mesh without source-supported size/scale relation" + }, + "object_keypoints/template/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "K", + 3 + ], + "valid_shape": [ + "K" + ], + "unit": "m", + "coordinate_frame": "object", + "static": true, + "required_metadata": [ + "keypoint_schema" + ] + }, + "mesh/obj/v1": { + "storage": "obj", + "unit": "m", + "static": true, + "valid_shape": [], + "dependencies": "MTL and textures retained under owning object" + }, + "rgb/uint8/v1": { + "storage": "mkv", + "dtype": "uint8", + "shape": [ + "T", + "H", + "W", + 3 + ], + "valid_shape": [ + "T" + ], + "color_order": "RGB", + "allowed_storage_profiles": [ + "mkv/mjpeg_copy/v1", + "mkv/source_copy/v1", + "mkv/h264_rgb_lossless/v1", + "mkv/ffv1_rgb/v1" + ], + "required_metadata": [ + "storage" + ] + }, + "contact/relations/v1": { + "storage": "jsonl", + "valid_shape": [ + "T" + ], + "frame_keys": [ + "frame_index", + "relations" + ], + "absence_semantics": "no record is not a negative contact annotation" + }, + "contact/vertex_region/v1": { + "storage": "pt", + "dtype": "bool", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id" + ], + "pilot_status": "defined_not_empirically_validated" + }, + "contact/vertex_distance/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "unit": "m", + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id", + "distance_definition" + ], + "pilot_status": "defined_not_empirically_validated" + }, + "object/articulated/v1": { + "storage": "json", + "required_keys": [ + "parts", + "joints" + ], + "part_keys": [ + "part_id", + "parent_id", + "has_model", + "mesh_ref" + ], + "hierarchy_semantics": "declare mechanical articulation or semantic containment; containment alone does not imply joints", + "acyclic": true + }, + "segment/uint16_labels/v1": { + "storage": "mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "storage_revision": "lossless-video-2026-09-18", + "sampling": { + "image": { + "single": { + "T": 1 + }, + "independent": { + "T": ">=2", + "required_frame_fields": [ + "sample_id", + "source_locator" + ], + "temporal_relationship": false + }, + "source_fps": null + }, + "video": { + "sampling_types": [ + "dense", + "sparse" + ] + } + }, + "storage_profiles": { + "mkv/mjpeg_copy/v1": { + "container": "matroska", + "codec": "mjpeg", + "method": "stream_copy_from_source_jpeg", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "source_jpeg_packet_sha256_exact", + "all_packet_count_order_and_dimensions_exact", + "deterministic_decoded_rgb_sample_exact", + "pilot_and_final_selected_whole_sequences_decoded_rgb_exact" + ], + "validation_policy": { + "id": "jpeg-packets-all-rgb-sample16/v1", + "sample_count_per_view": 16, + "short_views": "all_frames_if_T_less_than_16", + "fixed_indices": "0,T-1,T//4,T//2,3*T//4, deduplicated", + "remaining_indices": "sample without replacement to min(T,16) using Python random.Random(seed)", + "seed": "first 8 bytes of SHA256(sequence_id/camera_id/20260920), big-endian integer", + "report": "policy, exact selected frame indices, seed, separate packet and pixel coverage", + "legacy_all_frame_pixel_proofs": "still accepted; preserve historical evidence" + } + }, + "mkv/source_copy/v1": { + "container": "matroska", + "codec": "source_codec_declared_in_metadata", + "method": "stream_copy_only", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "no_reencoding", + "all_decoded_rgb_frames_exact", + "presentation_frame_order_exact" + ] + }, + "mkv/h264_rgb_lossless/v1": { + "container": "matroska", + "codec": "h264", + "encoder": "libx264rgb", + "crf": 0, + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "gop": "declared_in_encoder_parameters", + "validation": [ + "all_decoded_rgb_frames_exact" + ], + "forbidden": [ + "lossy_rate_control", + "rgb_to_yuv420_subsampling" + ] + }, + "mkv/ffv1_rgb/v1": { + "container": "matroska", + "codec": "ffv1", + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "validation": [ + "all_decoded_rgb_frames_exact" + ] + }, + "mkv/depth_float32_bits/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray16le", + "logical_dtype": "float32", + "logical_shape": [ + "T", + "H", + "W" + ], + "encoded_shape": [ + "T", + "H", + "2*W" + ], + "packing": "IEEE754 little-endian float32 bits; low uint16 in first W columns, high uint16 in last W columns", + "decode": "reinterpret_float32(uint32(low) | (uint32(high) << 16))", + "validation": [ + "all_float32_bits_exact_including_nan" + ] + }, + "mkv/bool_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray", + "logical_dtype": "bool", + "stored_values": [ + 0, + 1 + ], + "validation": [ + "all_bool_values_exact" + ] + }, + "mkv/uint16_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_formats": [ + "gray", + "gray16le" + ], + "logical_dtype": "uint16", + "gray_condition": "all values <=255; decode by exact uint8-to-uint16 promotion", + "validation": [ + "all_integer_values_exact" + ] + } + }, + "video_metadata": { + "required": [ + "profile", + "codec", + "pixel_format", + "encoded_size", + "decoder", + "encoder_parameters", + "source_lossy" + ], + "source_lossy_values": [ + true, + false, + "unknown" + ], + "timebase_role": "index_only", + "lossless_reference": "source compressed packets or fixed-decoder source pixels; depth uses normalized standard float32 bits", + "selection": "choose smaller complete candidate only after exact roundtrip validation" + } +} diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/full.log b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/full.log new file mode 100644 index 0000000000000000000000000000000000000000..88785c5ae24611caaf852eed171804ef5a164c18 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/full.log @@ -0,0 +1,8 @@ +Verified existing subject1/h1/0 +Verified existing subject2/h1/0 +Verified existing subject1/h1/6 +Verified existing subject1/h1/3 +Verified existing subject2/h1/6 +Converted subject3/h1/0 +Verified existing subject1/h1/7 +Converted subject4/h1/0 diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/full.status b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/full.status new file mode 100644 index 0000000000000000000000000000000000000000..70a37e730f28768cec24b071afd0f74cbce3db74 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/full.status @@ -0,0 +1,7 @@ +START=2026-09-30T10:22:30+08:00 +WORKERS=4 CODEC_THREADS=10 SUBJECTS=1,2,3,4 CASA=false +CPU_LIMIT=none +CGROUP=/user.slice/user-25044.slice/user@25044.service/app.slice/h2o-full-w4c10-r2-20260930.scope +CPU_MAX=max controller_disabled + +RECONFIGURE=2026-09-30T11:03:03+08:00 REASON=decoder10_depth4_no_resume_png_writes diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/run-full.sh b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/run-full.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b9267d75a5fb7c4d1729397219e7f8ca2a688c4 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/run-full.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -u +base="$HOME/Datasets/uni-hoi-h2o-full-20260930-w4-c10" +raw="$HOME/Datasets/Hand-Datasets-Raw/H2O" +cd "$HOME/Projects/uni-hoi-dataset" || exit 1 +mkdir -p "$base/scratch" +export TMPDIR="$base/scratch" PYTHONUNBUFFERED=1 +for n in 1 2 3 4; do test -s "$raw/raw/data/subject${n}_v1_1.tar.gz" || exit 2; done +test ! -e "$base/full.status" || exit 3 +cg=$(awk -F: '$1=="0" {print $3}' /proc/self/cgroup) +if [[ -f "/sys/fs/cgroup$cg/cpu.max" ]]; then + read -r quota period < "/sys/fs/cgroup$cg/cpu.max" +else + quota=max + period=controller_disabled +fi +printf 'START=%s\nWORKERS=4 CODEC_THREADS=10 SUBJECTS=1,2,3,4 CASA=false\nCPU_LIMIT=none\nCGROUP=%s\nCPU_MAX=%s %s\n' "$(date -Is)" "$cg" "$quota" "$period" > "$base/full.status" +if [[ "$quota" != max ]]; then + printf 'EXIT=4 ERROR=UNEXPECTED_CPU_QUOTA\n' >> "$base/full.status" + exit 4 +fi +/usr/bin/time -v .venv/bin/python "$base/frozen-code/scripts/convert_h2o_v1.0.py" --root "$raw" --out "$base" --release-id shared-v1.0 --workers 4 --codec-threads 10 --mano-dir "$HOME/Projects/WiLoR/mano_data" > "$base/full.log" 2>&1 +code=$? +printf 'EXIT=%s END=%s\n' "$code" "$(date -Is)" >> "$base/full.status" +if [[ -f "/sys/fs/cgroup$cg/cpu.stat" ]]; then cat "/sys/fs/cgroup$cg/cpu.stat" >> "$base/full.status"; fi +exit "$code" diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/check_dexycb_projection.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/check_dexycb_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..2774c004fc1359dea582135ec7171f600b33b336 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/check_dexycb_projection.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Check saved Dex-YCB source 3D joints against saved source 2D joints in sampled views.""" +import json +from pathlib import Path +import sys + +import numpy as np +import torch + +root = Path(sys.argv[1]) +report = json.loads((root / 'doc/validation/STRUCTURAL_AUDIT.json').read_text()) +checks = [] +for name in report['sampled_views']: + view = root / name + load = lambda path: torch.load(view / path, weights_only=True, map_location='cpu').numpy() + k = load('camera/intrinsic.pt') + xyz = load('annotation/keypoints/xyz.pt') + uv = load('annotation/keypoints/uv.pt') + valid = load('annotation/keypoints/xyz_valid.pt') & load('annotation/keypoints/uv_valid.pt') + z = xyz[..., 2] + valid &= np.isfinite(xyz).all(axis=-1) & np.isfinite(uv).all(axis=-1) & (z > 0) + z = np.where(valid, z, 1) + pred = np.stack((k[:, 0, 0, None, None] * xyz[..., 0] / z + k[:, 0, 2, None, None], + k[:, 1, 1, None, None] * xyz[..., 1] / z + k[:, 1, 2, None, None]), axis=-1) + errors = np.linalg.norm(pred[valid] - uv[valid], axis=-1) + checks.append(dict(view=name, points=int(errors.size), median_px=float(np.median(errors)) if errors.size else None, + p95_px=float(np.percentile(errors, 95)) if errors.size else None)) +(root / 'doc/validation/KEYPOINT_PROJECTION_QC.json').write_text(json.dumps({ + 'scope': 'Saved source 3D joints projected with saved color intrinsics vs saved source 2D joints; independent of hand mesh rendering.', + 'views': checks}, ensure_ascii=False, indent=2) + '\n') +print(json.dumps(checks, ensure_ascii=False), flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/config.json b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/config.json new file mode 100644 index 0000000000000000000000000000000000000000..f5f637095de54c1431bca56e19cd398949f4111a --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/config.json @@ -0,0 +1,15 @@ +{ + "root": "/home/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O", + "out": "/home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10", + "release_id": "shared-v1.0", + "limit": null, + "max_frames": null, + "mano_dir": "/home/xuzhefeng/Projects/WiLoR/mano_data", + "views": null, + "jpeg_full_check": false, + "workers": 4, + "codec_threads": 10, + "subjects": null, + "include_casa": false, + "archive": null +} diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/convert_dexycb_v1.0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/convert_dexycb_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..ed3f479787fae378b3d3b51ce2f58ccaebfd3d0f --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/convert_dexycb_v1.0.py @@ -0,0 +1,349 @@ +#!/usr/bin/env python3 +"""Dex-YCB source annotations → CONTRACT.md v1.0. No derived annotations.""" +import io +import re +import shutil +import tarfile +import tempfile +from pathlib import Path + +import numpy as np +from PIL import Image +import yaml + +from warehouse_v1_0 import (View, build_record, find_file, locator, mano_models, mesh_asset, + model_profile, parser, pca_to_axis_angle, release, roots, safe_member, sequence_dir) + +IMG_W, IMG_H = 640, 480 + +class _Loader(yaml.SafeLoader): + pass + + +_Loader.add_constructor("tag:yaml.org,2002:python/tuple", + lambda l, n: tuple(l.construct_sequence(n))) + + +def yaml_load_bytes(data: bytes): + return yaml.load(io.BytesIO(data), Loader=_Loader) + + +class Calibration: + def __init__(self, dexycb_root: Path): + self.intrinsics = {} # serial -> {fx,fy,cx,cy,w,h} + self.extrinsics = {} # group -> {serial: [12] 行优先 3×4 cam→world} + self.betas = {} # mano_calib_name -> [10] + calib_dir = dexycb_root / "calibration" + if calib_dir.is_dir(): + self._load((p.as_posix(), p.read_bytes()) + for p in sorted(calib_dir.rglob("*")) if p.is_file()) + else: + tar_path = dexycb_root / "calibration.tar.gz" + if not tar_path.exists(): + raise FileNotFoundError(f"no calibration/ nor calibration.tar.gz in {dexycb_root}") + with tarfile.open(tar_path, "r:gz") as tf: + self._load((m.name, tf.extractfile(m).read()) for m in tf if m.isfile()) + + _RE_INTR = re.compile(r"(?:^|/)intrinsics/(\d+)_\d+x\d+\.yml$") + _RE_EXTRA = re.compile(r"(?:^|/)extrinsics_(\d{8}_\d{6})/extrinsics\.yml$") + _RE_MANO = re.compile(r"(?:^|/)mano_(\d{8}_\d{6}_subject-\d{2}_right)/mano\.yml$") + + def _load(self, files): + for rel, data in files: + m = self._RE_INTR.search(rel) + if m: + c = yaml_load_bytes(data)["color"] + self.intrinsics[m.group(1)] = {"fx": float(c["fx"]), "fy": float(c["fy"]), + "cx": float(c["ppx"]), "cy": float(c["ppy"]), + "w": IMG_W, "h": IMG_H} + continue + m = self._RE_EXTRA.search(rel) + if m: + raw = yaml_load_bytes(data)["extrinsics"] + self.extrinsics[m.group(1)] = { + str(s): [float(x) for x in np.asarray(v).ravel()] for s, v in raw.items()} + continue + m = self._RE_MANO.search(rel) + if m: + self.betas[m.group(1)] = [float(b) for b in yaml_load_bytes(data)["betas"]] + + + +def calibration_locator(path, member, **extra): + if path.is_dir(): + return locator(path / member.removeprefix('calibration/'), **extra) + return locator(path, member, **extra) + + +def prepare_models(root, destination): + archive = find_file(root, 'models.tar.gz') + if archive is None: + return {}, None + pattern = re.compile(r'^models/(\d{3}_[a-z0-9_]+)/(textured_simple\.obj(?:\.mtl)?|texture_map\.png)$') + names = set() + with tarfile.open(archive, 'r|gz') as tf: + for member in tf: + match = pattern.fullmatch(member.name) + if member.isfile() and match: + names.add(match[1]) + path = safe_member(destination, '/'.join(match.groups())) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(tf.extractfile(member).read()) + if len(names) != 21: + raise ValueError('expected all 21 source YCB model directories') + return {i: destination / name for i, name in enumerate(sorted(names), 1)}, archive + + +def convert_view(path, args, seq, serial, frames, meta, meta_loc, calib, calib_path, models, assets, asset_archive): + total = int(meta.get('num_frames', max(frames) + 1)) + ids = list(range(min(total, args.max_frames) if args.max_frames else total)) + for f in ids: + frames.setdefault(f, {}) + if not ids: + raise ValueError('no RGB frames') + source_rows = [] + for f in ids: + row = frames[f] + source_rows.append(dict(source_frame_id=f, sync_id=f'{seq}:{f}', + source_locator=row['color'][1] if 'color' in row else (meta_loc | {'source_frame_id': f, 'missing_rgb': True}), annotation_matches={ + 'labels': {'source_frame_id': f, 'source_timestamp_ns': None, 'clock_domain': None, + 'match_method': 'index_map', 'delta_ns': None, 'source_locator': row['labels'][1]} + for _ in [0] if 'labels' in row}, + component_sources={k: v[1] for k, v in row.items()})) + view = View(path, 'dex-ycb', args.release_id, seq, serial, source_rows, + sampling='dense' if ids == list(range(ids[0], ids[-1] + 1)) else 'sparse') + view.valid_rules = { + 'mano': 'Source pose_m present and not all zero; side model/calibration available', + 'keypoints': 'Corresponding joint_2d/joint_3d present; whole-hand all -1 is missing, broadcast to its 21 points', + 'pose': 'Source pose_y for this ycb_ids slot present and not an all-zero matrix', + 'segment': 'Source seg array provided for this frame; region codes and entity references validated', + 'relations': 'Source sequence ycb_grasp_ind resolves through ycb_ids; broadcast sequence grasp to selected frames', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'exo' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} + subject = re.search(r'subject-(\d+)', seq) + if subject and 1 <= int(subject[1]) <= 10: + index = int(subject[1]) + view.meta.update(split='val' if index == 7 else 'test' if index in (8, 9) else 'train', + split_scheme='Dex-YCB/s1', split_source_locator={ + 'url': 'https://github.com/NVlabs/dex-ycb-toolkit/blob/master/dex_ycb_toolkit/dex_ycb.py', + 'rule': 's1 unseen-subject: 01-06/10 train, 07 val, 08-09 test'}) + view.meta.pop('split_reason', None) + view.rgb([frames[f]['color'][0] if 'color' in frames[f] else None for f in ids], {'frames_ref': 'camera/frames.jsonl'}) + n = len(ids) + intr = calib.intrinsics.get(serial) + K = None if intr is None else np.array([[intr['fx'], 0, intr['cx']], [0, intr['fy'], intr['cy']], [0, 0, 1]]) + ext = calib.extrinsics.get(str(meta['extrinsics']), {}).get(serial) + E = None + if ext is not None: + E = np.eye(4) + E[:3] = np.asarray(ext).reshape(3, 4) + E = np.linalg.inv(E) + view.camera(K, calibration_locator(calib_path, f'calibration/intrinsics/{serial}_640x480.yml'), E, + calibration_locator(calib_path, f'calibration/extrinsics_{meta["extrinsics"]}/extrinsics.yml', + conversion='inverse of source T_world_from_camera')) + sides = meta.get('mano_sides') + if sides not in (['left'], ['right']): + raise ValueError(f'expected exactly one anatomical source hand: {sides}') + side = sides[0] + slot = ['left', 'right'].index(side) + cal_name = meta['mano_calib'][0] if isinstance(meta['mano_calib'], list) else meta['mano_calib'] + labels = [dict(np.load(frames[f]['labels'][0])) if 'labels' in frames[f] else {} for f in ids] + label_loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources.labels'} + motion = np.full((n, 2, 61), np.nan, np.float32) + mv = np.zeros((n, 2), bool) + if side in models and any('pose_m' in lab for lab in labels): + for i, lab in enumerate(labels): + if 'pose_m' not in lab: + continue + pose = np.asarray(lab['pose_m']).reshape(51) + if not np.any(pose): # Official Dex-YCB missing-pose sentinel, independent of joints/seg. + continue + motion[i, slot] = np.r_[pose[:3], pca_to_axis_angle(pose[3:48], models[side]), + calib.betas[cal_name], pose[48:51]] + mv[i, slot] = True + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], label_loc, model_profile=model_profile(models), + calibration_source=calibration_locator(calib_path, f'calibration/mano_{cal_name}/mano.yml'), + provenance={'kind': 'format_conversion', 'method': 'source PCA @ hands_components + hands_mean; explicit axis-angle consumed with flat_hand_mean=true'}) + elif any('pose_m' in lab for lab in labels): + view.absent('mano', 'Source PCA exists; provide --mano-dir to expand it', 'dependency_missing') + else: + view.absent('mano', 'No source pose_m field') + for source_key, key, dim, unit in [('joint_2d', 'uv', 2, 'pixel'), ('joint_3d', 'xyz', 3, 'm')]: + if not any(source_key in x for x in labels): + view.absent('keypoints_' + key, 'No source ' + source_key) + continue + points = np.full((n, 2, 21, dim), np.nan, np.float32) + valid = np.zeros((n, 2, 21), bool) + for i, lab in enumerate(labels): + if source_key not in lab: + continue + p = np.asarray(lab[source_key]).reshape(21, dim) + points[i, slot] = p + valid[i, slot] = not np.all(p == -1) # Official sentinel covers the whole source hand. + # An individual off-image point (-1, -1) is not evidence of missing annotation. + view.tensor('keypoints_' + key, f'keypoints/{key}/v1', f'annotation/keypoints/{key}.pt', + points, valid, ['T', 'hand', 'keypoint', 'coordinate'], label_loc, + keypoint_schema='mano21/v1', unit=unit) + ycb_ids = [int(x) for x in meta['ycb_ids']] + for j, oid in enumerate(ycb_ids): + entity = f'ycb_{oid:02d}' + view.object(entity, meta_loc, source_object_id=oid, category_id=oid) + poses = np.full((n, 4, 4), np.nan, np.float32) + valid = np.zeros(n, bool) + for i, lab in enumerate(labels): + if 'pose_y' in lab: + pose = np.asarray(lab['pose_y']) + if pose.shape != (len(ycb_ids), 3, 4): + raise ValueError('pose_y shape differs from ycb_ids') + if np.any(pose[j]): # Official all-zero missing object pose sentinel. + poses[i] = np.eye(4) + poses[i, :3] = pose[j] + valid[i] = True + if any('pose_y' in lab for lab in labels): + view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', + poses, valid, ['T', 'row', 'column'], label_loc, + convention='T_camera_from_object', unit='m') + else: + view.absent('pose_' + entity, 'No source pose_y field') + if oid in assets: + mesh_asset(view, entity, assets[oid], assets[oid] / 'textured_simple.obj', + locator(asset_archive, f'models/{assets[oid].name}/textured_simple.obj')) + else: + view.absent('mesh_' + entity, 'models.tar.gz unavailable', 'not_downloaded') + if any('seg' in lab for lab in labels): + mask_rows = [] + width, height = view.meta['camera']['image_size'] + for i, lab in enumerate(labels): + values = np.unique(lab.get('seg', np.zeros((height, width), np.uint8))) + mappings = [] + for value in values: + value = int(value) + if value == 0: + continue + if value != 255 and value not in ycb_ids: + raise ValueError(f'unknown Dex-YCB region value {value}') + mappings.append(dict(mask_value=value, category_id='hand' if value == 255 else value, + entity_id='hand_' + side if value == 255 else f'ycb_{value:02d}', part_id=None, + source_instance_id=value)) + mask_rows.append(dict(frame_index=i, labels=mappings)) + view.raster('segment', (lab.get('seg', np.zeros((height, width), np.uint16)) for lab in labels), + ['seg' in lab for lab in labels], label_loc, mask_rows) + view.meta['components']['segment'].update(coverage={'kind': 'selected_entities', + 'entities': ['hand_' + side] + [f'ycb_{o:02d}' for o in ycb_ids]}, source_zero_meaning='background') + else: + view.absent('segment', 'No source seg field') + if any('aligned_depth_to_color' in frames[f] for f in ids): + def depths(): + width, height = view.meta['camera']['image_size'] + for f in ids: + item = frames[f].get('aligned_depth_to_color') + if item is None: + yield np.full((height, width), np.nan, np.float32) + else: + with Image.open(item[0]) as im: + yield np.asarray(im).astype(np.float32) / 1000.0 + view.raster('depth', depths(), None, {'frames_ref': 'camera/frames.jsonl', + 'source_field': 'component_sources.aligned_depth_to_color', 'conversion': 'millimetres to metres'}) + else: + view.absent('depth', 'No source aligned_depth_to_color frames') + grasp = meta.get('ycb_grasp_ind') + if grasp is not None: + if not 0 <= int(grasp) < len(ycb_ids): + raise ValueError('invalid ycb_grasp_ind') + relation = dict(relation_type='grasp', subject_id='hand_' + side, + object_id=f'ycb_{ycb_ids[int(grasp)]:02d}', status='positive', source_locator=meta_loc, + provenance={'kind': 'source', 'method': 'sequence ycb_grasp_ind resolved through ycb_ids; not per-frame contact'}) + view.relations([{'frame_index': i, 'relations': [relation]} for i in range(n)], np.ones(n, bool), meta_loc) + else: + view.absent('relations', 'No source grasp/contact relation') + return view.finish() + + +MEMBER = re.compile(r'^([^/]+)/(\d{8}_\d{6})/(meta\.yml|(\d{12})/(color|labels|aligned_depth_to_color)_(\d+)\.(jpg|npz|png))$') + + +def convert_archive(archive, args, out, calib, calib_path, models, assets, asset_archive): + selected_views = set(args.views.split(',')) if args.views else None + done = 0 + current, meta, meta_loc, rows = None, None, None, {} + with tempfile.TemporaryDirectory(prefix='dex-source-') as wd: + work = Path(wd) + def flush(): + nonlocal done + if not rows: + return + seq = archive.name.split('.tar')[0] + '_' + current + reports = {} + with sequence_dir(out, seq) as target: + for serial, frames in sorted(rows.items()): + reports[serial] = convert_view(target / serial, args, seq, serial, frames, meta, + meta_loc, calib, calib_path, models, assets, asset_archive) + build_record(out, seq, reports) + for staged in list(work.iterdir()): + if staged.is_dir(): + shutil.rmtree(staged) + else: + staged.unlink() + done += 1 + print(f'Converted {seq}', flush=True) + with tarfile.open(archive, 'r|gz') as tf: + for member in tf: + match = MEMBER.fullmatch(member.name) + if not member.isfile() or not match: + continue + seq = match[2] + if seq != current: + flush() + if args.limit and done >= args.limit: + break + current, meta, meta_loc, rows = seq, None, None, {} + data_kind = match[3] + if data_kind == 'meta.yml': + data = tf.extractfile(member).read() + meta = yaml_load_bytes(data) + meta_loc = locator(archive, member.name, data) + continue + serial, kind, f = match[4], match[5], int(match[6]) + if selected_views and serial not in selected_views or args.max_frames and f >= args.max_frames: + continue + data = tf.extractfile(member).read() + dest = safe_member(work, member.name) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(data) + row = rows.setdefault(serial, {}).setdefault(f, {}) + if kind in row: + raise ValueError('duplicate archive frame') + row[kind] = (dest, locator(archive, member.name, data)) + else: + flush() + return done + + +def main(argv=None): + p = parser('dex-ycb', __doc__) + p.add_argument('--subjects') + args = p.parse_args(argv) + archives = sorted({a for r in roots(args.root) for a in r.glob('*-subject-*.tar.gz')}) + if args.subjects: + subjects = {s.strip().zfill(2) for s in args.subjects.split(',')} + archives = [a for a in archives if re.search(r'subject-(\d+)', a.name)[1] in subjects] + if not archives: + p.error('no Dex-YCB subject archives found') + cp = find_file(args.root, 'calibration.tar.gz') or find_file(args.root, 'calibration') + if cp is None: + p.error('calibration source missing') + calib = Calibration(cp.parent) + models = mano_models(args.mano_dir) + out = release(args, 'dex-ycb') + with tempfile.TemporaryDirectory(prefix='dex-models-') as wd: + assets, asset_archive = prepare_models(args.root, Path(wd)) + for archive in archives: + convert_archive(archive, args, out, calib, cp, models, assets, asset_archive) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/convert_h2o_v1.0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/convert_h2o_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..727461a74046ad8dc16ec26d6fdb365b9c304594 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/convert_h2o_v1.0.py @@ -0,0 +1,527 @@ +#!/usr/bin/env python3 +"""H2O native RGB-D, MANO, joints and objects → CONTRACT.md v1.0 (no rendered masks).""" +from concurrent.futures import ThreadPoolExecutor +import json +import os +import re +import shutil +import tarfile +import tempfile +from pathlib import Path +import zipfile + +# Bound native libraries before loading NumPy/Torch; each worker still uses independent FFmpeg processes. +for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + +import numpy as np +from PIL import Image +import torch + +from warehouse_v1_0 import (View, build_record, check_mesh, find_file, locator, mano_models, mesh_asset, + model_profile, parser, release, roots, safe_member, sequence_dir, sha256) + +OBJECTS = {1: 'book', 2: 'espresso', 3: 'lotion', 4: 'spray', + 5: 'milk', 6: 'cocoa', 7: 'chips', 8: 'cappuccino'} +MEMBER = re.compile(r'^(?:h2o_CASA/)?(subject\d+)/([^/]+)/(\d+)/(cam\d)/(.+)$') +FRAME = re.compile(r'(rgb|depth|cam_pose|hand_pose|hand_pose_mano|obj_pose|obj_pose_rt)/(\d+)\.(png|jpg|txt)$') + + +def load_splits(root): + archive = find_file(root, 'label_split.zip') + result = {} + if archive is not None: + with zipfile.ZipFile(archive) as z: + for split in ('train', 'val', 'test'): + member = f'label_split/action_{split}.txt' + for line_no, line in enumerate(z.read(member).decode().splitlines(), 1): + fields = line.split() + if len(fields) < 2 or fields[1] == 'path': + continue + key = fields[1] + if key in result and result[key][0] != split: + raise ValueError('conflicting official splits') + result[key] = (split, locator(archive, member, record=line_no)) + return result + + +def load_assets(root, work): + archive = find_file(root, 'object.zip') + if archive is None: + return {}, None + with zipfile.ZipFile(archive) as z: + for member in z.infolist(): + if member.is_dir(): + continue + path = safe_member(work, member.filename) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(z.read(member)) + result = {} + for oid, name in OBJECTS.items(): + directory = work / 'object' / name + aliases = [] + # Source cocoa.obj -> ovomaltine.mtl -> cocoa.png, but the ZIP names the + # supplied texture ovomaltine.png. Keep all originals and add a byte-identical alias. + if name == 'cocoa' and not (directory / 'cocoa.png').exists(): + mtl = directory / 'ovomaltine.mtl' + if mtl.is_file() and 'map_Kd cocoa.png' in mtl.read_text().splitlines(): + texture = directory / 'ovomaltine.png' + shutil.copyfile(texture, directory / 'cocoa.png') + aliases.append({'file': 'cocoa.png', 'sha256': sha256(texture), + 'source': locator(archive, 'object/cocoa/ovomaltine.png')}) + candidates = list(directory.glob('*.obj')) + if len(candidates) != 1: + raise ValueError(f'expected one source OBJ for {name}') + check_mesh(candidates[0], directory) # Fail before decoding any large subject archive. + result[oid] = (directory, candidates[0], aliases) + return result, archive + + +def convert_view(path, args, seq, cam, rows, intr, splits, models, assets, asset_archive): + codec_threads = getattr(args, 'codec_threads', 1) + ids = list(range(min(rows), max(rows) + 1)) + for f in ids: + rows.setdefault(f, {}) + n = len(ids) + if not n: + raise ValueError('no RGB frames') + split, split_loc = splits.get(seq, ('unknown', None)) + frame_rows = [dict(source_frame_id=f, sync_id=f'{seq}:{f}', source_locator=rows[f]['rgb'][1] if 'rgb' in rows[f] else {'sequence': seq, 'camera': cam, 'source_frame_id': f, 'missing_rgb': True}, + component_sources={k: item[1] for k, item in rows[f].items()}, + annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None) + for k in rows[f] if k != 'rgb'}) for f in ids] + view = View(path, 'H2O', args.release_id, seq.replace('/', '_'), cam, frame_rows, split=split) + view.valid_rules = { + 'mano': 'Per-hand hand_pose_mano flag equals 1; corresponding side model available', + 'keypoints': "Per-hand hand_pose flag equals 1, broadcast to that hand's 21 source points independently of MANO", + 'pose': 'Source obj_pose_rt class equals this nonzero object class', + 'points': 'Source obj_pose class equals this nonzero object class, broadcast to its 21 points', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'ego' if cam == 'cam4' else 'exo' if cam in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} + if split_loc: + view.meta.update(split_scheme='official_action_split', split_source_locator=split_loc) + # In the measured 275 H2O views, exact FFV1 was always smaller than exact H.264. + view.rgb([rows[f]['rgb'][0] if 'rgb' in rows[f] else None for f in ids], + {'frames_ref': 'camera/frames.jsonl'}, ffv1_first=True, codec_threads=codec_threads) + loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} + if intr is not None: + fx, fy, cx, cy, width, height = np.loadtxt(intr[0]).ravel() + if [int(width), int(height)] != view.meta['camera']['image_size']: + raise ValueError('source intrinsics resolution mismatch') + K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) + view.camera(K, intr[1]) + camps = np.full((n, 4, 4), np.nan, np.float32) + cv = np.zeros(n, bool) + data = [] + for i, f in enumerate(ids): + lab = {k: np.loadtxt(item[0]).ravel() for k, item in rows[f].items() if k not in ('rgb', 'depth')} + data.append(lab) + if 'cam_pose' in lab: + camps[i] = np.linalg.inv(lab['cam_pose'].reshape(4, 4)) + cv[i] = True + if cv.any(): + view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', camps, cv, + ['T', 'row', 'column'], loc, convention='T_camera_from_world', + source_convention='T_world_from_camera') + motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) + points, pv = np.full((n, 2, 21, 3), np.nan, np.float32), np.zeros((n, 2, 21), bool) + object_ids = set() + for i, lab in enumerate(data): + if 'hand_pose_mano' in lab: + hands = lab['hand_pose_mano'].reshape(2, 62) + for side, row in enumerate(hands): + if row[0] not in (0, 1): + raise ValueError('unexpected H2O MANO presence flag') + if row[0] == 1: + motion[i, side] = np.r_[row[4:52], row[52:62], row[1:4]] + mv[i, side] = True + if 'hand_pose' in lab: + hands = lab['hand_pose'].reshape(2, 64) + for side, row in enumerate(hands): + if row[0] not in (0, 1): + raise ValueError('unexpected H2O keypoint presence flag') + if row[0] == 1: + points[i, side] = row[1:].reshape(21, 3) + pv[i, side] = True + for key in ('obj_pose', 'obj_pose_rt'): + if key in lab and lab[key][0] != 0: + object_ids.add(int(lab[key][0])) + if any('hand_pose_mano' in lab for lab in data): + if len(models) == 2: + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) + else: + view.absent('mano', 'Source parameters exist; --mano-dir must identify both model profiles', 'dependency_missing') + if any('hand_pose' in lab for lab in data): + view.tensor('keypoints_xyz', 'keypoints/xyz/v1', 'annotation/keypoints/xyz.pt', points, pv, + ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='m') + for oid in sorted(object_ids): + if oid not in OBJECTS: + raise ValueError(f'unknown H2O object class {oid}') + entity = OBJECTS[oid] + view.object(entity, loc, category_id=oid, source_object_id=oid) + poses, ov = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + pts, kv = np.full((n, 21, 3), np.nan, np.float32), np.zeros((n, 21), bool) + for i, lab in enumerate(data): + if 'obj_pose_rt' in lab and lab['obj_pose_rt'][0] == oid: + poses[i] = lab['obj_pose_rt'][1:].reshape(4, 4) + ov[i] = True + if 'obj_pose' in lab and lab['obj_pose'][0] == oid: + pts[i] = lab['obj_pose'][1:].reshape(21, 3) + kv[i] = True + if ov.any(): + view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', + poses, ov, ['T', 'row', 'column'], loc, convention='T_camera_from_object', unit='m') + if kv.any(): + view.tensor('points_' + entity, 'object_keypoints/camera/v1', + f'annotation/object/{entity}/keypoints/xyz.pt', pts, kv, + ['T', 'keypoint', 'coordinate'], loc, keypoint_schema='H2O_official_object21', + keypoint_names=['center'] + [f'corner_{i}' for i in range(8)] + [f'edge_midpoint_{i}' for i in range(12)], + source_order='official obj_point_order.jpg: center, 8 corners, 12 edge midpoints', unit='m') + if oid in assets: + directory, obj, aliases = assets[oid] + asset_loc = locator(asset_archive, f'object/{entity}/{obj.name}') + if aliases: + asset_loc['texture_aliases'] = aliases + mesh_asset(view, entity, directory, obj, asset_loc) + else: + view.absent('mesh_' + entity, 'Source object.zip unavailable', 'not_downloaded') + if any('depth' in rows[f] for f in ids): + width, height = view.meta['camera']['image_size'] + def depths(): + for f in ids: + item = rows[f].get('depth') + if item: + with Image.open(item[0]) as im: + yield np.asarray(im).astype(np.float32) / 1000.0 + else: + yield np.full((height, width), np.nan, np.float32) + view.raster('depth', depths(), None, loc | {'source_field': 'component_sources.depth', + 'definition': 'https://github.com/taeinkwon/h2oplayer/blob/main/utils.py', + 'conversion': 'registered millimetre camera-Z to metres; no viewer range clipping'}, + codec_threads=codec_threads) + else: + view.absent('depth', 'No source depth frames') + view.absent('segment', 'H2O provides no native segmentation; rendering deferred to v2.0') + view.absent('relations', 'No source contact/grasp annotation') + return view.finish() + + +def convert_archive(archive, args, out, splits, models, assets, asset_archive): + selected_views = set(args.views.split(',')) if args.views else None + subjects = {'subject' + s.strip() for s in args.subjects.split(',')} if args.subjects else None + current, rows, intrinsics, done = None, {}, {}, 0 + with tempfile.TemporaryDirectory(prefix='h2o-source-') as wd: + work = Path(wd) + def flush(): + nonlocal done + if not rows: + return + seq = '/'.join(current) + reports, pending = {}, {} + for cam, frames in sorted(rows.items()): + existing = out / 'data' / seq.replace('/', '_') / cam + if (existing / 'metainfo.json').is_file(): + old_frames = [json.loads(line) for line in (existing / 'camera/frames.jsonl').read_text().splitlines()] + if [f['source_frame_id'] for f in old_frames] != list(range(min(frames), max(frames) + 1)): + raise ValueError('existing view has different sampling; choose a new release-id') + for frame in old_frames: + incoming = frames.get(frame['source_frame_id'], {}) + previous = frame.get('component_sources', {}) + if set(previous) != set(incoming) or any(previous[k].get('sha256') != v[1].get('sha256') for k, v in incoming.items()): + raise ValueError('duplicate H2O view differs from the published source; choose a new release-id') + else: + pending[cam] = frames + if pending: + with sequence_dir(out, seq.replace('/', '_')) as target: + for cam, frames in pending.items(): + reports[cam] = convert_view(target / cam, args, seq, cam, frames, + intrinsics.get(cam), splits, models, assets, asset_archive) + build_record(out, seq.replace('/', '_'), reports) + for staged in list(work.iterdir()): + if staged.is_dir(): + shutil.rmtree(staged) + else: + staged.unlink() + done += 1 + print(f'{"Converted" if pending else "Verified existing"} {seq}', flush=True) + # Uncompressed CASA supports seeking over large frames; gzip is single-pass. + mode = 'r:' if archive.suffix == '.tar' else 'r|gz' + with tarfile.open(archive, mode) as tf: + for member in tf: + match = MEMBER.fullmatch(member.name) + if not member.isfile() or not match: + continue + subj, scene, seq, cam, tail = match.groups() + if subjects and subj not in subjects: + continue + key = (subj, scene, seq) + if key != current: + flush() + if args.limit and done >= args.limit: + break + current, rows, intrinsics = key, {}, {} + if selected_views and cam not in selected_views: + continue + frame = FRAME.fullmatch(tail) + if tail != 'cam_intrinsics.txt' and not frame: + continue + if frame and args.max_frames and int(frame[2]) >= args.max_frames: + continue + data = tf.extractfile(member).read() + dest = safe_member(work, member.name) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(data) + item = (dest, locator(archive, member.name, data)) + if tail == 'cam_intrinsics.txt': + intrinsics[cam] = item + else: + kind, f = frame[1], int(frame[2]) + row = rows.setdefault(cam, {}).setdefault(f, {}) + if kind in row: + raise ValueError('duplicate H2O frame') + row[kind] = item + else: + flush() + return done + + +def main(argv=None): + p = parser('H2O', __doc__) + p.set_defaults(release_id='shared-v1.0') + p.add_argument('--workers', type=int, choices=range(1, 5), default=1, + help='Independent subject archives in parallel, 1..4; benchmark before using >2') + p.add_argument('--codec-threads', type=int, choices=(1, 2, 4, 8, 10), default=4, + help='FFV1 slice threads per encode; default 4, use 10 for the current full run') + p.add_argument('--subjects') + p.add_argument('--include-casa', action='store_true') + p.add_argument('--archive', type=Path, help='Convert one explicit source archive') + args = p.parse_args(argv) + if args.include_casa and args.workers != 1: + p.error('CASA can share sequence IDs with subject archives; convert it sequentially in a separate release') + archives = [args.archive.expanduser()] if args.archive else sorted( + {a for root in roots(args.root) for a in root.glob('subject*_v1_1.tar.gz')}) + if args.subjects and not args.archive: + requested = {'subject' + s.strip() for s in args.subjects.split(',')} + archives = [arc for arc in archives if arc.name.split('_', 1)[0] in requested] + if args.include_casa: + casa = find_file(args.root, 'h2o_CASA.tar') + if casa: + archives.append(casa) + if not archives: + p.error('no H2O archives found') + out = release(args, 'H2O') + source_mapping = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/h2o-RAW_TO_SHARED.md', + Path(__file__).resolve().parents[1] / 'doc/RAW_TO_SHARED.md', + out / 'doc/RAW_TO_SHARED.md') if p.is_file()) + mapping = out / 'doc/RAW_TO_SHARED.md' + if mapping.exists() and mapping.read_bytes() != source_mapping.read_bytes(): + raise ValueError('RAW_TO_SHARED.md changed; choose a new release-id') + if not mapping.exists(): + shutil.copyfile(source_mapping, mapping) + torch.set_num_threads(1) + models, splits = mano_models(args.mano_dir), load_splits(args.root) + with tempfile.TemporaryDirectory(prefix='h2o-assets-') as wd: + assets, asset_archive = load_assets(args.root, Path(wd)) + def convert_one(archive): + return convert_archive(archive, args, out, splits, models, assets, asset_archive) + if args.workers == 1: + for archive in archives: + convert_one(archive) + else: + with ThreadPoolExecutor(max_workers=args.workers) as pool: + for archive, count in zip(archives, pool.map(convert_one, archives), strict=True): + print(f'Archive {archive.name}: {count} sequences', flush=True) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) + +# TODO(v2.0): 以下旧 MANO 网格和渲染分割代码仅保留备查;v1.0 不生成标注。 +# def load_mano_model(path: Path): +# """MPI MANO pkl → numpy 字典。shapedirs 在 pkl 内为 chumpy Select(对 (778,3,20) 基 +# 底 flat 选取前 10 个 shape 分量;idxs 已核实等价于 base[:,:,:10])。""" +# with open(path, "rb") as f: +# d = _ManoUnpickler(f, encoding="latin1").load() +# sd = d["shapedirs"] +# base = np.asarray(sd.a.x, np.float64) # (778, 3, 20) +# shapedirs = base.reshape(-1)[np.asarray(sd.idxs)].reshape(base.shape[0], 3, -1) +# jreg = d["J_regressor"] +# jreg = np.asarray(jreg.todense()) if hasattr(jreg, "todense") else np.asarray(jreg) +# return {"v_template": np.asarray(d["v_template"], np.float64), +# "shapedirs": shapedirs, +# "posedirs": np.asarray(d["posedirs"], np.float64), +# "weights": np.asarray(d["weights"], np.float64), +# "J_regressor": np.asarray(jreg, np.float64), +# "kintree": np.asarray(d["kintree_table"], np.int64), +# "faces": np.asarray(d["f"], np.int64)} +# +# +# def rodrigues(r): +# """axis-angle (N,3) → 旋转矩阵 (N,3,3)。公式 I + sinθ·K + (1−cosθ)·K²(已对 scipy 核验)。""" +# r = np.asarray(r, np.float64).reshape(-1, 3) +# th = np.linalg.norm(r, axis=1) +# R = np.zeros((len(r), 3, 3)) +# nz = th > 1e-12 +# R[~nz] = np.eye(3) +# k = r[nz] / th[nz, None] +# K = np.zeros((len(k), 3, 3)) +# K[:, 0, 1], K[:, 0, 2], K[:, 1, 2] = -k[:, 2], k[:, 1], -k[:, 0] +# K[:, 1, 0], K[:, 2, 0], K[:, 2, 1] = k[:, 2], -k[:, 1], k[:, 0] +# s, c = np.sin(th[nz])[:, None, None], np.cos(th[nz])[:, None, None] +# R[nz] = np.eye(3) + s * K + (1 - c) * (K @ K) +# return R +# +# +# def _mano_chain(model, betas, pose): +# """返回 (v_shaped, J, Rs, G):G 为 16 个关节的全局变换(平移列 = 关节位置)。""" +# v = model["v_template"] + np.einsum("nkc,c->nk", model["shapedirs"], betas) +# J = model["J_regressor"] @ v +# Rs = rodrigues(np.asarray(pose, np.float64).reshape(16, 3)) +# kt = model["kintree"] +# G = np.zeros((16, 4, 4)) +# for j in range(16): +# p = kt[0, j] if j else -1 +# loc = np.eye(4) +# loc[:3, :3] = Rs[j] +# loc[:3, 3] = J[j] - (J[p] if j else 0.0) +# G[j] = loc if not j else G[p] @ loc +# return v, J, Rs, G +# +# +# def mano_forward(model, betas, pose, transl): +# """MANO LBS 前向(经典蒙皮 M_j = G_j·G0_j⁻¹;对 hand_pose 21 关节实证 0.0 mm)。 +# pose: 48 axis-angle([0:3] 全局);返回相机系米顶点 (778,3)。""" +# v, J, Rs, G = _mano_chain(model, betas, pose) +# lrot = (Rs[1:] - np.eye(3)).ravel() +# v_posed = v + np.einsum("nkc,c->nk", model["posedirs"], lrot) +# kt = model["kintree"] +# G0 = np.zeros((16, 4, 4)) +# for j in range(16): +# p = kt[0, j] if j else -1 +# loc = np.eye(4) +# loc[:3, 3] = J[j] - (J[p] if j else 0.0) +# G0[j] = loc if not j else G0[p] @ loc +# M = np.einsum("nj,jab->nab", model["weights"], G @ np.linalg.inv(G0)) +# out = np.einsum("nab,nb->na", M[:, :3, :3], v_posed) + M[:, :3, 3] +# return out + np.asarray(transl, np.float64) +# +# +# def mano_chain_joints(model, betas, pose, transl): +# """16 个关节位置(相机系米)= 链平移列;自检用。""" +# _, _, _, G = _mano_chain(model, betas, pose) +# return G[:, :3, 3] + np.asarray(transl, np.float64) +# +# +# def rasterize(verts_cam, faces, labels, W, H, fx, fy, cx, cy): +# z = verts_cam[:, 2] +# P = faces +# ok = (z[P] > 0.02).all(1) # 任一顶点在相机后 → 丢弃该三角形 +# P, labels = P[ok], labels[ok] +# if len(P) == 0: +# return np.zeros((H, W), np.uint16), np.zeros(0, np.int64) +# x = verts_cam[:, 0] / z * fx + cx +# y = verts_cam[:, 1] / z * fy + cy +# xa = np.maximum(0, np.minimum(np.floor(x[P[:, 0]]), np.minimum( +# np.floor(x[P[:, 1]]), np.floor(x[P[:, 2]]))).astype(np.int64)) +# xb = np.minimum(W - 1, np.maximum(np.ceil(x[P[:, 0]]), np.maximum( +# np.ceil(x[P[:, 1]]), np.ceil(x[P[:, 2]]))).astype(np.int64)) +# ya = np.maximum(0, np.minimum(np.floor(y[P[:, 0]]), np.minimum( +# np.floor(y[P[:, 1]]), np.floor(y[P[:, 2]]))).astype(np.int64)) +# yb = np.minimum(H - 1, np.maximum(np.ceil(y[P[:, 0]]), np.maximum( +# np.ceil(y[P[:, 1]]), np.ceil(y[P[:, 2]]))).astype(np.int64)) +# xa, ya = np.minimum(xa, xb), np.minimum(ya, yb) # 完全出画的三角形 → 空 bbox +# wdt, hgt = xb - xa + 1, yb - ya + 1 +# cnt = wdt * hgt +# tot = int(cnt.sum()) +# tri = np.repeat(np.arange(len(P)), cnt) +# k = np.arange(tot) - (np.cumsum(cnt) - cnt)[tri] +# px = xa[tri] + k % wdt[tri] + 0.5 +# py = ya[tri] + k // wdt[tri] + 0.5 +# ax, ay = x[P[tri, 0]], y[P[tri, 0]] +# bx, by = x[P[tri, 1]], y[P[tri, 1]] +# cx_, cy_ = x[P[tri, 2]], y[P[tri, 2]] +# area = ((x[P[:, 1]] - x[P[:, 0]]) * (y[P[:, 2]] - y[P[:, 0]]) +# - (y[P[:, 1]] - y[P[:, 0]]) * (x[P[:, 2]] - x[P[:, 0]])) +# areat = area[tri] +# e0 = (bx - ax) * (py - ay) - (by - ay) * (px - ax) +# e1 = (cx_ - bx) * (py - by) - (cy_ - by) * (px - bx) +# e2 = (ax - cx_) * (py - cy_) - (ay - cy_) * (px - cx_) +# s = np.sign(areat) +# inside = (np.abs(areat) > 1e-9) & ((e0 * s >= 0) & (e1 * s >= 0) & (e2 * s >= 0)) +# px, py, tri = px[inside], py[inside], tri[inside] +# at = areat[inside] +# w0, w1, w2 = e1[inside] / at, e2[inside] / at, e0[inside] / at +# zz = w0 * z[P[tri, 0]] + w1 * z[P[tri, 1]] + w2 * z[P[tri, 2]] +# pix = py.astype(np.int64) * W + px.astype(np.int64) +# order = np.lexsort((zz, pix)) # 同像素按深度升序 → 首条即最近 +# pix, tri = pix[order], tri[order] +# first = np.unique(pix, return_index=True)[1] +# mask = np.zeros(H * W, np.uint16) +# win = tri[first] +# mask[pix[first]] = labels[win] + 1 # 临时标签 +1(0=背景) +# return mask.reshape(H, W), np.bincount(labels[win] + 1) +# +# +# # ============================================================================ +# # ffmpeg 写出与核验(与 convert_dexycb.py 同构) +# # ============================================================================ +# verts, faces_all, labels = [], [], [] +# for ti, (tid, kind) in enumerate(tracks): +# if kind == "hand_left" and b["mano"][0] > 0.5: +# verts.append(mano_forward(mano_models["left"], b["mano"][52:62], +# b["mano"][4:52], b["mano"][1:4])) +# faces_all.append(mano_models["left"]["faces"]) +# elif kind == "hand_right" and b["mano"][62] > 0.5: +# verts.append(mano_forward(mano_models["right"], b["mano"][114:124], +# b["mano"][66:114], b["mano"][63:66])) +# faces_all.append(mano_models["right"]["faces"]) +# elif isinstance(kind, tuple) and int(b["objp"][0]) == kind[1]: +# M = np.asarray(b["objrt"][1:17], np.float64).reshape(4, 4) +# V0, F0 = meshes[kind[1]] +# verts.append(V0 @ M[:3, :3].T + M[:3, 3]) +# faces_all.append(F0) +# else: +# continue +# labels.append(np.full(len(faces_all[-1]), ti)) +# if verts: +# V = np.concatenate(verts) +# offs = np.cumsum([0] + [len(v) for v in verts[:-1]]) +# F = np.concatenate([fa + o for fa, o in zip(faces_all, offs)]) +# mask, counts = rasterize(V, F, np.concatenate(labels), +# IMG_W, IMG_H, fx, fy, cx, cy) +# else: +# mask, counts = np.zeros((IMG_H, IMG_W), np.uint16), np.zeros(0, np.int64) +# lut = np.zeros(n_tracks + 1, np.uint16) +# for ti in range(n_tracks): +# present = ti + 1 < len(counts) and counts[ti + 1] > 0 +# if present: +# presence[tracks[ti][0]][f] = True +# if active_id[ti] is None: +# pid = next(i for i in range(1, 65535) if i not in used) +# used.add(pid) +# active_id[ti], seg_start[ti] = pid, f +# frame_maps[ti].append({"id": pid}) +# lut[ti + 1] = active_id[ti] +# elif active_id[ti] is not None: +# frame_maps[ti][-1]["frames"] = [seg_start[ti], f - 1] +# segments[ti].append([seg_start[ti], f - 1]) +# used.discard(active_id[ti]) +# active_id[ti] = None +# mw.write(lut[mask]) + + +# TODO(v2.0): 旧物体尺寸派生代码;v1.0 仅保留源物体关键点。 +# pts = np.asarray(b["objp"][1:64], np.float64).reshape(21, 3) +# half = np.abs((pts[1:9] - pts[0]) @ M[:3, :3]).max(0) +# obj_recs.append({ +# "track_id": f"o{classes.index(c)}", "frame": f, +# "mesh_ref": f"h2o/{OBJ_CLASSES[c]}.obj", +# "pose": {"quat": rotmat_to_quat_wxyz(M[:3, :3])[0].tolist(), +# "trans": M[:3, 3].tolist()}, +# "bbox_center3d": pts[0].tolist(), +# "bbox_size": (2 * half).tolist()}) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/convert_hoi4d_v1.0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/convert_hoi4d_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..9d5914d64ae72ee62564897743dfe5a41923e08d --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/convert_hoi4d_v1.0.py @@ -0,0 +1,595 @@ +#!/usr/bin/env python3 +"""HOI4D native observations and annotations → CONTRACT.md v1.0.""" +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from contextlib import ExitStack +from functools import lru_cache +import gzip +import io +import json +import os +from pathlib import Path +import pickle +import re +import shutil +import shlex +import posixpath +import subprocess +import tempfile +import tarfile +import threading +import zipfile + +# Each worker owns one Python thread; prevent native libraries spawning CPU pools. +for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + +import numpy as np +from PIL import Image +from scipy.spatial.transform import Rotation + +import torch + +from warehouse_v1_0 import (View, build_record, check_mesh, decode_args, find_file, json_write, locator, + mano_models, model_profile, parser, probe, release, run, safe_member, sequence_dir) + +CATEGORIES = { + 1: dict(cad="rigid/ToyCar", groups=[("main", [1], "Toy Car", 1)], + hands={2: "right"}, objmap={"Toycar": "main"}), + 2: dict(cad="rigid/Mug", groups=[("a", [1], "Mug", 2), ("b", [3], "Mug", 2)], + hands={2: "right"}, objmap={"Watercup": "a"}), + 3: dict(cad="articulated/Laptop", groups=[("main", [1, 3], "Laptop", 3)], + hands={2: "right"}, + objmap={"Laptopdisplay": "main", "Laptopkeyboard": "main"}), + 4: dict(cad="articulated/StorageFurniture", + groups=[("main", [1, 3, 4], "Storage Furniture", 4), + ("bottle", [5], "Bottle", 5)], + hands={2: "right"}, + objmap={"Lockerbody": "main", "Lockersldingdoor": "main", + "Lockerdrawer": "main", "Safebox": "main"}), + 5: dict(cad="rigid/Bottle", groups=[("main", [1], "Bottle", 5), + ("mug", [3], "Mug", 2)], + hands={2: "right"}, objmap={"bottleddrinks": "main"}), + 6: dict(cad="articulated/Safe", groups=[("main", [1, 3], "Safe", 6), + ("bottle", [4], "Bottle", 5)], + hands={2: "right"}, objmap={"Safebox": "main", "Safedoor": "main"}), + 7: dict(cad="rigid/Bowl", groups=[("main", [1], "Bowl", 7), + ("ball", [3], "Ball", None)], + hands={2: "right"}, objmap={"bowl": "main"}), + 8: dict(cad="articulated/Bucket", + groups=[("a", [1, 3], "Bucket", 8), ("b", [4, 5], "Bucket", 8)], + hands={2: "right", 6: "left"}, + objmap={"bucket": "a", "Buckethandle": "a"}), + 9: dict(cad="articulated/Scissors", groups=[("main", [1, 3], "Scissors", 9)], + hands={2: "right"}, + objmap={"scissors": "main", "scissors2": None}), # scissors2:场景道具,无掩码 + 11: dict(cad="articulated/Pliers", groups=[("main", [1, 3], "Pliers", 11)], + hands={2: "right"}, objmap={"Pliersleft": "main", "Pliersright": "main"}), + 12: dict(cad="rigid/Kettle", groups=[("main", [1], "Kettle", 12), + ("mug", [3], "Mug", 2)], + hands={2: "right"}, objmap={"kettle": "main"}), + 13: dict(cad="rigid/Knife", groups=[("main", [1], "Knife", 13), + ("apple", [3], "Apple", None)], + hands={2: "right"}, objmap={"knife": "main"}), + 14: dict(cad="articulated/TrashCan", + groups=[("main", [1, 3], "Trash Can", 14), ("bottle", [4], "Bottle", 5)], + hands={2: "right"}, objmap={"Dustbinbase": "main", "Dustbincover": "main"}), + 17: dict(cad="articulated/Lamp", groups=[("main", [1, 3, 4, 5], "Lamp", 17)], + hands={2: "right", 6: "left"}, + objmap={"Lampbase": "main", "Tablelampfirstjoint": "main", + "Tablelampsecondjoint": "main", "Thirdjointoftablelamp": "main"}), + 18: dict(cad="articulated/Stapler", + groups=[("main", [1, 3, 4], "Stapler", 18), ("paper", [5], "Paper", None)], + hands={2: "right", 6: "left"}, # 6=左手:官方 label.csv 缺列,实测修正 + objmap={"Staplerbase": "main", "Staplercover": "main"}), + 20: dict(cad="rigid/Chair", groups=[("main", [1], "Chair", 20)], + hands={2: "right", 3: "left"}, objmap={"chair": "main"}), +} + + +# Official HOI4D definitions/motion segmentation/label.csv; no spatial side inference. +REGION_NAMES = {1: {1: 'Toy Car', 2: 'Right Hand'}, 2: {1: 'Mug', 2: 'Right Hand', 3: 'Mug'}, 3: {1: 'Screen', 2: 'Right Hand', 3: 'Keyboard'}, 4: {1: 'Door', 2: 'Right Hand', 3: 'Body of the Cabinet', 4: 'Drawer', 5: 'Bottle'}, 5: {1: 'Bottle', 2: 'Right Hand', 3: 'Mug'}, 6: {1: 'Body of the Safe', 2: 'Right Hand', 3: 'Door', 4: 'Bottle'}, 7: {1: 'Bowl', 2: 'Right Hand', 3: 'Ball'}, 8: {1: 'Body of the Bucket', 2: 'Right Hand', 3: 'Handle', 4: 'Body of the Bucket', 5: 'Handle', 6: 'Left Hand'}, 9: {1: 'Left Part of the Scissors', 2: 'Right Hand', 3: 'Right Part of the Scissors'}, 11: {1: 'Left Part of the Pliers', 2: 'Right Hand', 3: 'Right Part of the Pliers'}, 12: {1: 'Kettle', 2: 'Right Hand', 3: 'Mug'}, 13: {1: 'Knife', 2: 'Right Hand', 3: 'Apple'}, 14: {1: 'Body of the Trash Can', 2: 'Right Hand', 3: 'Lid', 4: 'Bottle'}, 17: {1: 'Base', 2: 'Right Hand', 3: 'Tube', 4: 'Top Link', 5: 'Bottom Link', 6: 'Left Hand'}, 18: {1: 'Base', 2: 'Right Hand', 3: 'Slot', 4: 'Lid', 5: 'Paper'}, 20: {1: 'Chair', 2: 'Right Hand', 3: 'Left Hand'}} + + +class SplitFiles(io.RawIOBase): + """Read concatenated source gzip parts without concatenating 119 GB on disk.""" + def __init__(self, paths): + self.paths = iter(paths) + self.current = None + + def readable(self): + return True + + def readinto(self, buffer): + while True: + if self.current is None: + path = next(self.paths, None) + if path is None: + return 0 + self.current = path.open('rb') + n = self.current.readinto(buffer) + if n: + return n + self.current.close() + self.current = None + + def close(self): + if self.current is not None: + self.current.close() + super().close() + + +def extract_depths(root, sequences, work): + directory = find_file(root, 'DEPTH') + if directory is None: + return {}, [] + parts = sorted(directory.glob('HOI4D_depth_video.tar.gz*'), key=lambda p: int(p.name.split('.gz')[1] or 0)) + if not parts: + return {}, [] + wanted = {f'HOI4D_depth_video/{seq}/align_depth/depth_video.avi': seq for seq in sequences} + found = {} + with SplitFiles(parts) as joined, io.BufferedReader(joined) as inp, gzip.GzipFile(fileobj=inp) as gz: + with tarfile.open(fileobj=gz, mode='r|') as tf: + for member in tf: + if member.isfile() and member.name in wanted: + seq = wanted[member.name] + dest = work / (seq.replace('/', '_') + '.avi') + with tf.extractfile(member) as src, dest.open('wb') as dst: + shutil.copyfileobj(src, dst) + found[seq] = (dest, {'files': [str(p.resolve()) for p in parts], 'member': member.name}) + if len(found) == len(wanted): + break + return found, parts + + +def palette_mask(data): + with Image.open(io.BytesIO(data)) as im: + arr = np.asarray(im) + if arr.ndim == 2: + return arr.astype(np.uint16) + if arr.shape[-1] != 3: + raise ValueError('unsupported HOI4D mask representation') + # VOC's 256-color palette interleaves eight label bits into the high RGB bits. + # Invert it directly instead of sorting every pixel with np.unique. + if np.any(arr & np.array([31, 31, 63], dtype=np.uint8)): + raise ValueError('source mask has colors outside official VOC palette') + mask = np.zeros(arr.shape[:2], dtype=np.uint16) + for bit in range(8): + mask |= ((arr[..., bit % 3] >> (7 - bit // 3)) & 1).astype(np.uint16) << bit + return mask + + +# Four workers each reuse annotation and hand indices instead of rebuilding the ZIP directory. +@lru_cache(maxsize=8) +def index_frames(z): + index = {} + for name in z.namelist(): + parent, _, filename = name.rpartition('/') + stem, dot, suffix = filename.rpartition('.') + if not dot or not stem.isdigit() or suffix not in ('png', 'json', 'pickle'): + continue + entries = index.setdefault((parent + '/', '.' + suffix), {}) + f = int(stem) + if f in entries: + raise ValueError(f'duplicate frame number under {parent}') + entries[f] = name + return index + + +def frame_members(z, prefix, suffix): + return index_frames(z).get((prefix, suffix), {}) + + +def convert_sequence(seq, args, target, rgbz, annz, hpz, calz, cadz, paths, models, depth): + # ponytail: cache only one sequence's encoded annotation bytes; no decoded masks or CAD cache. + @lru_cache(maxsize=None) + def read_annotation(archive, name): + return archive.read(name) + + category = int(re.search(r'/C(\d+)/', seq)[1]) + definition = CATEGORIES.get(category) + if definition is None: + raise ValueError(f'category mapping unavailable: {category}') + prefix = f'HOI4D_annotations/{seq}' + mask_members = frame_members(annz, prefix + '/2Dseg/mask/', '.png') + shifted = frame_members(annz, prefix + '/2Dseg/shift_mask/', '.png') + if not mask_members: + mask_members = shifted + pose_members = frame_members(annz, prefix + '/objpose/', '.json') + hand_members = {side: frame_members(hpz, f'Hand_pose/handpose_{side}_hand/{seq}/', '.pickle') + for side in ('left', 'right')} if hpz else {'left': {}, 'right': {}} + with tempfile.TemporaryDirectory(prefix='hoi4d-source-') as wd: + work = Path(wd) + member = f'HOI4D_release/{seq}/align_rgb/image.mp4' + video = work / 'rgb.mp4' + with rgbz.open(member) as src, video.open('wb') as dst: + shutil.copyfileobj(src, dst) + info = probe(video) + if 'nb_frames' not in info: + info['nb_frames'] = json.loads(run(['ffprobe', '-v', 'error', '-count_frames', '-select_streams', 'v:0', + '-show_entries', 'stream=nb_read_frames', '-of', 'json', str(video)], stdout=subprocess.PIPE).stdout)['streams'][0]['nb_read_frames'] + n = int(info['nb_frames']) + if args.max_frames: + n = min(n, args.max_frames) + if shifted and mask_members != shifted and any(f not in mask_members and f in shifted for f in range(n)): + raise ValueError('shift_mask has frames absent from mask; correspondence unverified') + frames = [] + for f in range(n): + sources = {} + if f in mask_members: + sources['segment'] = locator(paths['annotations'], mask_members[f], read_annotation(annz, mask_members[f])) + if f in pose_members: + sources['object'] = locator(paths['annotations'], pose_members[f], read_annotation(annz, pose_members[f])) + for side in ('left', 'right'): + if f in hand_members[side]: + sources['hand_' + side] = locator(paths['hand'], hand_members[side][f], read_annotation(hpz, hand_members[side][f])) + frames.append(dict(source_frame_id=f, source_locator=locator(paths['release'], member, frame=f), + component_sources=sources, annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None) for k in sources})) + view = View(target, 'HOI4D', args.release_id, seq.replace('/', '_'), 'ego', frames) + view.valid_rules = { + 'mano': 'Matched side pickle contains poseCoeff, beta, trans and corresponding model available; zero angles are not missing', + 'keypoints': 'Matched side pickle contains kps2D; independently provided source points, no visibility gate', + 'pose': 'Matched source object record contains rotation and center; record identity retained', + 'dimensions': 'Matched source object record contains dimensions; size/mesh relation remains source_unspecified', + 'segment': 'Source mask or shift_mask present with verified palette codes and entity/part mapping', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'ego' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'source_sequence': seq} + view.rgb([], locator(paths['release'], member), video=video, count=n) + intr_name = f'camera_params/{seq.split("/")[0]}/intrin.npy' + if calz and intr_name in calz.namelist(): + view.camera(np.load(io.BytesIO(calz.read(intr_name))), locator(paths['camera'], intr_name)) + extr_name = prefix + '/3Dseg/output.log' + if extr_name in annz.NameToInfo: + lines = [line for line in annz.read(extr_name).decode().splitlines() if line.strip()] + if len(lines) % 5: + raise ValueError('invalid Open3D camera trajectory') + extr, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + for i in range(0, len(lines), 5): + idx = int(lines[i].split()[0]) + if idx < n: + if valid[idx]: + raise ValueError('duplicate trajectory index') + extr[idx] = np.linalg.inv(np.loadtxt(io.StringIO('\n'.join(lines[i + 1:i + 5])))) + valid[idx] = True + view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', extr, valid, + ['T', 'row', 'column'], locator(paths['annotations'], extr_name), + convention='T_camera_from_world', source_convention='Open3D LOG camera-to-world; inverted') + loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} + motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) + points, pv = np.full((n, 2, 21, 2), np.nan, np.float32), np.zeros((n, 2, 21), bool) + for slot, side in enumerate(('left', 'right')): + for f, name in hand_members[side].items(): + if f >= n: + continue + data = pickle.loads(read_annotation(hpz, name), encoding='latin1') + if all(k in data for k in ('poseCoeff', 'beta', 'trans')): + motion[f, slot] = np.r_[np.asarray(data['poseCoeff']).reshape(48), + np.asarray(data['beta']).reshape(10), np.asarray(data['trans']).reshape(3)] + mv[f, slot] = True # Zero angles are a valid pose, not a missing sentinel. + if 'kps2D' in data: + points[f, slot] = np.asarray(data['kps2D']).reshape(21, 2) + pv[f, slot] = True + if mv.any(): + if all(side in models for slot, side in enumerate(('left', 'right')) if mv[:, slot].any()): + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) + else: + view.absent('mano', 'Source MANO exists; provide --mano-dir to fix model identity', 'dependency_missing') + if pv.any(): + view.tensor('keypoints_uv', 'keypoints/uv/v1', 'annotation/keypoints/uv.pt', points, pv, + ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='pixel', + source_method='Upstream fitted MANO projection already present in kps2D') + objects = {} + groups = {key: (vals, name, cls) for key, vals, name, cls in definition['groups']} + def ensure_object(key, source_loc, category_id=None, frame=None, source_id=None): + if key not in objects: + view.object(key, source_loc, scope='frame' if frame is not None else 'sequence', + scope_id=f'{seq}:{frame}' if frame is not None else None, + category_id=category_id, source_object_id=source_id) + objects[key] = {} + mappings = [] + mask_valid = [f in mask_members for f in range(n)] + if any(mask_valid): + width, height = view.meta['camera']['image_size'] + def masks(): + for f in range(n): + labels = [] + if f in mask_members: + mask = palette_mask(read_annotation(annz, mask_members[f])) + for value in np.unique(mask): + value = int(value) + if value in (0, 255): + if value == 255: + raise ValueError('HOI4D 255 region semantics unverified') + continue + if REGION_NAMES[category].get(value) in ('Left Hand', 'Right Hand'): + entity, part, cls = 'hand_' + REGION_NAMES[category][value].split()[0].lower(), None, 'hand' + else: + group = next((k for k, (vals, _, _) in groups.items() if value in vals), None) + entity = group or f'unknown_region_{value}' + cls = groups[group][2] if group else None + part = f'region_{value}' if group and len(groups[group][0]) > 1 else None + ensure_object(entity, frames[f]['component_sources']['segment'], cls) + if part: + objects[entity].setdefault('parts', {})[part] = {'part_id': part, 'parent_id': None, + 'has_model': False, 'mesh_ref': None, 'source_region_code': value, 'name': REGION_NAMES[category].get(value)} + labels.append(dict(mask_value=value, category_id=cls, entity_id=entity, + part_id=part, source_instance_id=value, + source_attributes={'region_name': REGION_NAMES[category].get(value)})) + else: + mask = np.zeros((height, width), np.uint16) + mappings.append(dict(frame_index=f, labels=labels)) + yield mask + view.raster('segment', masks(), mask_valid, loc, mappings) + view.meta['components']['segment']['coverage'] = {'kind': 'unknown'} + if any(label['part_id'] for row in mappings for label in row['labels']): + view.meta['components']['segment']['segmentation_type'] = 'part' + else: + view.absent('segment', 'No native segmentation for this source sequence') + records = {} + for f, name in pose_members.items(): + if f >= n: + continue + data = json.loads(read_annotation(annz, name)) + # isEffective is not used to erase existing numerical annotations. + source_records = data.get('dataList', data.get('objects')) + if source_records is None: + raise ValueError('unrecognized source object annotation structure') + if category == 2 and source_records and (len(source_records) != 1 or + source_records[0].get('id') != 1 or source_records[0].get('label') != 'Watercup'): + raise ValueError('C2 native pose differs from the verified one-object target; cannot map to mask region 1') + label_counts = Counter(record['label'] for record in source_records) + per_frame = set() + for record_index, record in enumerate(source_records): + label = record['label'] + group = definition['objmap'].get(label) + # Pinned official ObjTracking reads dataList[0] with segmentation label 1. + source_primary = category == 2 and record_index == 0 and record.get('id') == 1 and group == 'a' + ambiguous = group is not None and sum(g[2] == groups[group][2] for g in groups.values()) > 1 and not source_primary + ambiguous = ambiguous or (label_counts[label] > 1 and not source_primary) or group is None + entity = f'pose_frame_{f}_{record_index}' if ambiguous else group + ensure_object(entity, locator(paths['annotations'], name, record=record_index), + groups[group][2] if group else None, frame=f if ambiguous else None, source_id=record.get('id')) + if ambiguous: + view.build['unresolved'].append({'component': entity, 'status': 'source_semantics_unverified', + 'reason': 'Source pose retained with frame identity; no guessed association to same-class mask instances'}) + label_key = (entity, label) + if label_key in per_frame: + raise ValueError(f'ambiguous repeated object label {label}; source identity must be resolved') + per_frame.add(label_key) + records.setdefault(label_key, {})[f] = (record, locator(paths['annotations'], name, record=record.get('id'))) + if category == 2 and any(entity == 'a' for entity, _ in records): + view.build['validation'].append({'component': 'C2_source_pose_mask_identity', + 'rule': 'Official ObjTracking process_data.py reads dataList[0] with semantic mask label 1', + 'source_revision': 'afa7bf37b02b7e33cf245acd08b98c207ccc175c', + 'source_pose_id': 1, 'mask_value': 1, 'matched_frames': sum(len(by_frame) for (entity, _), by_frame in records.items() if entity == 'a')}) + for (entity, label), by_frame in records.items(): + part_labels = [k[1] for k in records if k[0] == entity] + articulated = definition['cad'].startswith('articulated/') and entity == definition['groups'][0][0] + part = 'pose_' + re.sub(r'[^a-zA-Z0-9_]', '_', label) if articulated or len(part_labels) > 1 else None + base = f'annotation/object/{entity}' + if part: + base += '/parts/' + part + objects[entity].setdefault('parts', {})[part] = dict(part_id=part, parent_id=None, + has_model=False, mesh_ref=None, source_label=label) + poses, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + dimensions = np.full((n, 3), np.nan, np.float32) + dv = np.zeros(n, bool) + for f, (record, _) in by_frame.items(): + if all(k in record for k in ('rotation', 'center')): + poses[f] = np.eye(4) + poses[f, :3, :3] = Rotation.from_euler('XYZ', [record['rotation'][k] for k in ('x', 'y', 'z')]).as_matrix() + poses[f, :3, 3] = [record['center'][k] for k in ('x', 'y', 'z')] + valid[f] = True + if 'dimensions' in record: + dimensions[f] = [record['dimensions'][k] for k in ('length', 'width', 'height')] + dv[f] = True + key = entity + ('_' + part if part else '') + view.tensor('pose_' + key, 'transform/se3/v1' if part else 'object/rigid/v1', base + '/pose.pt', poses, valid, + ['T', 'row', 'column'], loc, convention='T_camera_from_part' if part else 'T_camera_from_object', + unit='m', source_label=label, source_euler_order='XYZ', + definition='https://github.com/hoi4d/ObjTracking/blob/main/process_data.py') + if dv.any(): + view.tensor('dimensions_' + key, 'object/dimensions/v1', base + '/dimensions.pt', dimensions, dv, + ['T', 'dimension'], loc, dimensions_semantics='source_unspecified', unit='m', scale_applied_to_mesh=False) + if cadz: + primary = definition['groups'][0][0] + if category != 2 and sum(g[2] == category for g in groups.values()) > 1: + primary = 'source_cad_instance' + instance = int(re.search(r'/N(\d+)/', seq)[1]) + mesh_prefix = f'HOI4D_CAD_Model_for_release/{definition["cad"]}/{instance:03d}' + candidates = [name for name in cadz.namelist() if not name.endswith('/') and + (name == mesh_prefix + '.obj' or name.startswith(mesh_prefix + '/'))] + if candidates: + # Retain OBJ material/texture dependencies beside their original names. + queue = list(candidates) + for name in queue: + if Path(name).suffix.lower() not in ('.obj', '.mtl'): + continue + for line in cadz.read(name).decode().splitlines(): + fields = shlex.split(line, comments=True) + if not fields: + continue + refs = fields[1:] if fields[0] == 'mtllib' else ([fields[-1]] if + fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal') else []) + for ref in refs: + dependency = posixpath.normpath(posixpath.join(posixpath.dirname(name), ref)) + if dependency not in cadz.NameToInfo: + raise ValueError(f'missing CAD dependency: {dependency}') + if dependency not in candidates: + candidates.append(dependency) + queue.append(dependency) + ensure_object(primary, locator(paths['cad'], mesh_prefix), category) + asset_dir = view.path / f'annotation/object/{primary}/assets' + asset_refs = [] + for name in candidates: + relative = posixpath.relpath(name, mesh_prefix if definition['cad'].startswith('articulated/') else posixpath.dirname(mesh_prefix)) + dest = safe_member(asset_dir, relative) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(cadz.read(name)) + ref = dest.relative_to(view.path).as_posix() + if dest.suffix.lower() == '.obj': + asset_key = re.sub(r'[^a-zA-Z0-9_]', '_', relative) + view.component('mesh_' + primary + '_' + asset_key, 'mesh/obj/v1', ref, ['vertex'], + locator(paths['cad'], name), unit='m', valid=True, + scale_applied_to_mesh=False, dimensions_semantics='source_unspecified') + asset_refs.append(ref) + if definition['cad'].startswith('articulated/'): + part_id = 'asset_' + asset_key + objects[primary].setdefault('parts', {})[part_id] = dict(part_id=part_id, + parent_id=None, has_model=True, mesh_ref=ref, source_asset=relative, + note='Source asset; correspondence to motion part labels remains unverified') + for asset_ref in asset_refs: + mesh_check = check_mesh(view.path / asset_ref, asset_dir) + view.build['validation'].append({'component': asset_ref, **mesh_check, + 'unit_basis': 'official ObjTracking loads source canonical CAD without scaling in metre camera coordinates', + 'geometric_acceptance': 'physical dimensions-to-mesh relation remains source_unspecified'}) + metadata_path = view.path / f'annotation/object/{primary}/metainfo.json' + metadata = json.loads(metadata_path.read_text()) + metadata.update(has_model=bool(asset_refs), asset_refs=asset_refs) + if definition['cad'].startswith('rigid/') and len(asset_refs) == 1: + metadata['mesh_ref'] = asset_refs[0] + json_write(metadata_path, metadata) + if definition['cad'].startswith('articulated/'): + view.build['unresolved'].append({'component': 'object_part_asset_association', + 'status': 'source_semantics_unverified', + 'reason': 'All source assets and motion labels retained, but no guessed correspondence or joint_state'}) + for entity, info in objects.items(): + if 'parts' in info: + ref = f'annotation/object/{entity}/articulation.json' + json_write(view.path / ref, {'parts': list(info['parts'].values()), 'joints': [], + 'hierarchy_semantics': 'semantic_containment', + 'note': 'Unassociated source region, motion and asset nodes; original CAD trees retained in assets'}) + view.component('articulation_' + entity, 'object/articulated/v1', ref, [], loc) + meta_path = view.path / f'annotation/object/{entity}/metainfo.json' + metadata = json.loads(meta_path.read_text()) + metadata['articulation_ref'] = ref + json_write(meta_path, metadata) + if depth is not None: + dpath, dloc = depth + dmeta = probe(dpath) + if [dmeta['width'], dmeta['height']] != view.meta['camera']['image_size']: + raise ValueError('HOI4D depth grid differs from RGB') + if dmeta['pix_fmt'] != 'gray16le': + raise ValueError('unexpected HOI4D depth pixel format') + width, height = view.meta['camera']['image_size'] + raw = work / 'depth.raw' + limits = ['-frames:v', str(n)] if args.max_frames else [] + run(decode_args(dpath, 'gray16le') + limits + ['-y', str(raw)]) + if raw.stat().st_size != n * width * height * 2: + raise ValueError('depth/RGB frame count or grid mismatch') + def depths(): + with raw.open('rb') as inp: + for _ in range(n): + yield np.frombuffer(inp.read(width * height * 2), ' best_iou + 0.1 and i > 0.15: +# best, best_iou = s[0], i +# if best != gk: +# gk, iou_fixups = best, iou_fixups + 1 diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/convert_visor_v1.0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/convert_visor_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..8f0595bf5e89ae00c959472ff197dfda2d7a6ea6 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/convert_visor_v1.0.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +"""VISOR source polygons and contact → CONTRACT.md v1.0, without rasterization or side inference.""" +from collections import Counter +import hashlib +import json +import re +import shutil +import tempfile +from pathlib import Path +import zipfile + +import numpy as np +import torch + +from warehouse_v1_0 import (View, build_record, find_file, jsonl_write, locator, parser, + release, roots, sequence_dir, source) + +FRAME = re.compile(r'frame_(\d+)') +HAND = {300: 'left', 301: 'right'} +GLOVE = {303: 'left', 304: 'right'} +STATES = {'hand-not-in-contact': 'negative', 'glove-not-in-contact': 'negative', + 'none-of-the-above': 'target_unannotated', 'inconclusive': 'unknown'} + + +def hand_side(ann): + if ann['class_id'] in HAND: + return HAND[ann['class_id']] + if ann['class_id'] not in (60, 303, 304): + return None + raw = ann.get('on_which_hand') + raw = raw if isinstance(raw, list) else [raw] + sides = set() + for item in raw: + if item == 'left hand': + sides.add('left') + if item in ('right hand', 'rigth hand'): + sides.add('right') + if len(sides) == 1: + return next(iter(sides)) + if not sides and ann['class_id'] in GLOVE: + return GLOVE[ann['class_id']] + return None + + +def convert_video(video, split, annotation, ann_loc, rgb_zip, rgb_loc, mapping, args, target): + indexed = sorted(enumerate(annotation['video_annotations']), key=lambda row: int(FRAME.search(row[1]['image']['name'])[1])) + if args.max_frames: + indexed = indexed[:args.max_frames] + if len({row['image']['name'] for _, row in indexed}) != len(indexed): + raise ValueError('duplicate VISOR frame') + keys = lambda row, ann: (row['image']['subsequence'], ann['class_id'], ann['name']) + collisions = set() + for _, row in indexed: + collisions.update(key for key, number in Counter(keys(row, a) for a in row['annotations']).items() if number > 1) + frames, paths = [], [] + with tempfile.TemporaryDirectory(prefix='visor-rgb-') as wd, zipfile.ZipFile(rgb_zip) as z: + work = Path(wd) + for original_index, row in indexed: + name = row['image']['name'] + data = z.read(name) + path = work / Path(name).name + path.write_bytes(data) + paths.append(path) + loc = rgb_loc | {'nested_member': name, 'sha256': hashlib.sha256(data).hexdigest()} + frames.append(dict(source_frame_id=int(FRAME.search(name)[1]), source_locator=loc, + source_image=row['image'], original_frame_name=mapping.get(name), + annotation_matches={'segment': dict(source_frame_id=name, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None, + source_locator=ann_loc | {'record': f'video_annotations[{original_index}]'})})) + view = View(target, 'EPIC-KITCHENS-VISOR', args.release_id, video, 'ego', frames, sampling='sparse', split=split) + view.valid_rules = { + 'segment': 'Selected sparse annotation frame present; all source polygons finite with at least three vertices and entity mapping valid', + 'relations': 'At least one source in_contact_object value present; positive targets resolve in the same frame; unknown is an explicit usable status', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta.update(view_type='ego', split_scheme='VISOR_GroundTruth_SparseAnnotations', split_source_locator=ann_loc) + view.meta['sampling']['selection'] = {'representation': 'official sparse annotations', 'max_frames': args.max_frames} + view.rgb(paths, rgb_loc) + entities = {} + polygons, mappings, relations, relation_valid = [], [], [], [] + for f, (original_index, row) in enumerate(indexed): + frame_loc = ann_loc | {'record': f'video_annotations[{original_index}]'} + id_map, labels, polys = {}, [], [] + for code, ann in enumerate(row['annotations'], 1): + if code >= 65535: + raise ValueError('too many source instances') + sid = ann['id'] + if sid in id_map: + raise ValueError('duplicate source instance ID within a frame') + side = hand_side(ann) + if side is not None: + entity = 'hand_' + side + else: + key = keys(row, ann) + identity = key + (sid, row['image']['name']) if key in collisions else key + entity = 'object_' + hashlib.sha256(json.dumps(identity).encode()).hexdigest()[:20] + if entity not in entities: + scope = 'frame' if key in collisions else 'subsequence' + scope_id = f'{video}:{row["image"]["name"]}' if scope == 'frame' else f'{video}:{key[0]}' + view.object(entity, frame_loc | {'source_instance_id': sid}, scope, scope_id, + category_id=ann['class_id'], name=ann['name'], + association_basis='source_frame_instance' if scope == 'frame' else 'official_subsequence_entity_name') + entities[entity] = True + id_map[sid] = entity + for polygon in ann.get('segments', []): + p = np.asarray(polygon) + if p.ndim != 2 or p.shape[1] != 2 or len(p) < 3 or not np.isfinite(p).all(): + raise ValueError(f'invalid source polygon {sid}') + polys.append(dict(mask_value=code, polygons=ann.get('segments', []))) + labels.append(dict(mask_value=code, category_id=ann['class_id'], entity_id=entity, + part_id=None, source_instance_id=sid, + source_attributes={k: v for k, v in ann.items() if k != 'segments'})) + rr = [] + provided = False + for ann in row['annotations']: + raw = ann.get('in_contact_object') + values = raw if isinstance(raw, list) else [raw] + for value in values: + if value is None: + continue + provided = True + status = STATES.get(value) + obj = None + if status is None: + if value not in id_map: + raise ValueError(f'unresolved source contact target {value} in {video} frame {f}') + status, obj = 'positive', id_map[value] + rr.append(dict(relation_type='contact', subject_id=id_map[ann['id']], object_id=obj, + status=status, source_value=value, source_locator=frame_loc | {'source_instance_id': ann['id']}, + provenance=source('Resolve source contact ID against instances in this frame'))) + polygons.append(dict(frame_index=f, instances=polys)) + mappings.append(dict(frame_index=f, labels=labels)) + relations.append(dict(frame_index=f, relations=rr)) + relation_valid.append(provided) + jsonl_write(view.path / 'annotation/segment/polygons.jsonl', polygons) + jsonl_write(view.path / 'annotation/segment/instances.jsonl', mappings) + torch.save(torch.ones(len(frames), dtype=torch.bool, device='cpu'), view.path / 'annotation/segment/mask_valid.pt') + view.component('segment', 'segment/instance_polygons/v1', 'annotation/segment/polygons.jsonl', ['T'], ann_loc, + valid_ref='annotation/segment/mask_valid.pt', valid_axes=['T'], segmentation_type='instance', + mapping_ref='annotation/segment/instances.jsonl', coverage={'kind': 'unknown', 'exhaustive_ref': 'annotation/segment/instances.jsonl'}) + view.relations(relations, relation_valid, ann_loc) + for component in ('depth', 'mano', 'keypoints_uv', 'keypoints_xyz', 'intrinsic', 'extrinsic'): + view.absent(component, 'Not provided by VISOR sparse source annotations') + return view.finish() + + +def main(argv=None): + p = parser('EPIC-KITCHENS-VISOR', __doc__) + p.add_argument('--videos', help='Comma-separated video names') + p.add_argument('--splits', default='train,val') + args = p.parse_args(argv) + wanted = set(args.videos.split(',')) if args.videos else None + splits = set(args.splits.split(',')) + if not splits <= {'train', 'val'}: + p.error('only annotated train/val splits are available') + out = release(args, 'EPIC-KITCHENS-VISOR') + archive = find_file(args.root, 'EPIC-KITCHENS VISOR.zip') + with tempfile.TemporaryDirectory(prefix='visor-source-') as wd: + work = Path(wd) + if archive: + with zipfile.ZipFile(archive) as z: + suffix = 'GroundTruth-SparseAnnotations/annotations/' + members = [n for n in z.namelist() if suffix in n and n.endswith('.json')] + prefix = members[0].split(suffix)[0] + fm = json.loads(z.read(prefix + 'frame_mapping.json')) + done = 0 + for member in sorted(members): + split, filename = member.split(suffix)[1].split('/') + video = Path(filename).stem + if split not in splits or wanted and video not in wanted: + continue + data = z.read(member) + rgb_member = prefix + f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' + rgb_zip = work / (video + '.zip') + with z.open(rgb_member) as inp, rgb_zip.open('wb') as dest: + shutil.copyfileobj(inp, dest) + with sequence_dir(out, video) as dest: + report = convert_video(video, split, json.loads(data), locator(archive, member, data), + rgb_zip, locator(archive, rgb_member), fm.get(video, {}), args, dest / 'ego') + build_record(out, video, {'ego': report}) + rgb_zip.unlink() + done += 1 + print(f'Converted {video}', flush=True) + if args.limit and done >= args.limit: + break + else: + root = next((r for r in roots(args.root) if (r / 'GroundTruth-SparseAnnotations').is_dir()), None) + if root is None: + p.error('VISOR outer ZIP or extracted source directory not found') + fm = json.loads((root / 'frame_mapping.json').read_text()) if (root / 'frame_mapping.json').exists() else {} + done = 0 + for split in sorted(splits): + for ann in sorted((root / 'GroundTruth-SparseAnnotations/annotations' / split).glob('*.json')): + video = ann.stem + if wanted and video not in wanted: + continue + rgb = root / f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' + with sequence_dir(out, video) as dest: + report = convert_video(video, split, json.loads(ann.read_text()), locator(ann), rgb, + locator(rgb), fm.get(video, {}), args, dest / 'ego') + build_record(out, video, {'ego': report}) + done += 1 + if args.limit and done >= args.limit: + return 0 + if not done: + p.error('no matching annotated videos found') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) + +# TODO(v2.0): 旧距离猜侧和单层掩码生成仅注释保留;v1.0 不执行。 +# if side is None and len(frame_hands) == 1: +# # 空间门槛:脱下放在远处的手套不并入(实测双峰 0..25px / ≥44px) +# hb = frame_hands[0][1] +# gb = _bbox_of(polys) +# if hb and gb and _bbox_dist(gb, hb) <= GLOVE60_MERGE_BBOX_DIST: +# side = frame_hands[0][0] +# stats["glove60_merged_into_sole_hand"] += 1 +# if side is None: +# stats["dropped_glove60_unresolved"] += 1 +# id_disp[mid] = ("dropped", "glove60") +# continue +# def rasterize_and_encode(vdir, frames, frame_draw, zip_path, n, stats): +# """流式读 zip 内 jpg + 光栅化多边形 → rgb.mkv / mask.mkv;返回 (w, h)。""" +# from PIL import Image, ImageDraw +# +# with zipfile.ZipFile(zip_path) as zf: +# member_of = {} +# for nm in zf.namelist(): +# member_of[os.path.basename(nm)] = nm +# names = [im["name"] for im in frames] +# missing = [nm for nm in names if nm not in member_of] +# if missing: +# raise RuntimeError(f"{len(missing)} annotated frames missing in zip, " +# f"e.g. {missing[:3]}") +# stats["zip_extra_members"] = len(member_of) - len(names) +# +# # 首帧定分辨率(官方 1920×1080,实测每帧校验) +# img0 = Image.open(io.BytesIO(zf.read(member_of[names[0]]))).convert("RGB") +# w, h = img0.size +# +# bin_img = Image.new("L", (w, h), 0) +# bin_draw = ImageDraw.Draw(bin_img) +# canvas = np.zeros((h, w), np.uint16) +# with VideoPipe(vdir / "mask.mkv", w, h, FPS, "mask") as mw, \ +# VideoPipe(vdir / "rgb.mkv", w, h, FPS, "rgb") as rw: +# for f in range(n): +# canvas[:] = 0 +# for pid, polys in frame_draw[f]: +# bin_draw.rectangle((0, 0, w, h), fill=0) +# for poly in polys: +# bin_draw.polygon([(float(x), float(y)) for x, y in poly], fill=255) +# arr = np.asarray(bin_img) +# canvas[arr > 0] = pid # 后画覆盖先画:物体→手(modal) +# mw.write(canvas) +# img = img0 if f == 0 else Image.open( +# io.BytesIO(zf.read(member_of[names[f]]))).convert("RGB") +# if img.size != (w, h): +# raise RuntimeError(f"frame {names[f]}: size {img.size} != {(w, h)}") +# rw.write(np.asarray(img)) +# n_mask, n_rgb = mw.n, rw.n +# if (n_rgb, n_mask) != (n, n): +# raise RuntimeError(f"wrote rgb={n_rgb} mask={n_mask} != {n}") +# got = (count_frames(vdir / "rgb.mkv"), count_frames(vdir / "mask.mkv")) +# if got != (n, n): +# raise RuntimeError(f"encoded rgb={got[0]} mask={got[1]} != {n} (decode verify)") +# return w, h +# +# diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/operations/prepare-w4-c10.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/operations/prepare-w4-c10.py new file mode 100644 index 0000000000000000000000000000000000000000..a96df6f5773da6c009993e00cd413e1cdd305462 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/operations/prepare-w4-c10.py @@ -0,0 +1,52 @@ +"""Preserve completed r1 sequences without re-encoding or touching source files.""" +import datetime +import json +import os +from pathlib import Path +import shutil + +old = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260929-r1') +new = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10') +snapshot = Path('/tmp/h2o-w4-c10-recovery') +new.mkdir() +shutil.copytree(snapshot / 'scripts', new / 'frozen-code/scripts') +shutil.copytree(snapshot / 'docs', new / 'frozen-code/docs') +shutil.copytree(snapshot / 'tests', new / 'frozen-code/tests') +release = new / 'H2O/shared-v1.0' +for directory in ('data', 'doc', 'script', 'script/provenance/r1', 'script/provenance/operations'): + (release / directory).mkdir(parents=True, exist_ok=True) +history = release / 'script/provenance/r1' +shutil.copytree(old / 'H2O/shared-v1.0/script', history / 'script') +shutil.copytree(old / 'frozen-code/docs', history / 'docs') +for name in ('full.log', 'full.status', 'run-full.sh'): + shutil.copy2(old / name, history / name) +records = [] +for record in sorted((old / 'H2O/shared-v1.0/doc').glob('*.build.json')): + build = json.loads(record.read_text()) + seq = build['sequence_id'] + assert Path(seq).name == seq and seq not in ('.', '..') + assert set(build['views']) == {f'cam{i}' for i in range(5)}, seq + data = old / 'H2O/shared-v1.0/data' / seq + frames = {} + for cam in build['views']: + meta = json.loads((data / cam / 'metainfo.json').read_text()) + frames[cam] = sum(1 for _ in (data / cam / 'camera/frames.jsonl').open()) + assert frames[cam] > 0 + shutil.copytree(data, release / 'data' / seq, copy_function=os.link) + shutil.copy2(record, release / 'doc' / record.name) + records.append({'sequence_id': seq, 'frames_by_camera': frames, + 'original_script_sha256': build['scripts']}) +manifest = {'time': datetime.datetime.now().astimezone().isoformat(), + 'source_run': str(old), 'destination_run': str(new), + 'reason': 'User requested four archive workers, ten threads per encoder, no CPU quota', + 'reuse': 'Hard-linked immutable completed views; frames and component source SHA256 rechecked during resume', + 'excluded': 'Unpublished .tmp directories; historical 62-sequence output; failed initial full run', + 'original_runtime_provenance': 'script/provenance/r1', 'sequences': records} +(release / 'doc/RESTART_PROVENANCE.json').write_text(json.dumps(manifest, indent=2) + '\n') +for source, target in (('/tmp/h2o-prepare-w4-c10.py', 'provenance/operations/prepare-w4-c10.py'), + ('/tmp/h2o-reconfigure-w4-c10.sh', 'reconfigure-w4-c10.sh'), + ('/tmp/h2o-run-w4-c10.sh', 'run-full.sh')): + shutil.copy2(source, release / 'script' / target) +shutil.copy2('/tmp/h2o-run-w4-c10.sh', new / 'run-full.sh') +shutil.copy2('/tmp/h2o-w4-c10-frozen-tests.log', history.parent / 'worker4-codec10-regression.log') +print(f'REUSED_SEQUENCES={len(records)} REUSED_VIEWS={sum(len(r["frames_by_camera"]) for r in records)}', flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/operations/retry-w4-c10.sh b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/operations/retry-w4-c10.sh new file mode 100644 index 0000000000000000000000000000000000000000..983a246b66440da976c7b929df289b0ec6427973 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/operations/retry-w4-c10.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail +base=/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10 +script="$base/H2O/shared-v1.0/script" +mkdir -p "$script/provenance/operations" "$script/provenance/startup-failure" +mv "$script/prepare-w4-c10.py" "$script/provenance/startup-failure/prepare-w4-c10.py" +cp /tmp/h2o-prepare-w4-c10.py "$script/provenance/operations/prepare-w4-c10.py" +mv "$base/full.status" "$script/provenance/startup-failure/full.status" +mv "$base/full.log" "$script/provenance/startup-failure/full.log" +cp /tmp/h2o-retry-w4-c10.sh "$script/provenance/operations/retry-w4-c10.sh" +systemd-run --user --scope --unit=h2o-full-w4c10-r2-20260930 -p CPUAccounting=yes /bin/bash "$base/run-full.sh" diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/CONTRACT.md b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/CONTRACT.md new file mode 100644 index 0000000000000000000000000000000000000000..f756d711647e109b6bb732ce1b9c84111730489d --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/CONTRACT.md @@ -0,0 +1,457 @@ +# 手物数据仓库统一约定 v1.0 + +格式版本:`hand-warehouse/1.0`。存储约定:`lossless-video-2026-09-18`。 + +范围限于手物交互重建。按本任务纳入的源模态转换,不要求每个数据集填满所有组件。缺失模态、尚未下载、语义未核实分别报告,不能互相替代。 + +本文定义各字段的含义与使用规则,机器可读注册表见 [schema.json](schema.json)。两者互相补充;如有冲突,应先核实并统一定义。 + +## 1. 目录 + +```text +hand-datasets/ + / + raw/ + doc/ # 官方说明、来源与校验记录 + script/ # 官方下载脚本、必要包装脚本 + data/ # 保留原始包,不原地解压或改写 + / + doc/ # 发布说明、schema、来源清单 + script/ # 转换、校验脚本及运行配置 + data/ + / + / + metainfo.json + observation/ + rgb.mkv + rgb_valid.pt + depth.mkv # float32 深度的可逆视频编码 + depth_valid.mkv # 逐像素 bool 的无损视频编码 + camera/ + frames.jsonl + intrinsic.pt + intrinsic_valid.pt + extrinsic.pt + extrinsic_valid.pt + annotation/ + mano/ + motion.pt + motion_valid.pt + visibility.pt + keypoints/ + uv.pt + uv_valid.pt + xyz.pt + xyz_valid.pt + visibility.pt # 源数据有时提供 + object/ + / + assets/ # 该物体的网格、材质、纹理及部件资产 + .obj + pose.pt + pose_valid.pt + visibility.pt + metainfo.json # 物体身份、类别、mesh、尺寸与部件引用 + articulation.json + keypoints/ + vertex_part_ids.pt + joint_state.pt + joint_state_valid.pt + parts//pose.pt + parts//pose_valid.pt + segment/ + mask.mkv + mask_valid.pt + instances.jsonl + contact/ + relations.jsonl + __/ # 对应实体间的距离/接触区域 +``` + +目录展示可能存在的组件,不要求填满。具体文件、字段和缺省规则分别见后续对应小节。原始包的解压发生在临时工作区,raw 内原始包保持不变。 + +## 2. 相机视图的 metainfo.json + +### 2.1 顶层字段与发布信息 + +每个相机视图必须有 `metainfo.json`。以下字段除另行说明外均为必填: + +| 字段 | 填写内容 | +|---|---| +| schema_version | 结构版本,本版为 `hand-warehouse/1.0` | +| dataset_id | 数据集的逻辑标识 | +| release_id | 本次数据发布版本,对应目录中的 dataset_version | +| sequence_id | 所属序列或独立图片样本的标识 | +| camera_id | 当前相机视图标识 | +| sample_type | `image` 或 `video`,规则见 2.2 | +| num_frames | 当前视图帧数 T,所有随帧组件按同一时间轴组织 | +| hand_slots | 固定为 `["left", "right"]`;解剖学左右的使用规则见 5.1 | +| sampling | 采样类型、源 FPS、帧索引引用及选择策略,见 2.2 | +| camera | 当前相机模型与图像尺寸,见 2.3 | +| components | 实际提供的组件及其文件、schema、有效性和来源,见 2.5 | +| split | `train/val/test/unknown`,划分协议见 2.4 | +| view_type | 可选,`ego/exo/unknown` | + +`dataset_version` 是数据发布版本;`schema_version` 是结构版本,两者独立。原始包校验摘要、官方来源和转换配置应记录在发布清单中。解压发生在临时工作区,原始包保持不变。 + +### 2.2 图片、视频与 sampling + +`sample_type=image`:允许单图 T=1、`sampling.type=single`,也允许将独立图片批量装入一个视频容器,T>1 时 `sampling.type=independent`、`source_fps=null`。分片大小按数据集选择;FreiHAND 默认每片最多 4096 张,训练与评估分开,尾片不补帧。该数量不是其他数据集的强制要求;同批分辨率、相机模型类型及划分协议一致。每行 frames 必须有稳定且唯一的 `sample_id`、原始文件定位;内参、手形状等仍逐帧保留,不能因打包而共享错误的标定或身份。`sequence_id` 在这里仅是批次标识,不代表真实序列;不得按相邻帧推断跟踪、同步或接触延续。源 camera_id、image_variant、split 等随样本变化时放在 frames 的对应字段中。真实采集时间未知则 timestamp_ns=null。合成背景变体不视为真实多相机。 + +`sample_type=video`:`sampling.type=dense/sparse`;`source_fps` 是真实采集 FPS,未知为 null。非连续取样必须保留源帧号和已知源时间,不可用采样后索引除以 FPS 冒充源时间。可另记采样策略与步长。 + +shared 可以仅存所选 RGB 帧对应的数据。OakInk2 图像/动捕不同采样率时用 annotation_matches 明确映射;不要求将未采样动捕点硬塞进 T。多视角身份和源同步关系要保留;选择了哪些帧/相机及原因写在 sampling 中。 + +`sampling.frames_ref` 指向 `camera/frames.jsonl`。帧号、逐帧时间、同步与标注匹配记录的结构见 4.1;MKV 封装时间的约定见 3.1。 + +### 2.3 camera 模型声明 + +`camera` 至少包含 `model`、`schema_id`、`image_size:[W,H]`。模型未知使用 `unknown` 和 `null`,不猜成针孔。实际内参、畸变及外参数组放在 `camera/`,各模型的固定结构见第 4 节。 + +### 2.4 split 与划分协议 + +保留上游划分,不将同一采集序列的相邻帧随意拆到不同集合。 + +有官方划分时必填 split_scheme 和 split_source_locator,split_scheme 区分如 Dex-YCB s0/s1、ARCTIC P1/P2 等选定协议;不知道时 split=unknown 并给理由,不凭空分配。每发布可选择一种协议;存在逐帧差异时 frames 中的 split 覆盖视图默认值,并登记其来源。 + +### 2.5 components 组件登记 + +组件表的键是本发布内唯一名称,例如 `rgb`、`depth`、`mano`、`keypoints_uv`。每个已提供组件声明以下信息;模态特有参数在第 3–5 节对应小节中定义。 + +| 字段 | 约定 | +|---|---| +| available | 本发布是否提供该组件;缺省也表示未提供 | +| schema_id | 已登记的具体存储与语义类型,不得临时创造未登记名称 | +| data_ref | 数据文件路径,相对当前相机视图根目录,使用 POSIX 路径 | +| axes | 数组各维度的含义 | +| valid_ref / valid_axes | 有效性文件及其维度;语义由所属组件规定 | +| storage / valid_storage | 视频数据/视频有效性的存储配置;包含已登记 profile、实际 codec、pixel_format、encoded_size,见 3.1;非视频组件按原数组规则 | +| provenance | source / format_conversion / derived,以及转换或生成方法 | +| source_locator | 原文件、压缩包成员和记录/帧的定位信息 | + +不存在的组件允许缺省或写作 `{ "available": false, "reason": "..." }`,不用引用不存在的文件。静态网格可声明标量有效性;具体见 5.4。观测的 valid 见第 3 节,标注的 valid 与 visibility 区分见 5.1。 + +`provenance.kind` 使用 source/format_conversion/derived,`method` 说明转换或生成方法;发布清单补充脚本版本、参数、输入摘要。`source_locator` 定位到原始文件/压缩包成员和记录、帧号;允许引用有完整溯源清单的前一发布,但链条最终应能回到 raw。不得仅写一个无法定位记录的数据集名字。 + +`.pt` 仅保存 CPU Tensor,不保存 Python 自定义对象;浮点默认 float32,有效性为 bool,浮点无效位置填 NaN。所有随帧数组保留首维 T,单帧也不 squeeze;静态资产按其 schema 单独声明。单位、坐标及固定形状见各组件小节。 + +机器注册表 `schema.json` 中,`components` 固定解码后的数据类型、形状、单位和语义;`storage_profiles` 固定视频内的编码/还原方式。不得临时创造未登记的 schema_id 或 storage.profile。同一语义允许选择其登记的不同无损存储 profile。 + +## 3. observation 观测数据 + +### 3.1 rgb.mkv 与 rgb_valid.pt + +RGB、深度和栅格 mask 在 shared 中统一使用 MKV 视频容器,不展开为逐帧图片或图像 tar。MANO、关键点、位姿等数值标注仍用数组;分割的重叠多边形仍用 JSONL,不为了视频化而有损栅格化。单图可为一帧视频,独立图批量封装规则见 2.2。 + +**无损指共享层不增加信息损失。** 源 JPEG/H.264 等本身可能已是有损编码,原样保留并不恢复已丢失信息;不得重新以有损 JPEG、H.264、H.265、AV1 参数编码。源视频/图片的色彩、位深、分辨率和几何关系不得被静默改变。RGB schema `rgb/uint8/v1` 的统一读取结果是 `[T,H,W,3] uint8`、RGB 通道,有效性仍为 `rgb_valid.pt [T] bool`。超出该 schema 的高位深或 HDR 源必须报告并扩展定义,不能降到 8 位冒充无损。 + +#### 3.1.1 允许的 RGB 存储 profile + +| storage.profile | 编码方式 | 适用规则 | +|---|---|---| +| mkv/mjpeg_copy/v1 | 源 JPEG 压缩帧直接封装成 MJPEG/MKV | 不解码重编码;保持每张 JPEG 码流字节;普通 8 位 JPEG 且 MKV/解码器支持时使用 | +| mkv/source_copy/v1 | 已有视频的 RGB 对应码流直接封装为 MKV | 仅源编码能被 MKV 和选定解码器支持时使用,不伪造帧;需维持正确的呈现顺序与依赖帧 | +| mkv/h264_rgb_lossless/v1 | libx264rgb 的真正无损模式 | 必须 RGB 路径、CRF=0,并通过全帧 RGB 字节比较;不能替换成默认 libx264 YUV420 路径 | +| mkv/ffv1_rgb/v1 | FFV1 的 RGB 可逆编码路径 | 作为通用候选;解码回 RGB 后必须逐字节相同,不做色度降采样 | + +优先尝试源码流直接封装;不能封装或需要选择稀疏帧时,比较 FFV1 与无损 RGB H.264。对完整待发布片段,只在通过无损验收的候选中选择文件较小者,不假设某个编码器总最小;编码时间和随机读取代价记入构建记录。中间候选不作为 shared 多份常驻。H.264 跨帧压缩允许较长 GOP,必须记录 GOP/关键帧间隔,随机取帧需从前一关键帧正确解码,不能把 seek 返回的近似帧当目标帧。 + +普通源视频可以保留它已有的有损码流,但不允许新增有损重编码。源是 VRS 等记录容器时,先查明图像流实际编码:已有兼容 JPEG/视频包可直接提取封装,否则解码后使用真正无损编码;不把整个 VRS 改后缀当 MKV。PNG 不要求直接塞进 MKV,可选上表两种无损重编码方式。 + +#### 3.1.2 视频配置与校验 + +每个视频组件在 metainfo 中登记 `storage`,至少包含: + +| 字段 | 内容 | +|---|---| +| profile | 上述登记的存储 profile;语义仍由组件 schema_id 指定 | +| codec | 文件中实际 codec,例如 mjpeg、h264、ffv1;source_copy 必须写实际 codec | +| pixel_format | 实际编码像素格式;不得仅凭编码器参数猜测 | +| encoded_size | 视频物理像素尺寸 `[width,height]`;深度可能不同于逻辑尺寸,见 3.2 | +| decoder | 解码器名称、版本,以及颜色矩阵/范围/旋转处理等实际像素解释配置;未知的源色彩声明 unknown,不擅自称为 sRGB | +| encoder_parameters | 重编码时的编码器、版本、无损模式和 GOP 等参数;直接封装时记录 stream_copy | +| source_lossy | 源是否已有损:true / false / unknown;不是共享层再有损编码的许可 | + +无损重新编码的 RGB 必须使用同一固定解码配置,比较**全部帧**的统一 RGB 字节、数量及顺序。MJPEG-copy 不重新编码,生产校验采用 `jpeg-packets-all-rgb-sample16/v1`:从 MKV 逐包取回,对全部源 JPEG 的 SHA256、数量、顺序和图像尺寸进行精确核对;每视图另用同一固定解码配置比较最多 16 帧的源与目标 RGB 字节(含首尾与四分位位置,其余由固定种子抽取)。记录策略、实际索引、种子与结果;不足 16 帧时全查。试点与最终完整序列随机抽查,对选中视图的全部帧复核解码 RGB。历史已做全帧像素检查的证明继续保留。 + +逐包一致与像素抽查的范围必须分别声明,不能将抽查写成全量像素检查。不能用 PSNR 高、视觉相似、编码器参数称为 lossless 等替代精确检查。同时保留源编码的色彩标记和必要元数据;原图有 EXIF/色彩/方向等元数据时保留 raw 和必要来源信息;不能静默自动旋转图像而不更新像素对应与标定。以上加速策略仅适用于原 JPEG 码流直接封装,不适用于深度、标签或重新编码的 RGB。 + +所有共享视频的呈现帧顺序与统一 frame_index 一一对应,每个栅格组件恰好 T 帧。MKV 的 `storage_fps` 只服务封装,声明 `timebase_role=index_only`;source_copy 可以保留源 PTS 以避免改坏码流,但真实时间与标注对齐仍以 frames 为准。未知真实时间保留 null。缺失某帧组件时保留索引位置并使用该组件的无效占位/valid 标识,不删帧;不能以重复相邻图像冒充已知观测。 + +### 3.2 depth.mkv 与 depth_valid.mkv + +深度语义仍是 `depth/z_float32/v1`:统一读取结果 `[T,H,W] float32`,米制相机 Z 分量,`depth_type=z`。有效深度有限且大于 0,无效位置为 NaN。`depth_origin=measured/rendered/unknown` 必填,来源不明时 unknown。默认与 RGB 共用像素网格及相机参考系,不处理未注册 RGB-D。射线距离必须依据源定义转换成 z,不能只改声明。 + +#### 3.2.1 float32 的可逆视频编码 + +采用 `mkv/depth_float32_bits/v1`:**不是把深度量化成 uint16**,而是将规范化后每个 IEEE-754 float32 的完整 32 位拆成两个 uint16,使用 FFV1 gray16le 保存。视频物理尺寸为 `[2W,H]`:每行前 W 列存原 float32 位串的低 16 位,后 W 列存高 16 位。读取时先合并为 uint32 位串,再按 float32 重新解释,不能数值 cast 成 float32。 + +```text +u = reinterpret_uint32(depth_float32) +encoded[:, :, :W] = uint16(u & 65535) +encoded[:, :, W:] = uint16(u >> 16) +u_restored = uint32(low) | (uint32(high) << 16) +depth_float32 = reinterpret_float32(u_restored) +``` + +统一采用 little-endian 原始字节接口。`camera.image_size` 始终是逻辑 RGB 尺寸 `[W,H]`,不能改成编码视频的 2W;`storage.encoded_size=[2W,H]`。包括 NaN 在内的 float32 位串必须全帧完全恢复,不允许改成 float16、整数毫米、归一化灰度或 RGB 伪彩色。这里的无损验收基准是完成既定米制/坐标转换后的标准 float32 数组,不声称消除 float64→float32 等原约定转换本身的舍入。 + +#### 3.2.2 逐像素有效性 + +`depth_valid.mkv` 使用 `mkv/bool_ffv1/v1`,FFV1 gray8(FFmpeg pixel_format=`gray`),物理尺寸 `[W,H]`。像素只能为 0 或 1,统一解码为 `[T,H,W] bool`,逐像素含义不变。这样不再把庞大的 bool 数组保存为未压缩 `.pt`;标注的帧级/手级 valid 仍保留原有小数组。 + +登记示例(W、H 以下取 640、480;decoder/encoder_parameters 的实际版本由转换器填写): + +```json +{ + "available": true, + "schema_id": "depth/z_float32/v1", + "data_ref": "observation/depth.mkv", + "axes": ["T", "height", "width"], + "valid_ref": "observation/depth_valid.mkv", + "valid_axes": ["T", "height", "width"], + "unit": "m", + "depth_type": "z", + "depth_origin": "measured", + "invalid_value": "NaN", + "storage": { + "profile": "mkv/depth_float32_bits/v1", + "codec": "ffv1", + "pixel_format": "gray16le", + "encoded_size": [1280, 480], + "source_lossy": false, + "decoder": {"name": "ffmpeg", "version": "填写实际版本"}, + "encoder_parameters": {"name": "ffv1", "level": 3, "version": "填写实际版本"} + }, + "valid_storage": { + "profile": "mkv/bool_ffv1/v1", + "codec": "ffv1", + "pixel_format": "gray", + "encoded_size": [640, 480], + "source_lossy": false, + "decoder": {"name": "ffmpeg", "version": "填写实际版本"}, + "encoder_parameters": {"name": "ffv1", "version": "填写实际版本"} + }, + "provenance": {"kind": "format_conversion", "method": "源深度转米制 z float32;逐位打包为 FFV1"}, + "source_locator": {"file": "raw/data/depth.zip", "member": "depth/0001.png"} +} +``` + +深度和有效性视频都必须逐帧解码验收:float32 位串相同、bool 相同、T 相同,并检查 valid=true 的正有限值和 valid=false 的 NaN。读取器必须按 profile 还原,不能把 depth.mkv 的编码像素直接当深度值。 + +## 4. camera 相机、帧索引与标定 + +### 4.1 frames.jsonl:索引、时间与对应关系 + +`camera/frames.jsonl` 每行对应统一帧号 `frame_index=0..T-1`,是所有组件的唯一行索引。至少包含 `frame_index`、`timestamp_ns`、`clock_domain`、`source_locator`;原始帧号/文件名保存在 `source_frame_id`,不能被新帧号替代。每行还可有 `annotation_matches`,按组件键保存 `source_frame_id`、`source_timestamp_ns`、`clock_domain`、`match_method` 和 `delta_ns`;方法为 exact/index_map/nearest/interpolated,索引映射无时间依据时 delta_ns=null。nearest 必须记录允许误差;interpolated 必须记录两端源标识和权重。delta_ns 仅在同一时间域中计算为源标注时间减图像时间。多相机共享 `sequence_id`;已知同步关系必须用 `sync_id` 或明确的源帧/时间映射表达,不能仅凭相同数组索引认定同步。 + +每个视图必须提供此文件。源时间使用整数纳秒及 `clock_domain`,未知写 JSON `null`;不同时间域不能直接比较。逐帧 split 可以覆盖 metainfo 的视图默认划分,并保留来源,见 2.4。 + +### 4.2 坐标系与标定通则 + +| 项目 | 统一约定 | +|---|---| +| 相机坐标 | 右手系,X 向右、Y 向下、Z 向前,长度单位米 | +| 齐次变换 | 列向量,`p_target = T_target_from_source @ p_source` | +| 图像坐标 | `(u,v)`;左上像素中心为 `(0,0)`,u 向右、v 向下,单位 pixel | +| 固定标定 | 本版展开为 T 份,同一 schema 不混用静态与动态形状 | +| 分辨率或模型变化 | 分开存储为视图/片段,不在同一组件中混装 | +| 未知标定 | 相机内外参允许缺省,不填单位阵冒充已知标定 | + +### 4.3 intrinsic.pt 与畸变参数 + +| model / schema_id | intrinsic.pt 的固定结构 | +|---|---| +| pinhole / camera/pinhole/v1 | `[T,3,3]`,标准 K,最后一行为 `[0,0,1]`;限无畸变或已校正图像 | +| fisheye624 / camera/fisheye624/v1 | `[T,15]`,`[f,cx,cy,k0,k1,k2,k3,k4,k5,p0,p1,s0,s1,s2,s3]`,采用 Project Aria Fisheye624 投影定义 | +| opencv_fisheye4 / camera/opencv_fisheye4/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件 `distortion_ref` 指向 `[T,4]`,顺序 `[k1,k2,k3,k4]`,使用 OpenCV fisheye 等距角度多项式;已由 ReInterHand 实际原始相机参数验证 | +| rational8 / camera/rational8/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件必需 `distortion_ref` 指向 `[T,8]`,顺序 `[k1,k2,p1,p2,k3,k4,k5,k6]` | +| unknown / null | 不提供可用 intrinsic,不声称可以投影 | + +有畸变的其他模型必须注册新 schema,固定参数名、顺序和投影公式;不能塞进针孔 K 后遗失畸变项。`metainfo.camera.schema_id` 必须与 intrinsic 组件一致。同一模型的别名不可隐式改变参数布局。 + +`opencv_fisheye4`:对前方点令 `x=X/Z, y=Y/Z, r=sqrt(x²+y²), theta=atan(r)`,`theta_d=theta*(1+k1*theta²+k2*theta⁴+k3*theta⁶+k4*theta⁸)`;`u=fx*x*theta_d/r+cx, v=fy*y*theta_d/r+cy`。光轴 r=0 时使用连续极限 `theta_d/r=1`。四系数不能按普通径向畸变解释,也不能补零冒充 Fisheye624。 + +rational8 对归一化坐标 x=X/Z、y=Y/Z,令 r²=x²+y²,径向项为 `(1+k1*r²+k2*r⁴+k3*r⁶)/(1+k4*r²+k5*r⁴+k6*r⁶)`;再加 p1/p2 切向项并经 K 得到像素。`distortion_ref` 与 intrinsic 共用 `[T]` valid,保存到 camera/distortion.pt。不得把这种畸变三维坐标当作真实相机系 xyz 保存。 + +内参有效性为 `intrinsic_valid.pt [T] bool`;有畸变时使用对应 `distortion_ref`。同一模型的参数名和顺序固定。 + +### 4.4 extrinsic.pt 与 extrinsic_valid.pt + +`extrinsic.pt` 为 `[T,4,4]`,schema `transform/se3/v1`,方向固定 `T_camera_from_world`,有效性 `[T]`。世界坐标含义及源坐标转换记录在 provenance 中;只有相机坐标标注不要求虚构世界坐标。旋转块须正交且 determinant≈1。 + +## 5. annotation 标注数据 + +### 5.1 标注通则:手槽、valid 与 visibility + +手槽固定为 0=left、1=right,指解剖学左右,不按画面位置或可见性重排。本阶段只处理左右手两槽,不处理更多手。实体引用使用 `hand_left`、`hand_right`;手槽不证明跨采集片段的个人身份。 + +#### 5.1.1 valid:标注是否可用于监督 + +标注的 `valid=true` 表示:有对应实际标注、通过本 schema 数值检查,且通过来源明确提供并适用于该组件的有效性/QA 条件。`valid=false` 可由缺标注、无法建立帧对应、源无效占位或官方 QA 不通过导致;不等于画面没有手或手不可见。各组件独立判断,MANO 按 `[T,2]` 标记左右手,关键点按 `[T,2,K]` 标记。 + +**2026-09-20 将标注 valid 从“仅表示存在”修订为“可用于监督”,字段形状不变。** 公式为 `source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass`。没有官方 QA 时省略最后一项,不伪造 QA;不能把未知当成已通过已存在的 QA。适配器在组件 `valid_policy` 中记录具体规则、来源、聚合/广播作用域。缺失官方必需 QA 的记录须明确处理为未知或暂停验收,不能静默通过。无效浮点项仍填 NaN,原始数据保留在 raw;被排除原值可用于 doc 中明确标识的诊断渲染,不能冒充 shared 有效监督。 + +本地筛选须依据明确的规则,并在 `valid_policy.local_excluded_frame_indices`、排除原因和正式报告中记录。单个可疑投影作为问题记录,不直接硬编码排除该帧。已确认的曝光异常须明确作用范围,不能把一个序列的“前两帧有问题”套到所有序列。RGB 编码完好与几何监督可用是两件事,允许保留原图及帧索引而屏蔽对应标注;未发现问题不等于完成全部人工审核,试点待确认时不能作为已验收发布使用。 + +源字段必须按官方语义映射,不能直接按名字复制: + +| 来源 | 官方含义 | 映射原则 | +|---|---|---| +| [H2O](https://github.com/taeinkwon/h2odataset) 的手标注首位 | 0 未标注、1 已标注 | 可作为对应手标注存在性的依据,不推断未标注原因 | +| [HOT3D](https://github.com/facebookresearch/hot3d#using-mask-files) 的 pose_available、visible、mask_qa_pass | 分别表达姿态存在、可见性、对画面中可见手物位姿的人工 QA | 逐手/物体记录决定存在性,再 AND 当前相机当前帧 QA;QA 是整帧聚合判定,保守排除该帧全部手物几何监督,不声称每个实体均有错误;源可见性基于位姿推导时,其自身 valid 同样受 QA 约束 | +| [Dex-YCB](https://github.com/NVlabs/dex-ycb-toolkit#loading-dataset-and-visualizing-samples) 的全零 pose_m、全 -1 joints | 不可见的手或缺标注共用占位表示 | 对应组件 valid=false;不能从该值判定 visibility=false,也不能声称原因是动捕缺失 | +| [ARCTIC](https://github.com/zc-alexfan/arctic/blob/master/docs/data/data_doc.md) 的 is_valid/left_valid/right_valid | 是否有效用于官方评估 | 核实每项筛选依据;不把可见性/评估选择直接等同 QA。本次原始 mano.npy 不含这些派生评估标记,按原记录与数值检查生成 valid,并声明没有额外官方 QA 输入 | + +源 valid=false 若代表评估筛选或其他条件,应检查实际标注和源约定后映射;不能一律清空坐标。反之,占位零或 -1 只有在源官方明确规定时才判为缺失,不泛化成所有数据的判断规则。 + +`valid=true` 的标注应通过其 schema 的数值与形状检查;检查失败必须报告或修复,不能静默隐藏。QA 不通过应报告排除数量与原因,并保留可追溯信息;不能把这类无效称为缺标注。RGB、深度等观测有效性仍按各自 schema;手物 QA 不自动否定 RGB、静态相机内参或物体资产。相机外参是否过滤须依据其自身来源规则;HOT3D 本次保留源外参用于溯源和诊断,不能用其存在性证明 QA 失败帧的几何监督正确。 + +#### 5.1.2 visibility:可见性属性 + +附加质量属性只保留 `visibility`,存放在对应模态或标注集内,不设 quality 目录。同一份可见性仅存一次;uv 与 xyz 共用时引用同一个文件。 + +visibility 通过所属组件 attributes 登记 data_ref、axes、dtype、visibility_type、meaning、provenance、source_locator;未知值通过属性 valid_ref 标识,全已知可声明 valid=true。比例与布尔值不相互强转,也不按任意阈值二值化。没有 MANO 时,整手可见性挂在 keypoints 组件,使用独立的 whole_hand_visibility.pt,明确 meaning=whole_hand,不与逐关键点可见性混用。 + +`valid` 回答“这项标注能否用于监督”,`visibility` 回答“在当前图像中是否可见(或可见多少)”。不可见的手或关键点仍可有有效标注;不能因 visibility=0 就清空坐标。源没有 visibility 时缺省或标为未知,不由 valid 推断。 + +| 情况 | 手标注 valid | visibility | +|---|---|---| +| RGB 已开始录制,动捕尚未开始,没有其他对应手标注 | false | 以独立源可见性标注为准;没有则未知 | +| 手被遮挡,但源有标注且通过适用有效性检查 | true | 若源声明不可见,则 false 或源可见比例 | +| 手可见且有对应标注,通过适用 QA | true | 若源有此信息,则 true 或源可见比例 | +| 手可见,但该帧漏标或动捕中断 | false | 可以为 true,但必须有独立来源依据 | +| 有手部参数,但官方 QA 明确不通过 | false | 不据此断言不可见;源可见比例若基于不可靠位姿,其属性 valid 也为 false | + +visibility 自己的 valid_ref 表示该可见性标注是否可用,不复用 MANO 或关键点坐标的 valid_ref;明确记录源存在性及适用的 QA 条件。上述例子不要求凭图像自动生成可见性。 + +不设 quality 组件或目录,不另存拟合误差、曝光、截断比例等通用质量数组。适用的官方 QA 合并进对应 valid,在 `valid_policy` 记录来源与规则;正式校验报告保留原始 QA 时间区间及排除统计。原始 QA 文件仍在 raw,官方 split 保留。 + +### 5.2 mano:参数与整手可见性 + +MANO schema `mano/axis_angle61/v1`:`motion.pt [T,2,61]`,顺序为完整 16 关节 axis-angle 48、shape betas 10、全局平移 3。姿态使用弧度,平移米,位于当前相机系。有效性 `[T,2]`;缺少一侧整槽 NaN。PCA 必须先按对应模型展开,不能将 PCA 系数直接填入 axis-angle。 + +`model_profile` 必须固定 MANO 版本、`flat_hand_mean=true`、左手 shapedirs 修正状态。平移表示模型输出顶点所加的全局平移,不是某个腕关节的坐标;源语义不同须转换。shape 无量纲。模型权重不作为共享数据附带上传。 + +`mano/visibility.pt [T,2]` 保存源整手可见比例时使用 float32 [0,1],`visibility_type=ratio`;只有实际采用 0–100 的百分比才除以100,不能只凭表头判断。HOT3D 的 `visibility_ratio[%]` 实值已经是0–1,官方读取器原样读取,必须保留原值。通过 MANO 组件 attributes 登记,使用独立有效性,不复用 motion_valid。 + +手部共享表示仅保留 MANO 参数与选定关键点,不发布独立手表面几何。需要渲染或接触计算时由 MANO 参数生成,几何引用使用固定 MANO 模型配置与顶点顺序;不影响 object 下的物体模型和材质资产。 + +### 5.3 keypoints:二维点、三维点与逐点可见性 + +关键点独立于 MANO 参数存在;没有 motion 也可有关键点。`uv.pt [T,2,K,2]` 与 `xyz.pt [T,2,K,3]`,有效性 `[T,2,K]`,分别采用 `keypoints/uv/v1` 和 `keypoints/xyz/v1`。K 由 `keypoint_schema` 固定,不能在同一数组中逐帧变化;同体系统一顺序。数值使用像素坐标或米制相机系。 + +| keypoint_schema | K 与固定索引 | +|---|---| +| mano21/v1 | 21;wrist 后依次 thumb/index/middle/ring/little,每指由近端至指尖 | +| rhd21/v1 | 21;保持 wrist,然后五指由近端至指尖;原始每指 tip→palm 反序。只统一顺序,不宣称解剖学位置等价于 MANO | + +具体名称与源索引映射见 `schema.json`。当前只登记 MANO21 与 RHD21;不登记 MediaPipe、ReInterHand capture21 或 fit24 中间关键点。 + +每个发布中的每个视图只提供一套标准手关键点,直接放在 keypoints 下,不设 annotation_set_id 字段或目录。uv 与 xyz 是这套关键点的二维与三维表示,不是两套标注。provenance 分别记录二者来自原始标注还是计算结果;不要求已有 2D 必须由当前 xyz 重新投影覆盖。 + +ReInterHand 的 Original keypoints、Original fits keypoints 及带前臂关键点不纳入 shared;如需手关键点,从选定 MANO 参数生成 MANO21 并记录模型/指尖回归约定。其他数据集默认使用选定的官方关键点,不额外生成平行的 MANO 派生集合。后续主动更换生成方法或结果时发布新的 dataset_version,不在同一版本内增设方法分支。 + +manual/projection/fitting 只记录在 provenance,不作为目录或类型分支。不得通过坐标为零、是否出画或 visibility 判断标注是否存在。派生标注仅在实际生成并通过数值检查后声明 valid=true;没有生成的项为 false,不伪造坐标。 + +`keypoints/visibility.pt [T,2,K]` 保存源逐点可见性,布尔表示使用 `visibility_type=boolean`。uv 与 xyz 共用时引用同一份文件。整手比例属性没有 MANO 可挂载时使用 `whole_hand_visibility.pt [T,2]`,`meaning=whole_hand`;它与逐点可见性分开,通用登记规则见 5.1。 + +不使用 annotation_set_id;ReInterHand 中间关键点集合不进入 shared,raw 保留来源文件。 + +### 5.4 object:身份、资产、位姿与几何 + +#### 5.4.1 metainfo.json:物体身份与跟踪作用域 + +手用 `hand_left`、`hand_right` 及槽位 0、1 表示,不再另存 entities.json。物体身份登记在 `annotation/object//metainfo.json`,必填 `object_id`、`identity_scope`、`scope_id`、`source_locator`;可含 `category_id`、`source_object_id`、`mesh_ref`、`has_model`、部件引用。即使只有分割、没有 pose/mesh,也可只有这份物体元信息。 + +`identity_scope` 为 frame/subsequence/sequence,`scope_id` 指定具体作用域;跨相机共享身份只在已有源对应证据时使用。VISOR 按官方 subsequence 与实体名关联时记录 `association_basis=official_subsequence_entity_name`,不能声称这是全视频物理实例跟踪。无需与 object_id 一一对应的标准 track_id;官方独立轨迹标识存在时保留为 source_track_id,并声明作用域。手槽不证明跨采集片段的个人身份。 + +#### 5.4.2 assets:网格、材质与纹理 + +资产属于物体,统一存放在 `annotation/object//` 内,可用 `assets/` 子目录组织网格、材质、纹理和部件资产。序列层不设共享 assets。所有引用采用视图根目录为基准;其中物体资产组件的 `data_ref` 与部件的 `mesh_ref` 采用相对于当前视图目录的 POSIX 路径,例如 `annotation/object/cup_01/assets/cup.obj`,且必须指向所属物体目录内的资产。OBJ 内部的材质、纹理引用遵循文件格式自身的相对路径规则,依赖文件一并保留。不同相机视图允许各自保存物体资产,不要求跨视图去重;下载物体时包含其资产依赖。 + +网格 schema 为 `mesh/obj/v1`,顶点米制,静态有效性可直接声明标量 `valid`,或通过 `valid_ref` 指向标量 bool Tensor;不按 T 重复静态资产。由物体/部件通过引用关联,不仅凭文件名猜测。 + +#### 5.4.3 pose.pt、pose_valid.pt 与 visibility.pt + +刚体 schema 为 `object/rigid/v1`,`pose.pt [T,4,4]` 固定为 `T_camera_from_object`,平移米制,有效性 `[T]`。物体坐标原点、轴向必须与 mesh 一致;旋转块为正交矩阵且 determinant≈1。 + +`object//visibility.pt [T]` 保存源物体可见比例,float32 [0,1],`visibility_type=ratio`。通过所属物体组件 attributes 登记,独立表达其有效性。 + +#### 5.4.4 articulation.json、部件位姿与 joint_state.pt + +关节物体:schema `object/articulated/v1`,`articulation.json` 登记 `parts` 与 `joints`。每个 part 有 `part_id`、`parent_id`(根为 null)、`has_model`、`mesh_ref`;has_model=false 时 mesh_ref=null,结构节点允许没有网格。父链不得成环。每个 joint 有唯一 `joint_id`、`parent_part`、`child_part`、`type`;fixed 单位 null、revolute 弧度、prismatic 米。有源限位时保存 `limits:[lower,upper]`;没有时 null,不伪造上下限。部件姿态统一为 `T_camera_from_part [T,4,4]`,不与父局部变换混装。 + +若提供 `joint_state.pt [T,J]`,必须登记固定 joint_order、轴在父部件系的表达、零位变换与正方向,valid 为 `[T,J]`;缺少这些运动学定义时只发布部件位姿与已有来源信息,不伪造可驱动的关节模型。关节值与部件位姿同时存在时需验证一致性。 + +部件层级应声明语义:纯语义包含树允许 `joints=[]`,不将包含关系推断为机械关节。关节状态 schema 为 `object/joint_state/v1`;转动用弧度、移动用米,混合类型按 joint_order 对应的关节定义解释。 + +#### 5.4.5 dimensions、几何关键点与顶点部件标签 + +`dimensions.pt [T,3]` 采用 `object/dimensions/v1`,有效性为 `[T]`。 + +物体/部件 `dimensions` 为 `[length,width,height]` 米,轴顺序与该 mesh 的局部坐标关联,登记 `dimensions_semantics` 和来源。HOI4D dimensions 与 mesh 的具体尺度关系未验证前标为 source_unspecified,保留源值并暂停依赖该关系的几何验收,不能默认为待施加缩放。需要施加缩放时明确 scale_applied_to_mesh,禁止重复应用。 + +源物体关键点放 `object//keypoints/xyz.pt [T,K,3]`(相机系)或 `template_xyz.pt [K,3]`(物体系),schema 分别为 object_keypoints/camera/v1 和 object_keypoints/template/v1。明确 keypoint_schema、keypoint_names、单位及有效性;模板点配合 pose 可投影,无须重复生成全部帧。H2O 中心/角点/棱中点,以及 ARCTIC 部件点分别登记具体源顺序,不套用手的 21 点 schema。每个发布选择一套源几何点并记录选择,不另建方法分支。 + +`vertex_part_ids.pt [V] int64` 绑定 `mesh_ref` 与 topology_id,登记整数到 part_id 的映射;未知用 -1。ARCTIC 不同拓扑的资产分别绑定,不能共用未经转换的顶点标签。部件层级中 is_instance/has_model 等源属性保留,几何文件仍全部归 object。 + +### 5.5 segment:分割类别、编码与覆盖范围 + +每个发布选择一套任务使用的分割表示,不建立方法/标注集分支。没有分割就不创建 segment 目录,不为其他模态创建空的实体表。 + +| schema_id | 文件与数值语义 | +|---|---| +| segment/uint16_labels/v1 | mask.mkv;整数区域编号,通过 instances.jsonl 解释 | +| segment/instance_polygons/v1 | polygons.jsonl;实例多边形,可重叠;当前不支持孔洞拓扑 | +| segment/foreground_intensity/v1 | mask.mkv;0–255 前景强度,不是区域编号或经过校准的概率 | + +#### 5.5.1 uint16 标签图与 instances.jsonl + +组件声明 `segmentation_type=semantic/instance/part`;同一组件固定一种类型。`mask.mkv` 解码为 `[T,H,W] uint16`,schema `segment/uint16_labels/v1`,使用 `mkv/uint16_ffv1/v1`,FFV1 gray16le 无损;只有所有区域编码均 ≤255 时允许 gray8(pixel_format=gray),读取后转 uint16,数值不变。禁止调色板和有损编码。有效性 `[T]`,表示该帧有可用分割标注。数值 0 固定为 unassigned,65535 固定为 ignore,1–65534 为区域编码,不能直接等同 entity_id。 + +`instances.jsonl` 每帧一行,包含 `frame_index` 与 `labels`。每条标签包含 `mask_value`、`category_id`、`entity_id`、`part_id`;无意义或未知字段为 null。semantic 允许 entity_id=null;instance 必须引用 hand_left/hand_right 或登记的 object_id;part 还须关联登记部件。源实例 ID 和其他属性分别保存在 `source_instance_id`、`source_attributes`。mask 中每个非保留编码必须有且仅有一个映射。 + +FreiHAND 的试点按本任务需要,统一到手/背景类别,保留每个原生区域编码;不要求给原生细分区域猜测手指名称。需要细部件监督时,尚未核实的部件名称必须保持未知,不能因粗粒度手类别已核实便声称部件语义也已统一。 + +#### 5.5.2 重叠实例多边形 + +每发布选择一套任务使用的分割表示,不建立方法/标注集分支。VISOR 的实际试点存在重叠实例多边形,单层标签图不能无损表达。对此补充 `segment/instance_polygons/v1`:`segment/polygons.jsonl` 每帧包含 `frame_index` 和 `instances`,每实例包含 `mask_value` 与 `polygons`(列表,每个多边形为源图像像素坐标顶点序列,保留原始精度)。身份和类别仍由同一 `instances.jsonl` 映射,有效性仍为 `[T]`,通过 schema 区分物理编码。允许多实例重叠,不采用后画覆盖前画。消费者按需栅格化为独立实例二值 mask;不能声称合并的单层 mask 无损。 + +#### 5.5.3 灰度前景强度 + +ReInterHand 的官方渲染 mask 为双手合并的灰度前景掩码,实测存在 0–255 的中间值,不是左右手实例编号。登记 `segment/foreground_intensity/v1`:仍存 `segment/mask.mkv`,解码为 `[T,H,W] uint16`,使用 `mkv/uint16_ffv1/v1`,此类数据优先编码为 FFV1 gray8(pixel_format=gray),读取后转 uint16。有效值范围 0–255,归一化值为 `float32(value)/255`;0 为背景端点、255 为前景端点。组件声明 `foreground_category=hand`、`entity_id=null` 和双手合并语义,不使用区域编号映射。这里保留原始渲染 mask 强度,不把它称为经过校准的概率。若任务需要二值 mask,阈值化属于任务层派生操作,记录阈值;共享层不丢弃中间灰度。不同 schema 的数值含义不同,不能将该文件按整数类别图解码。 + +FreiHAND 训练集的 JPEG mask 使用 `segment/foreground_intensity/v1`,逐像素保留 JPEG 解码后的灰度,`entity_id=hand_right`。该 schema 不限定双手合并:单手或合并范围由 `entity_id` 与 `coverage` 明确声明。评估集整数区域图仍用 `segment/uint16_labels/v1`,两者不能仅凭文件名使用同一种解码语义。 + +#### 5.5.4 coverage 与有效性 + +`coverage.kind=full/selected_entities/partial/unknown`。full 指声明的标注范围完整;selected_entities 还应列出目标范围。无论哪种,0 本身不自动成为背景;背景要有明确类别映射,未标注区域不能用于构造负样本。保留源逐类/逐实例 exhaustive 信息,未知不可改写为完整。 + +三种表示的帧级有效性均为 `[T]`,表示该帧是否提供此分割标注;对应 valid_ref 在组件中登记,仍用小型 bool `.pt` 数组。栅格 mask 必须登记 storage,格式见 3.1.2,所有帧的整数编码或强度逐值完全相同。编码语义由 schema_id 决定,读取器不能仅依据 mask.mkv 文件名选择解码方式。 + +### 5.6 contact:接触、抓取、区域与距离 + +#### 5.6.1 relations.jsonl 与 relations_valid.pt + +`annotation/contact/relations.jsonl`,schema contact/relations/v1,每帧一行含 frame_index、relations。每条记录含 relation_type(contact/grasp)、subject_id(手槽或登记实体)、object_id、status、source_locator、provenance。status 固定为 positive/negative/unknown/target_unannotated:positive 必须有可解析目标,negative 表示源明确否定该关系,unknown 为不确定,target_unannotated 为确有接触但目标未标注。非 positive 的 object_id 可 null,不能用 null 冒充“不接触”。稀疏源无记录的帧不自动补 negative。 + +VISOR 的对象 mask ID 必须先按同帧 source_instance_id 解析成 object_id;hand-not-in-contact、none-of-the-above、inconclusive 分别映射 negative、target_unannotated、unknown,保留原始字符串。Dex ycb_grasp_ind 通过 ycb_ids 映射到登记物体,以 relation_type=grasp 保存;不得当作逐顶点接触。 + +relations 组件的 valid_ref 指向 `relations_valid.pt [T] bool`,表示该帧是否有可用源关系标注。有效帧中可以存在 status=unknown 的明确不确定标注;无源标注的帧为 valid=false、relations=[]。组件仍声明 available/provenance/source_locator。 + +#### 5.6.2 实体对的顶点区域与距离 + +已发布的接触区域/距离按参与关系的 subject_id 与 object_id 组织,每对实体保留选定的一套结果,以精确 geometry_ref/topology_id 关联到手或物体/部件;不要求每套数据都有。顶点区域 schema contact/vertex_region/v1:bool `[T,V]` 加同形 valid;顶点距离 schema contact/vertex_distance/v1:float32 `[T,V]`、米、同形 valid,声明 source/target geometry_ref、distance_definition(signed/unsigned、测量到点集或表面等明确源定义)。geometry_ref 必须指向已登记 mesh 或由固定 MANO 模型配置确定的拓扑;拓扑/顶点数变化时按拓扑拆分片段。其他源区域表示只有在实际接入并登记 schema 后才可转换,不能随意栅格化宣称等价。 + +顶点区域/距离已有存储定义,但尚未完成真实输入试点;接入时必须提供源语义与几何验收证据,不因已经登记 schema 就视为通过。 + +## 附录:任务范围 + +不强制收录 2D bbox、完整高频动捕、动作程序、身体 SMPL-X、点云或网络特征。范围内的接触、visibility、选定手关键点、物体几何不能因不便处理而静默丢弃。分割采用的物理编码由第 5.5 节决定,存在重叠时不能以单层标签图声称无损。 + +不设置 entities_ref/segment/entities.json,不要求与 object_id 重复的 track_id。MediaPipe 不在当前关键点定义中;旧版本迁移必须保留可追溯关系,不能直接删表。手部共享表示不含独立 hand_mesh。 + +schema.json 是普通注册表,不是 JSON Schema 文档或可执行验收器;定义存在不代表真实数据已验证。验收须保留实测范围与未决项。 + +本存储约定只更新标准,不代表既有 FFV1/depth.pt 试点已迁移。新发布必须显式写 storage 配置;旧产物按其旧定义读取,不能只改文件后缀或版本标识伪装为合规。 diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/h2o-RAW_TO_SHARED.md b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/h2o-RAW_TO_SHARED.md new file mode 100644 index 0000000000000000000000000000000000000000..71253fa14376d7f6074f9a962ab4450e6db43306 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/h2o-RAW_TO_SHARED.md @@ -0,0 +1,30 @@ +# H2O raw → shared-v1.0 + +## 范围与来源 + +本版本仅转换 `raw/data/subject{1,2,3,4}_v1_1.tar.gz` 的真实五视角 (`cam0`–`cam4`) 序列;`h2o_CASA.tar` 是单独的扩展,不与标准序列混合。每个原始序列存于 `data/subjectN__/cam{0..4}/`。源压缩包保持不变,不合成源不存在的标注。输出仅在本地制作;完整序列试点及人工检查通过、更新全量预估之前,不启动全量。 + +| 源包/字段 | shared 文件/处理 | +| --- | --- | +| `subjectN_v1_1.tar.gz`: `camX/rgb/.png` | `observation/rgb.mkv`:逐帧源 RGB 解码为 RGB24,FFV1 直接编码;输出**每帧**解码与源 RGB 字节摘要完全一致。`rgb_valid.pt` 记录存在性,源帧号和每组件的包成员及 SHA256 写入 `camera/frames.jsonl`。不再额外编码未采用的 H.264 RGB 候选;FFV1 编码器进程失败时才尝试 H.264。 | +| 同包 `camX/depth/.png` | `observation/depth.mkv` 和 `depth_valid.mkv`;按源毫米单位除以 1000 转米,保留无效深度与全帧时间轴,深度位串以 FFV1 保真封装并逐帧校验。既不做 3 米裁剪也不造出缺失的深度。 | +| `camX/cam_intrinsics.txt`、`camX/cam_pose/.txt` | `camera/intrinsic.pt`、`extrinsic.pt`:保留源内参;逐帧源 `T_world_from_camera` 求逆后存 `T_camera_from_world`;声明变换约定与有效性。 | +| `camX/hand_pose_mano/.txt` | `annotation/mano/motion.pt`、`motion_valid.pt`:源左/右手标志各自判断有效性;姿态与平移保持源数值,声明 MANO 模型配置,缺模型则明确标依赖缺失,不伪造网格或掩码。 | +| `camX/hand_pose/.txt` | `annotation/keypoints/xyz.pt`、`xyz_valid.pt`:源双手 21 点,相机坐标系米制,与 MANO 有效性彼此独立。HTML 中的投影仅用于人工预览,不写回训练数据。 | +| `camX/obj_pose/.txt`、`obj_pose_rt/.txt` | `annotation/object//keypoints/xyz.pt`、`pose.pt`:按源类号关联 21 个物体点及物体→相机位姿;仅源存在时登记组件及有效性。 | +| `object.zip` | `annotation/object//assets/` 与源 OBJ、MTL、纹理;静态形状预览不等于所有帧网格位姿的投影证明。 | +| `label_split.zip` 的 `action_{train,val,test}.txt` | 序列元数据的官方划分及来源;未知映射明确记 `unknown`,不自行编排。 | + +`cam4` 是 ego,`cam0`–`cam3` 是 exo。真实时间/FPS 缺乏可靠来源时使用 null,不把 MKV 封装帧率冒充采集时钟。源 `action_label`、`verb_label`、pose 任务帧列表和 `manolabel_v1.1.tar.gz` 保留在 raw;当前契约没有相应动作组件,本发布不宣称它们已转换。源没有像素分割,本版本不投影网格生成替代分割。 + +## 源资产文件名修复 + +源 `object/cocoa/cocoa.obj` 引用 `ovomaltine.mtl`,材质内写的是 `map_Kd cocoa.png`,但原 ZIP 只提供 `ovomaltine.png`。仅在临时解压目录为该已确认的纹理增加**字节相同**的 `cocoa.png` 别名,保留原 PNG、OBJ、MTL 不变;在网格 `source_locator.texture_aliases` 中记录别名、原始包成员和 SHA256。别名与已保留的旧 cocoa 资产一致,不替换图像、标注或网格。全部八类物体的材质依赖在读取大 subject 包之前预检,其他缺失/越界依赖仍报错。 + +## 加速与验收 + +四个互不依赖的 subject 压缩包可由 `--workers 1..4` 并行顺序读取,各 worker 一次只处理一个序列。数值库保持单线程;FFV1 编码使用 `--codec-threads 4`(经完整视图实测后选择),逐帧解码校验仍保留。并发数由相同输入实测吞吐量决定,记录 OS 线程峰值和磁盘占用,不以 CPU 线程数本身作为提速证据。RGB 源为 PNG,不适用 ARCTIC/HOT3D 的 JPEG 包直封和 16 帧抽查:RGB、深度、有效性与数值模态仍逐帧精确校验。临时文件在 `/data` 上隔离放置,已有旧版目录不复用、不覆盖。 + +先运行不截帧的代表性完整序列试点,保存自动 QC、真实耗时和 `doc/validation/index.html`(RGB、深度、源 3D 关键点投影、原生物体网格和全组件数值/有效性)。试点由人工核查之后再决定全量;全量后再次抽样人工核查。报告须区分数据完整性、源未提供的模态与仅供人工判断的几何对齐。 + +2026-09-29 完整序列试点已获人工确认,用户已授权本地全量。资源预算改为 H2O 整个进程组不超过 101 CPU 总容量的约 80%,用 systemd 用户 scope 的 CPUQuota 管理,包含 FFmpeg 子进程;不以线程个数作为硬上限。101 当前 40 个逻辑 CPU 对应 CPUQuota=3200%(32 个逻辑 CPU 等效)。这不是全机其他用户任务的负载上限。源包和旧产物保留;失败版本不覆盖,修复版本使用独立输出目录。 diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/schema.json b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/schema.json new file mode 100644 index 0000000000000000000000000000000000000000..d904a34272de7f3fd4428c8dc68a919e94a68fca --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/schema.json @@ -0,0 +1,869 @@ +{ + "schema_version": "hand-warehouse/1.0", + "validity_revision": "usable-annotation-2026-09-20", + "annotation_validity": { + "meaning": "annotation usable for supervision, not merely record presence", + "formula": "source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass AND NOT explicitly_reviewed_local_exclusion", + "without_official_qa": "omit QA term; declare source rules; do not fabricate QA", + "policy_field": "components..valid_policy", + "visibility_is_independent": true, + "invalid_float_value": "NaN", + "hot3d": "broadcast per-camera frame manual QA conservatively to hand/object labels and pose-derived visibility; retain RGB and source calibration; keep native QA in raw and review report", + "hot3d_visibility": "native visibility_ratio[%] already ranges from 0 to 1; do not divide by 100" + }, + "hand_slots": [ + "left", + "right" + ], + "keypoints": { + "mano21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map": null, + "note": "adapter maps official MANO joint and fingertip convention" + }, + "rhd21/v1": { + "count": 21, + "names": [ + "wrist", + "thumb_1", + "thumb_2", + "thumb_3", + "thumb_4", + "index_1", + "index_2", + "index_3", + "index_4", + "middle_1", + "middle_2", + "middle_3", + "middle_4", + "ring_1", + "ring_2", + "ring_3", + "ring_4", + "little_1", + "little_2", + "little_3", + "little_4" + ], + "source_index_map_per_hand": [ + 0, + 4, + 3, + 2, + 1, + 8, + 7, + 6, + 5, + 12, + 11, + 10, + 9, + 16, + 15, + 14, + 13, + 20, + 19, + 18, + 17 + ] + } + }, + "camera": { + "opencv_fisheye4": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "k3", + "k4" + ], + "projection": "theta=atan(r); theta_d=theta*(1+k1*theta^2+k2*theta^4+k3*theta^6+k4*theta^8); source ReInterHand" + }, + "pinhole": { + "K": [ + 3, + 3 + ] + }, + "fisheye624": { + "parameters": [ + "f", + "cx", + "cy", + "k0", + "k1", + "k2", + "k3", + "k4", + "k5", + "p0", + "p1", + "s0", + "s1", + "s2", + "s3" + ] + }, + "rational8": { + "K": [ + 3, + 3 + ], + "distortion": [ + "k1", + "k2", + "p1", + "p2", + "k3", + "k4", + "k5", + "k6" + ] + } + }, + "segmentation": { + "segment/uint16_labels/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "polygons.jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mask.mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "note": "Registry for hand-warehouse/1.0. Read CONTRACT.md for field semantics. This is not a JSON Schema document or executable validator.", + "components": { + "mano/axis_angle61/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 61 + ], + "valid_shape": [ + "T", + 2 + ], + "unit": "m", + "angle_unit": "rad", + "coordinate_frame": "camera", + "layout": { + "pose_axis_angle": [ + 0, + 48 + ], + "shape": [ + 48, + 58 + ], + "translation": [ + 58, + 61 + ] + } + }, + "keypoints/uv/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 2 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "pixel", + "required_metadata": [ + "keypoint_schema" + ] + }, + "keypoints/xyz/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 2, + 21, + 3 + ], + "valid_shape": [ + "T", + 2, + 21 + ], + "unit": "m", + "required_metadata": [ + "keypoint_schema" + ] + }, + "depth/z_float32/v1": { + "storage": "mkv", + "dtype": "float32", + "shape": [ + "T", + "H", + "W" + ], + "valid_shape": [ + "T", + "H", + "W" + ], + "unit": "m", + "depth_type": "z", + "pixel_grid": "current_rgb", + "coordinate_frame": "current_rgb_camera", + "valid_storage": "mkv", + "allowed_storage_profiles": [ + "mkv/depth_float32_bits/v1" + ], + "allowed_valid_storage_profiles": [ + "mkv/bool_ffv1/v1" + ], + "required_metadata": [ + "storage", + "valid_storage", + "depth_origin" + ], + "depth_origin_values": [ + "measured", + "rendered", + "unknown" + ] + }, + "transform/se3/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention" + ] + }, + "object/rigid/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4, + 4 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "convention" + ] + }, + "camera/pinhole/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/rational8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/opencv_fisheye4/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3, + 3 + ], + "valid_shape": [ + "T" + ] + }, + "camera/fisheye624/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 15 + ], + "valid_shape": [ + "T" + ] + }, + "camera/distortion8/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 8 + ], + "valid_shape": [ + "T" + ] + }, + "camera/fisheye4_distortion/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 4 + ], + "valid_shape": [ + "T" + ] + }, + "object/joint_state/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "J" + ], + "valid_shape": [ + "T", + "J" + ], + "required_metadata": [ + "joint_order" + ], + "unit_rule": "revolute radians; prismatic metres; mixed types declared per joint" + }, + "object_keypoints/camera/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "K", + 3 + ], + "valid_shape": [ + "T", + "K" + ], + "unit": "m", + "coordinate_frame": "camera", + "required_metadata": [ + "keypoint_schema" + ] + }, + "object/dimensions/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + 3 + ], + "valid_shape": [ + "T" + ], + "unit": "m", + "required_metadata": [ + "dimensions_semantics" + ], + "axis_order": [ + "length", + "width", + "height" + ], + "scale_rule": "do not apply to mesh without source-supported size/scale relation" + }, + "object_keypoints/template/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "K", + 3 + ], + "valid_shape": [ + "K" + ], + "unit": "m", + "coordinate_frame": "object", + "static": true, + "required_metadata": [ + "keypoint_schema" + ] + }, + "mesh/obj/v1": { + "storage": "obj", + "unit": "m", + "static": true, + "valid_shape": [], + "dependencies": "MTL and textures retained under owning object" + }, + "rgb/uint8/v1": { + "storage": "mkv", + "dtype": "uint8", + "shape": [ + "T", + "H", + "W", + 3 + ], + "valid_shape": [ + "T" + ], + "color_order": "RGB", + "allowed_storage_profiles": [ + "mkv/mjpeg_copy/v1", + "mkv/source_copy/v1", + "mkv/h264_rgb_lossless/v1", + "mkv/ffv1_rgb/v1" + ], + "required_metadata": [ + "storage" + ] + }, + "contact/relations/v1": { + "storage": "jsonl", + "valid_shape": [ + "T" + ], + "frame_keys": [ + "frame_index", + "relations" + ], + "absence_semantics": "no record is not a negative contact annotation" + }, + "contact/vertex_region/v1": { + "storage": "pt", + "dtype": "bool", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id" + ], + "pilot_status": "defined_not_empirically_validated" + }, + "contact/vertex_distance/v1": { + "storage": "pt", + "dtype": "float32", + "shape": [ + "T", + "V" + ], + "valid_shape": [ + "T", + "V" + ], + "unit": "m", + "required_metadata": [ + "source_geometry_ref", + "target_geometry_ref", + "topology_id", + "distance_definition" + ], + "pilot_status": "defined_not_empirically_validated" + }, + "object/articulated/v1": { + "storage": "json", + "required_keys": [ + "parts", + "joints" + ], + "part_keys": [ + "part_id", + "parent_id", + "has_model", + "mesh_ref" + ], + "hierarchy_semantics": "declare mechanical articulation or semantic containment; containment alone does not imply joints", + "acyclic": true + }, + "segment/uint16_labels/v1": { + "storage": "mkv", + "dtype": "uint16", + "mapping": "instances.jsonl", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "reserved_codes": { + "0": "unassigned", + "65535": "ignore" + }, + "region_codes": [ + 1, + 65534 + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + }, + "segment/instance_polygons/v1": { + "storage": "jsonl", + "mapping": "instances.jsonl", + "frame_keys": [ + "frame_index", + "instances" + ], + "instance_keys": [ + "mask_value", + "polygons" + ], + "coordinate_unit": "pixel", + "overlap_allowed": true, + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "mapping_ref" + ], + "polygon_shape": [ + "N", + 2 + ], + "holes_supported": false + }, + "segment/foreground_intensity/v1": { + "storage": "mkv", + "dtype": "uint16", + "value_range": [ + 0, + 255 + ], + "normalization_scale": 0.00392156862745098, + "axes": [ + "T", + "height", + "width" + ], + "meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability", + "zero": "background", + "full_scale": "foreground", + "mapping": "foreground_category in component metadata", + "valid_shape": [ + "T" + ], + "required_metadata": [ + "segmentation_type", + "coverage", + "value_range", + "normalization_scale", + "foreground_category", + "entity_id", + "storage" + ], + "shape": [ + "T", + "H", + "W" + ], + "allowed_storage_profiles": [ + "mkv/uint16_ffv1/v1" + ] + } + }, + "storage_revision": "lossless-video-2026-09-18", + "sampling": { + "image": { + "single": { + "T": 1 + }, + "independent": { + "T": ">=2", + "required_frame_fields": [ + "sample_id", + "source_locator" + ], + "temporal_relationship": false + }, + "source_fps": null + }, + "video": { + "sampling_types": [ + "dense", + "sparse" + ] + } + }, + "storage_profiles": { + "mkv/mjpeg_copy/v1": { + "container": "matroska", + "codec": "mjpeg", + "method": "stream_copy_from_source_jpeg", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "source_jpeg_packet_sha256_exact", + "all_packet_count_order_and_dimensions_exact", + "deterministic_decoded_rgb_sample_exact", + "pilot_and_final_selected_whole_sequences_decoded_rgb_exact" + ], + "validation_policy": { + "id": "jpeg-packets-all-rgb-sample16/v1", + "sample_count_per_view": 16, + "short_views": "all_frames_if_T_less_than_16", + "fixed_indices": "0,T-1,T//4,T//2,3*T//4, deduplicated", + "remaining_indices": "sample without replacement to min(T,16) using Python random.Random(seed)", + "seed": "first 8 bytes of SHA256(sequence_id/camera_id/20260920), big-endian integer", + "report": "policy, exact selected frame indices, seed, separate packet and pixel coverage", + "legacy_all_frame_pixel_proofs": "still accepted; preserve historical evidence" + } + }, + "mkv/source_copy/v1": { + "container": "matroska", + "codec": "source_codec_declared_in_metadata", + "method": "stream_copy_only", + "logical_dtype": "uint8", + "decoded_pixel_format": "rgb24", + "validation": [ + "no_reencoding", + "all_decoded_rgb_frames_exact", + "presentation_frame_order_exact" + ] + }, + "mkv/h264_rgb_lossless/v1": { + "container": "matroska", + "codec": "h264", + "encoder": "libx264rgb", + "crf": 0, + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "gop": "declared_in_encoder_parameters", + "validation": [ + "all_decoded_rgb_frames_exact" + ], + "forbidden": [ + "lossy_rate_control", + "rgb_to_yuv420_subsampling" + ] + }, + "mkv/ffv1_rgb/v1": { + "container": "matroska", + "codec": "ffv1", + "decoded_pixel_format": "rgb24", + "logical_dtype": "uint8", + "validation": [ + "all_decoded_rgb_frames_exact" + ] + }, + "mkv/depth_float32_bits/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray16le", + "logical_dtype": "float32", + "logical_shape": [ + "T", + "H", + "W" + ], + "encoded_shape": [ + "T", + "H", + "2*W" + ], + "packing": "IEEE754 little-endian float32 bits; low uint16 in first W columns, high uint16 in last W columns", + "decode": "reinterpret_float32(uint32(low) | (uint32(high) << 16))", + "validation": [ + "all_float32_bits_exact_including_nan" + ] + }, + "mkv/bool_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_format": "gray", + "logical_dtype": "bool", + "stored_values": [ + 0, + 1 + ], + "validation": [ + "all_bool_values_exact" + ] + }, + "mkv/uint16_ffv1/v1": { + "container": "matroska", + "codec": "ffv1", + "pixel_formats": [ + "gray", + "gray16le" + ], + "logical_dtype": "uint16", + "gray_condition": "all values <=255; decode by exact uint8-to-uint16 promotion", + "validation": [ + "all_integer_values_exact" + ] + } + }, + "video_metadata": { + "required": [ + "profile", + "codec", + "pixel_format", + "encoded_size", + "decoder", + "encoder_parameters", + "source_lossy" + ], + "source_lossy_values": [ + true, + false, + "unknown" + ], + "timebase_role": "index_only", + "lossless_reference": "source compressed packets or fixed-decoder source pixels; depth uses normalized standard float32 bits", + "selection": "choose smaller complete candidate only after exact roundtrip validation" + } +} diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/full.log b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/full.log new file mode 100644 index 0000000000000000000000000000000000000000..65931a5b8d015b51eddb13bde0be744e71687977 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/full.log @@ -0,0 +1,53 @@ +Converted subject1/h1/0 +Converted subject2/h1/0 +Converted subject1/h1/6 +Converted subject2/h1/6 +Converted subject1/h1/3 +Converted subject2/h1/3 +Converted subject1/h1/7 +Converted subject2/h1/7 +Converted subject1/h1/4 +Converted subject2/h1/4 +Converted subject1/h1/2 +Converted subject2/h1/2 +Converted subject1/h1/1 +Converted subject1/h1/5 +Converted subject2/h1/1 +Converted subject1/o1/0 +Converted subject2/h1/5 +Converted subject1/o1/6 +Converted subject2/o1/0 +Converted subject1/o1/3 +Converted subject2/o1/6 +Converted subject1/o1/7 +Converted subject2/o1/3 +Converted subject1/o1/4 +Converted subject1/o1/2 +Converted subject2/o1/4 +Converted subject1/o1/1 +Converted subject1/o1/5 +Converted subject2/o1/2 +Converted subject1/o2/0 +Converted subject1/o2/6 +Converted subject2/o1/1 +Converted subject1/o2/3 +Converted subject2/o1/5 +Converted subject1/o2/7 +Converted subject2/o2/0 +Converted subject1/o2/4 +Converted subject2/o2/6 +Converted subject2/o2/3 +Converted subject1/o2/2 +Converted subject2/o2/4 +Converted subject2/o2/2 +Converted subject1/o2/1 +Converted subject1/o2/5 +Converted subject2/o2/1 +Converted subject1/k1/0 +Converted subject2/o2/5 +Converted subject1/k1/6 +Converted subject2/k1/0 +Converted subject1/k1/3 +Converted subject2/k1/6 +Converted subject1/k1/7 +Converted subject2/k1/3 diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/full.status b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/full.status new file mode 100644 index 0000000000000000000000000000000000000000..d53dae27bfc3a5a7669881f91405612f8b2495e4 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/full.status @@ -0,0 +1,7 @@ +START=2026-09-29T22:12:28+08:00 +WORKERS=2 CODEC_THREADS=4 SUBJECTS=1,2,3,4 CASA=false +CPU_BUDGET_PERCENT=80 LOGICAL_CPUS=40 +CGROUP=/user.slice/user-25044.slice/user@25044.service/app.slice/h2o-full-r1-20260929.scope +CPU_MAX=3200000 100000 + +RECONFIGURE=2026-09-30T10:20:40+08:00 REASON=user_requested_worker4_codec10 CPU_LIMIT=none diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/run-full.sh b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/run-full.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d27d5547332f029b9d2e92108469ad40bc121e6 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/run-full.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -u +base="$HOME/Datasets/uni-hoi-h2o-full-20260929-r1" +raw="$HOME/Datasets/Hand-Datasets-Raw/H2O" +cd "$HOME/Projects/uni-hoi-dataset" || exit 1 +mkdir -p "$base/scratch" +export TMPDIR="$base/scratch" PYTHONUNBUFFERED=1 +for n in 1 2 3 4; do test -s "$raw/raw/data/subject${n}_v1_1.tar.gz" || exit 2; done +test ! -e "$base/H2O/shared-v1.0" || exit 3 +cg=$(awk -F: '$1=="0" {print $3}' /proc/self/cgroup) +read -r quota period < "/sys/fs/cgroup$cg/cpu.max" +cpus=$(getconf _NPROCESSORS_ONLN) +printf 'START=%s\nWORKERS=2 CODEC_THREADS=4 SUBJECTS=1,2,3,4 CASA=false\nCPU_BUDGET_PERCENT=80 LOGICAL_CPUS=%s\nCGROUP=%s\nCPU_MAX=%s %s\n' "$(date -Is)" "$cpus" "$cg" "$quota" "$period" > "$base/full.status" +if [[ "$quota" == max ]] || (( quota * 100 > cpus * period * 80 )); then + printf 'EXIT=4 ERROR=CPU_QUOTA_NOT_ENFORCED\n' >> "$base/full.status" + exit 4 +fi +/usr/bin/time -v .venv/bin/python "$base/frozen-code/scripts/convert_h2o_v1.0.py" --root "$raw" --out "$base" --release-id shared-v1.0 --workers 2 --codec-threads 4 --mano-dir "$HOME/Projects/WiLoR/mano_data" > "$base/full.log" 2>&1 +code=$? +printf 'EXIT=%s END=%s\n' "$code" "$(date -Is)" >> "$base/full.status" +cat "/sys/fs/cgroup$cg/cpu.stat" >> "$base/full.status" +exit "$code" diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/check_dexycb_projection.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/check_dexycb_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..2774c004fc1359dea582135ec7171f600b33b336 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/check_dexycb_projection.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Check saved Dex-YCB source 3D joints against saved source 2D joints in sampled views.""" +import json +from pathlib import Path +import sys + +import numpy as np +import torch + +root = Path(sys.argv[1]) +report = json.loads((root / 'doc/validation/STRUCTURAL_AUDIT.json').read_text()) +checks = [] +for name in report['sampled_views']: + view = root / name + load = lambda path: torch.load(view / path, weights_only=True, map_location='cpu').numpy() + k = load('camera/intrinsic.pt') + xyz = load('annotation/keypoints/xyz.pt') + uv = load('annotation/keypoints/uv.pt') + valid = load('annotation/keypoints/xyz_valid.pt') & load('annotation/keypoints/uv_valid.pt') + z = xyz[..., 2] + valid &= np.isfinite(xyz).all(axis=-1) & np.isfinite(uv).all(axis=-1) & (z > 0) + z = np.where(valid, z, 1) + pred = np.stack((k[:, 0, 0, None, None] * xyz[..., 0] / z + k[:, 0, 2, None, None], + k[:, 1, 1, None, None] * xyz[..., 1] / z + k[:, 1, 2, None, None]), axis=-1) + errors = np.linalg.norm(pred[valid] - uv[valid], axis=-1) + checks.append(dict(view=name, points=int(errors.size), median_px=float(np.median(errors)) if errors.size else None, + p95_px=float(np.percentile(errors, 95)) if errors.size else None)) +(root / 'doc/validation/KEYPOINT_PROJECTION_QC.json').write_text(json.dumps({ + 'scope': 'Saved source 3D joints projected with saved color intrinsics vs saved source 2D joints; independent of hand mesh rendering.', + 'views': checks}, ensure_ascii=False, indent=2) + '\n') +print(json.dumps(checks, ensure_ascii=False), flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/config.json b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/config.json new file mode 100644 index 0000000000000000000000000000000000000000..76756f7bfa5e51a14928440034cf492eece3f6c2 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/config.json @@ -0,0 +1,15 @@ +{ + "root": "/home/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O", + "out": "/home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260929-r1", + "release_id": "shared-v1.0", + "limit": null, + "max_frames": null, + "mano_dir": "/home/xuzhefeng/Projects/WiLoR/mano_data", + "views": null, + "jpeg_full_check": false, + "workers": 2, + "codec_threads": 4, + "subjects": null, + "include_casa": false, + "archive": null +} diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_dexycb_v1.0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_dexycb_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..ed3f479787fae378b3d3b51ce2f58ccaebfd3d0f --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_dexycb_v1.0.py @@ -0,0 +1,349 @@ +#!/usr/bin/env python3 +"""Dex-YCB source annotations → CONTRACT.md v1.0. No derived annotations.""" +import io +import re +import shutil +import tarfile +import tempfile +from pathlib import Path + +import numpy as np +from PIL import Image +import yaml + +from warehouse_v1_0 import (View, build_record, find_file, locator, mano_models, mesh_asset, + model_profile, parser, pca_to_axis_angle, release, roots, safe_member, sequence_dir) + +IMG_W, IMG_H = 640, 480 + +class _Loader(yaml.SafeLoader): + pass + + +_Loader.add_constructor("tag:yaml.org,2002:python/tuple", + lambda l, n: tuple(l.construct_sequence(n))) + + +def yaml_load_bytes(data: bytes): + return yaml.load(io.BytesIO(data), Loader=_Loader) + + +class Calibration: + def __init__(self, dexycb_root: Path): + self.intrinsics = {} # serial -> {fx,fy,cx,cy,w,h} + self.extrinsics = {} # group -> {serial: [12] 行优先 3×4 cam→world} + self.betas = {} # mano_calib_name -> [10] + calib_dir = dexycb_root / "calibration" + if calib_dir.is_dir(): + self._load((p.as_posix(), p.read_bytes()) + for p in sorted(calib_dir.rglob("*")) if p.is_file()) + else: + tar_path = dexycb_root / "calibration.tar.gz" + if not tar_path.exists(): + raise FileNotFoundError(f"no calibration/ nor calibration.tar.gz in {dexycb_root}") + with tarfile.open(tar_path, "r:gz") as tf: + self._load((m.name, tf.extractfile(m).read()) for m in tf if m.isfile()) + + _RE_INTR = re.compile(r"(?:^|/)intrinsics/(\d+)_\d+x\d+\.yml$") + _RE_EXTRA = re.compile(r"(?:^|/)extrinsics_(\d{8}_\d{6})/extrinsics\.yml$") + _RE_MANO = re.compile(r"(?:^|/)mano_(\d{8}_\d{6}_subject-\d{2}_right)/mano\.yml$") + + def _load(self, files): + for rel, data in files: + m = self._RE_INTR.search(rel) + if m: + c = yaml_load_bytes(data)["color"] + self.intrinsics[m.group(1)] = {"fx": float(c["fx"]), "fy": float(c["fy"]), + "cx": float(c["ppx"]), "cy": float(c["ppy"]), + "w": IMG_W, "h": IMG_H} + continue + m = self._RE_EXTRA.search(rel) + if m: + raw = yaml_load_bytes(data)["extrinsics"] + self.extrinsics[m.group(1)] = { + str(s): [float(x) for x in np.asarray(v).ravel()] for s, v in raw.items()} + continue + m = self._RE_MANO.search(rel) + if m: + self.betas[m.group(1)] = [float(b) for b in yaml_load_bytes(data)["betas"]] + + + +def calibration_locator(path, member, **extra): + if path.is_dir(): + return locator(path / member.removeprefix('calibration/'), **extra) + return locator(path, member, **extra) + + +def prepare_models(root, destination): + archive = find_file(root, 'models.tar.gz') + if archive is None: + return {}, None + pattern = re.compile(r'^models/(\d{3}_[a-z0-9_]+)/(textured_simple\.obj(?:\.mtl)?|texture_map\.png)$') + names = set() + with tarfile.open(archive, 'r|gz') as tf: + for member in tf: + match = pattern.fullmatch(member.name) + if member.isfile() and match: + names.add(match[1]) + path = safe_member(destination, '/'.join(match.groups())) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(tf.extractfile(member).read()) + if len(names) != 21: + raise ValueError('expected all 21 source YCB model directories') + return {i: destination / name for i, name in enumerate(sorted(names), 1)}, archive + + +def convert_view(path, args, seq, serial, frames, meta, meta_loc, calib, calib_path, models, assets, asset_archive): + total = int(meta.get('num_frames', max(frames) + 1)) + ids = list(range(min(total, args.max_frames) if args.max_frames else total)) + for f in ids: + frames.setdefault(f, {}) + if not ids: + raise ValueError('no RGB frames') + source_rows = [] + for f in ids: + row = frames[f] + source_rows.append(dict(source_frame_id=f, sync_id=f'{seq}:{f}', + source_locator=row['color'][1] if 'color' in row else (meta_loc | {'source_frame_id': f, 'missing_rgb': True}), annotation_matches={ + 'labels': {'source_frame_id': f, 'source_timestamp_ns': None, 'clock_domain': None, + 'match_method': 'index_map', 'delta_ns': None, 'source_locator': row['labels'][1]} + for _ in [0] if 'labels' in row}, + component_sources={k: v[1] for k, v in row.items()})) + view = View(path, 'dex-ycb', args.release_id, seq, serial, source_rows, + sampling='dense' if ids == list(range(ids[0], ids[-1] + 1)) else 'sparse') + view.valid_rules = { + 'mano': 'Source pose_m present and not all zero; side model/calibration available', + 'keypoints': 'Corresponding joint_2d/joint_3d present; whole-hand all -1 is missing, broadcast to its 21 points', + 'pose': 'Source pose_y for this ycb_ids slot present and not an all-zero matrix', + 'segment': 'Source seg array provided for this frame; region codes and entity references validated', + 'relations': 'Source sequence ycb_grasp_ind resolves through ycb_ids; broadcast sequence grasp to selected frames', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'exo' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} + subject = re.search(r'subject-(\d+)', seq) + if subject and 1 <= int(subject[1]) <= 10: + index = int(subject[1]) + view.meta.update(split='val' if index == 7 else 'test' if index in (8, 9) else 'train', + split_scheme='Dex-YCB/s1', split_source_locator={ + 'url': 'https://github.com/NVlabs/dex-ycb-toolkit/blob/master/dex_ycb_toolkit/dex_ycb.py', + 'rule': 's1 unseen-subject: 01-06/10 train, 07 val, 08-09 test'}) + view.meta.pop('split_reason', None) + view.rgb([frames[f]['color'][0] if 'color' in frames[f] else None for f in ids], {'frames_ref': 'camera/frames.jsonl'}) + n = len(ids) + intr = calib.intrinsics.get(serial) + K = None if intr is None else np.array([[intr['fx'], 0, intr['cx']], [0, intr['fy'], intr['cy']], [0, 0, 1]]) + ext = calib.extrinsics.get(str(meta['extrinsics']), {}).get(serial) + E = None + if ext is not None: + E = np.eye(4) + E[:3] = np.asarray(ext).reshape(3, 4) + E = np.linalg.inv(E) + view.camera(K, calibration_locator(calib_path, f'calibration/intrinsics/{serial}_640x480.yml'), E, + calibration_locator(calib_path, f'calibration/extrinsics_{meta["extrinsics"]}/extrinsics.yml', + conversion='inverse of source T_world_from_camera')) + sides = meta.get('mano_sides') + if sides not in (['left'], ['right']): + raise ValueError(f'expected exactly one anatomical source hand: {sides}') + side = sides[0] + slot = ['left', 'right'].index(side) + cal_name = meta['mano_calib'][0] if isinstance(meta['mano_calib'], list) else meta['mano_calib'] + labels = [dict(np.load(frames[f]['labels'][0])) if 'labels' in frames[f] else {} for f in ids] + label_loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources.labels'} + motion = np.full((n, 2, 61), np.nan, np.float32) + mv = np.zeros((n, 2), bool) + if side in models and any('pose_m' in lab for lab in labels): + for i, lab in enumerate(labels): + if 'pose_m' not in lab: + continue + pose = np.asarray(lab['pose_m']).reshape(51) + if not np.any(pose): # Official Dex-YCB missing-pose sentinel, independent of joints/seg. + continue + motion[i, slot] = np.r_[pose[:3], pca_to_axis_angle(pose[3:48], models[side]), + calib.betas[cal_name], pose[48:51]] + mv[i, slot] = True + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], label_loc, model_profile=model_profile(models), + calibration_source=calibration_locator(calib_path, f'calibration/mano_{cal_name}/mano.yml'), + provenance={'kind': 'format_conversion', 'method': 'source PCA @ hands_components + hands_mean; explicit axis-angle consumed with flat_hand_mean=true'}) + elif any('pose_m' in lab for lab in labels): + view.absent('mano', 'Source PCA exists; provide --mano-dir to expand it', 'dependency_missing') + else: + view.absent('mano', 'No source pose_m field') + for source_key, key, dim, unit in [('joint_2d', 'uv', 2, 'pixel'), ('joint_3d', 'xyz', 3, 'm')]: + if not any(source_key in x for x in labels): + view.absent('keypoints_' + key, 'No source ' + source_key) + continue + points = np.full((n, 2, 21, dim), np.nan, np.float32) + valid = np.zeros((n, 2, 21), bool) + for i, lab in enumerate(labels): + if source_key not in lab: + continue + p = np.asarray(lab[source_key]).reshape(21, dim) + points[i, slot] = p + valid[i, slot] = not np.all(p == -1) # Official sentinel covers the whole source hand. + # An individual off-image point (-1, -1) is not evidence of missing annotation. + view.tensor('keypoints_' + key, f'keypoints/{key}/v1', f'annotation/keypoints/{key}.pt', + points, valid, ['T', 'hand', 'keypoint', 'coordinate'], label_loc, + keypoint_schema='mano21/v1', unit=unit) + ycb_ids = [int(x) for x in meta['ycb_ids']] + for j, oid in enumerate(ycb_ids): + entity = f'ycb_{oid:02d}' + view.object(entity, meta_loc, source_object_id=oid, category_id=oid) + poses = np.full((n, 4, 4), np.nan, np.float32) + valid = np.zeros(n, bool) + for i, lab in enumerate(labels): + if 'pose_y' in lab: + pose = np.asarray(lab['pose_y']) + if pose.shape != (len(ycb_ids), 3, 4): + raise ValueError('pose_y shape differs from ycb_ids') + if np.any(pose[j]): # Official all-zero missing object pose sentinel. + poses[i] = np.eye(4) + poses[i, :3] = pose[j] + valid[i] = True + if any('pose_y' in lab for lab in labels): + view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', + poses, valid, ['T', 'row', 'column'], label_loc, + convention='T_camera_from_object', unit='m') + else: + view.absent('pose_' + entity, 'No source pose_y field') + if oid in assets: + mesh_asset(view, entity, assets[oid], assets[oid] / 'textured_simple.obj', + locator(asset_archive, f'models/{assets[oid].name}/textured_simple.obj')) + else: + view.absent('mesh_' + entity, 'models.tar.gz unavailable', 'not_downloaded') + if any('seg' in lab for lab in labels): + mask_rows = [] + width, height = view.meta['camera']['image_size'] + for i, lab in enumerate(labels): + values = np.unique(lab.get('seg', np.zeros((height, width), np.uint8))) + mappings = [] + for value in values: + value = int(value) + if value == 0: + continue + if value != 255 and value not in ycb_ids: + raise ValueError(f'unknown Dex-YCB region value {value}') + mappings.append(dict(mask_value=value, category_id='hand' if value == 255 else value, + entity_id='hand_' + side if value == 255 else f'ycb_{value:02d}', part_id=None, + source_instance_id=value)) + mask_rows.append(dict(frame_index=i, labels=mappings)) + view.raster('segment', (lab.get('seg', np.zeros((height, width), np.uint16)) for lab in labels), + ['seg' in lab for lab in labels], label_loc, mask_rows) + view.meta['components']['segment'].update(coverage={'kind': 'selected_entities', + 'entities': ['hand_' + side] + [f'ycb_{o:02d}' for o in ycb_ids]}, source_zero_meaning='background') + else: + view.absent('segment', 'No source seg field') + if any('aligned_depth_to_color' in frames[f] for f in ids): + def depths(): + width, height = view.meta['camera']['image_size'] + for f in ids: + item = frames[f].get('aligned_depth_to_color') + if item is None: + yield np.full((height, width), np.nan, np.float32) + else: + with Image.open(item[0]) as im: + yield np.asarray(im).astype(np.float32) / 1000.0 + view.raster('depth', depths(), None, {'frames_ref': 'camera/frames.jsonl', + 'source_field': 'component_sources.aligned_depth_to_color', 'conversion': 'millimetres to metres'}) + else: + view.absent('depth', 'No source aligned_depth_to_color frames') + grasp = meta.get('ycb_grasp_ind') + if grasp is not None: + if not 0 <= int(grasp) < len(ycb_ids): + raise ValueError('invalid ycb_grasp_ind') + relation = dict(relation_type='grasp', subject_id='hand_' + side, + object_id=f'ycb_{ycb_ids[int(grasp)]:02d}', status='positive', source_locator=meta_loc, + provenance={'kind': 'source', 'method': 'sequence ycb_grasp_ind resolved through ycb_ids; not per-frame contact'}) + view.relations([{'frame_index': i, 'relations': [relation]} for i in range(n)], np.ones(n, bool), meta_loc) + else: + view.absent('relations', 'No source grasp/contact relation') + return view.finish() + + +MEMBER = re.compile(r'^([^/]+)/(\d{8}_\d{6})/(meta\.yml|(\d{12})/(color|labels|aligned_depth_to_color)_(\d+)\.(jpg|npz|png))$') + + +def convert_archive(archive, args, out, calib, calib_path, models, assets, asset_archive): + selected_views = set(args.views.split(',')) if args.views else None + done = 0 + current, meta, meta_loc, rows = None, None, None, {} + with tempfile.TemporaryDirectory(prefix='dex-source-') as wd: + work = Path(wd) + def flush(): + nonlocal done + if not rows: + return + seq = archive.name.split('.tar')[0] + '_' + current + reports = {} + with sequence_dir(out, seq) as target: + for serial, frames in sorted(rows.items()): + reports[serial] = convert_view(target / serial, args, seq, serial, frames, meta, + meta_loc, calib, calib_path, models, assets, asset_archive) + build_record(out, seq, reports) + for staged in list(work.iterdir()): + if staged.is_dir(): + shutil.rmtree(staged) + else: + staged.unlink() + done += 1 + print(f'Converted {seq}', flush=True) + with tarfile.open(archive, 'r|gz') as tf: + for member in tf: + match = MEMBER.fullmatch(member.name) + if not member.isfile() or not match: + continue + seq = match[2] + if seq != current: + flush() + if args.limit and done >= args.limit: + break + current, meta, meta_loc, rows = seq, None, None, {} + data_kind = match[3] + if data_kind == 'meta.yml': + data = tf.extractfile(member).read() + meta = yaml_load_bytes(data) + meta_loc = locator(archive, member.name, data) + continue + serial, kind, f = match[4], match[5], int(match[6]) + if selected_views and serial not in selected_views or args.max_frames and f >= args.max_frames: + continue + data = tf.extractfile(member).read() + dest = safe_member(work, member.name) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(data) + row = rows.setdefault(serial, {}).setdefault(f, {}) + if kind in row: + raise ValueError('duplicate archive frame') + row[kind] = (dest, locator(archive, member.name, data)) + else: + flush() + return done + + +def main(argv=None): + p = parser('dex-ycb', __doc__) + p.add_argument('--subjects') + args = p.parse_args(argv) + archives = sorted({a for r in roots(args.root) for a in r.glob('*-subject-*.tar.gz')}) + if args.subjects: + subjects = {s.strip().zfill(2) for s in args.subjects.split(',')} + archives = [a for a in archives if re.search(r'subject-(\d+)', a.name)[1] in subjects] + if not archives: + p.error('no Dex-YCB subject archives found') + cp = find_file(args.root, 'calibration.tar.gz') or find_file(args.root, 'calibration') + if cp is None: + p.error('calibration source missing') + calib = Calibration(cp.parent) + models = mano_models(args.mano_dir) + out = release(args, 'dex-ycb') + with tempfile.TemporaryDirectory(prefix='dex-models-') as wd: + assets, asset_archive = prepare_models(args.root, Path(wd)) + for archive in archives: + convert_archive(archive, args, out, calib, cp, models, assets, asset_archive) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_h2o_v1.0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_h2o_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..f55e39721c261ad4483ad9ff45d3e15de817cbdf --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_h2o_v1.0.py @@ -0,0 +1,527 @@ +#!/usr/bin/env python3 +"""H2O native RGB-D, MANO, joints and objects → CONTRACT.md v1.0 (no rendered masks).""" +from concurrent.futures import ThreadPoolExecutor +import json +import os +import re +import shutil +import tarfile +import tempfile +from pathlib import Path +import zipfile + +# Bound native libraries before loading NumPy/Torch; each worker still uses independent FFmpeg processes. +for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + +import numpy as np +from PIL import Image +import torch + +from warehouse_v1_0 import (View, build_record, check_mesh, find_file, locator, mano_models, mesh_asset, + model_profile, parser, release, roots, safe_member, sequence_dir, sha256) + +OBJECTS = {1: 'book', 2: 'espresso', 3: 'lotion', 4: 'spray', + 5: 'milk', 6: 'cocoa', 7: 'chips', 8: 'cappuccino'} +MEMBER = re.compile(r'^(?:h2o_CASA/)?(subject\d+)/([^/]+)/(\d+)/(cam\d)/(.+)$') +FRAME = re.compile(r'(rgb|depth|cam_pose|hand_pose|hand_pose_mano|obj_pose|obj_pose_rt)/(\d+)\.(png|jpg|txt)$') + + +def load_splits(root): + archive = find_file(root, 'label_split.zip') + result = {} + if archive is not None: + with zipfile.ZipFile(archive) as z: + for split in ('train', 'val', 'test'): + member = f'label_split/action_{split}.txt' + for line_no, line in enumerate(z.read(member).decode().splitlines(), 1): + fields = line.split() + if len(fields) < 2 or fields[1] == 'path': + continue + key = fields[1] + if key in result and result[key][0] != split: + raise ValueError('conflicting official splits') + result[key] = (split, locator(archive, member, record=line_no)) + return result + + +def load_assets(root, work): + archive = find_file(root, 'object.zip') + if archive is None: + return {}, None + with zipfile.ZipFile(archive) as z: + for member in z.infolist(): + if member.is_dir(): + continue + path = safe_member(work, member.filename) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(z.read(member)) + result = {} + for oid, name in OBJECTS.items(): + directory = work / 'object' / name + aliases = [] + # Source cocoa.obj -> ovomaltine.mtl -> cocoa.png, but the ZIP names the + # supplied texture ovomaltine.png. Keep all originals and add a byte-identical alias. + if name == 'cocoa' and not (directory / 'cocoa.png').exists(): + mtl = directory / 'ovomaltine.mtl' + if mtl.is_file() and 'map_Kd cocoa.png' in mtl.read_text().splitlines(): + texture = directory / 'ovomaltine.png' + shutil.copyfile(texture, directory / 'cocoa.png') + aliases.append({'file': 'cocoa.png', 'sha256': sha256(texture), + 'source': locator(archive, 'object/cocoa/ovomaltine.png')}) + candidates = list(directory.glob('*.obj')) + if len(candidates) != 1: + raise ValueError(f'expected one source OBJ for {name}') + check_mesh(candidates[0], directory) # Fail before decoding any large subject archive. + result[oid] = (directory, candidates[0], aliases) + return result, archive + + +def convert_view(path, args, seq, cam, rows, intr, splits, models, assets, asset_archive): + codec_threads = getattr(args, 'codec_threads', 1) + ids = list(range(min(rows), max(rows) + 1)) + for f in ids: + rows.setdefault(f, {}) + n = len(ids) + if not n: + raise ValueError('no RGB frames') + split, split_loc = splits.get(seq, ('unknown', None)) + frame_rows = [dict(source_frame_id=f, sync_id=f'{seq}:{f}', source_locator=rows[f]['rgb'][1] if 'rgb' in rows[f] else {'sequence': seq, 'camera': cam, 'source_frame_id': f, 'missing_rgb': True}, + component_sources={k: item[1] for k, item in rows[f].items()}, + annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None) + for k in rows[f] if k != 'rgb'}) for f in ids] + view = View(path, 'H2O', args.release_id, seq.replace('/', '_'), cam, frame_rows, split=split) + view.valid_rules = { + 'mano': 'Per-hand hand_pose_mano flag equals 1; corresponding side model available', + 'keypoints': "Per-hand hand_pose flag equals 1, broadcast to that hand's 21 source points independently of MANO", + 'pose': 'Source obj_pose_rt class equals this nonzero object class', + 'points': 'Source obj_pose class equals this nonzero object class, broadcast to its 21 points', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'ego' if cam == 'cam4' else 'exo' if cam in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} + if split_loc: + view.meta.update(split_scheme='official_action_split', split_source_locator=split_loc) + # In the measured 275 H2O views, exact FFV1 was always smaller than exact H.264. + view.rgb([rows[f]['rgb'][0] if 'rgb' in rows[f] else None for f in ids], + {'frames_ref': 'camera/frames.jsonl'}, ffv1_first=True, codec_threads=codec_threads) + loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} + if intr is not None: + fx, fy, cx, cy, width, height = np.loadtxt(intr[0]).ravel() + if [int(width), int(height)] != view.meta['camera']['image_size']: + raise ValueError('source intrinsics resolution mismatch') + K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) + view.camera(K, intr[1]) + camps = np.full((n, 4, 4), np.nan, np.float32) + cv = np.zeros(n, bool) + data = [] + for i, f in enumerate(ids): + lab = {k: np.loadtxt(item[0]).ravel() for k, item in rows[f].items() if k not in ('rgb', 'depth')} + data.append(lab) + if 'cam_pose' in lab: + camps[i] = np.linalg.inv(lab['cam_pose'].reshape(4, 4)) + cv[i] = True + if cv.any(): + view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', camps, cv, + ['T', 'row', 'column'], loc, convention='T_camera_from_world', + source_convention='T_world_from_camera') + motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) + points, pv = np.full((n, 2, 21, 3), np.nan, np.float32), np.zeros((n, 2, 21), bool) + object_ids = set() + for i, lab in enumerate(data): + if 'hand_pose_mano' in lab: + hands = lab['hand_pose_mano'].reshape(2, 62) + for side, row in enumerate(hands): + if row[0] not in (0, 1): + raise ValueError('unexpected H2O MANO presence flag') + if row[0] == 1: + motion[i, side] = np.r_[row[4:52], row[52:62], row[1:4]] + mv[i, side] = True + if 'hand_pose' in lab: + hands = lab['hand_pose'].reshape(2, 64) + for side, row in enumerate(hands): + if row[0] not in (0, 1): + raise ValueError('unexpected H2O keypoint presence flag') + if row[0] == 1: + points[i, side] = row[1:].reshape(21, 3) + pv[i, side] = True + for key in ('obj_pose', 'obj_pose_rt'): + if key in lab and lab[key][0] != 0: + object_ids.add(int(lab[key][0])) + if any('hand_pose_mano' in lab for lab in data): + if len(models) == 2: + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) + else: + view.absent('mano', 'Source parameters exist; --mano-dir must identify both model profiles', 'dependency_missing') + if any('hand_pose' in lab for lab in data): + view.tensor('keypoints_xyz', 'keypoints/xyz/v1', 'annotation/keypoints/xyz.pt', points, pv, + ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='m') + for oid in sorted(object_ids): + if oid not in OBJECTS: + raise ValueError(f'unknown H2O object class {oid}') + entity = OBJECTS[oid] + view.object(entity, loc, category_id=oid, source_object_id=oid) + poses, ov = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + pts, kv = np.full((n, 21, 3), np.nan, np.float32), np.zeros((n, 21), bool) + for i, lab in enumerate(data): + if 'obj_pose_rt' in lab and lab['obj_pose_rt'][0] == oid: + poses[i] = lab['obj_pose_rt'][1:].reshape(4, 4) + ov[i] = True + if 'obj_pose' in lab and lab['obj_pose'][0] == oid: + pts[i] = lab['obj_pose'][1:].reshape(21, 3) + kv[i] = True + if ov.any(): + view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', + poses, ov, ['T', 'row', 'column'], loc, convention='T_camera_from_object', unit='m') + if kv.any(): + view.tensor('points_' + entity, 'object_keypoints/camera/v1', + f'annotation/object/{entity}/keypoints/xyz.pt', pts, kv, + ['T', 'keypoint', 'coordinate'], loc, keypoint_schema='H2O_official_object21', + keypoint_names=['center'] + [f'corner_{i}' for i in range(8)] + [f'edge_midpoint_{i}' for i in range(12)], + source_order='official obj_point_order.jpg: center, 8 corners, 12 edge midpoints', unit='m') + if oid in assets: + directory, obj, aliases = assets[oid] + asset_loc = locator(asset_archive, f'object/{entity}/{obj.name}') + if aliases: + asset_loc['texture_aliases'] = aliases + mesh_asset(view, entity, directory, obj, asset_loc) + else: + view.absent('mesh_' + entity, 'Source object.zip unavailable', 'not_downloaded') + if any('depth' in rows[f] for f in ids): + width, height = view.meta['camera']['image_size'] + def depths(): + for f in ids: + item = rows[f].get('depth') + if item: + with Image.open(item[0]) as im: + yield np.asarray(im).astype(np.float32) / 1000.0 + else: + yield np.full((height, width), np.nan, np.float32) + view.raster('depth', depths(), None, loc | {'source_field': 'component_sources.depth', + 'definition': 'https://github.com/taeinkwon/h2oplayer/blob/main/utils.py', + 'conversion': 'registered millimetre camera-Z to metres; no viewer range clipping'}, + codec_threads=codec_threads) + else: + view.absent('depth', 'No source depth frames') + view.absent('segment', 'H2O provides no native segmentation; rendering deferred to v2.0') + view.absent('relations', 'No source contact/grasp annotation') + return view.finish() + + +def convert_archive(archive, args, out, splits, models, assets, asset_archive): + selected_views = set(args.views.split(',')) if args.views else None + subjects = {'subject' + s.strip() for s in args.subjects.split(',')} if args.subjects else None + current, rows, intrinsics, done = None, {}, {}, 0 + with tempfile.TemporaryDirectory(prefix='h2o-source-') as wd: + work = Path(wd) + def flush(): + nonlocal done + if not rows: + return + seq = '/'.join(current) + reports, pending = {}, {} + for cam, frames in sorted(rows.items()): + existing = out / 'data' / seq.replace('/', '_') / cam + if (existing / 'metainfo.json').is_file(): + old_frames = [json.loads(line) for line in (existing / 'camera/frames.jsonl').read_text().splitlines()] + if [f['source_frame_id'] for f in old_frames] != list(range(min(frames), max(frames) + 1)): + raise ValueError('existing view has different sampling; choose a new release-id') + for frame in old_frames: + incoming = frames.get(frame['source_frame_id'], {}) + previous = frame.get('component_sources', {}) + if set(previous) != set(incoming) or any(previous[k].get('sha256') != v[1].get('sha256') for k, v in incoming.items()): + raise ValueError('duplicate H2O view differs from the published source; choose a new release-id') + else: + pending[cam] = frames + if pending: + with sequence_dir(out, seq.replace('/', '_')) as target: + for cam, frames in pending.items(): + reports[cam] = convert_view(target / cam, args, seq, cam, frames, + intrinsics.get(cam), splits, models, assets, asset_archive) + build_record(out, seq.replace('/', '_'), reports) + for staged in list(work.iterdir()): + if staged.is_dir(): + shutil.rmtree(staged) + else: + staged.unlink() + done += 1 + print(f'{"Converted" if pending else "Verified existing"} {seq}', flush=True) + # Uncompressed CASA supports seeking over large frames; gzip is single-pass. + mode = 'r:' if archive.suffix == '.tar' else 'r|gz' + with tarfile.open(archive, mode) as tf: + for member in tf: + match = MEMBER.fullmatch(member.name) + if not member.isfile() or not match: + continue + subj, scene, seq, cam, tail = match.groups() + if subjects and subj not in subjects: + continue + key = (subj, scene, seq) + if key != current: + flush() + if args.limit and done >= args.limit: + break + current, rows, intrinsics = key, {}, {} + if selected_views and cam not in selected_views: + continue + frame = FRAME.fullmatch(tail) + if tail != 'cam_intrinsics.txt' and not frame: + continue + if frame and args.max_frames and int(frame[2]) >= args.max_frames: + continue + data = tf.extractfile(member).read() + dest = safe_member(work, member.name) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(data) + item = (dest, locator(archive, member.name, data)) + if tail == 'cam_intrinsics.txt': + intrinsics[cam] = item + else: + kind, f = frame[1], int(frame[2]) + row = rows.setdefault(cam, {}).setdefault(f, {}) + if kind in row: + raise ValueError('duplicate H2O frame') + row[kind] = item + else: + flush() + return done + + +def main(argv=None): + p = parser('H2O', __doc__) + p.set_defaults(release_id='shared-v1.0') + p.add_argument('--workers', type=int, choices=range(1, 5), default=1, + help='Independent subject archives in parallel, 1..4; benchmark before using >2') + p.add_argument('--codec-threads', type=int, choices=(1, 2, 4, 8), default=4, + help='FFV1 slice threads per encode; 4 chosen from full-view RGB benchmark') + p.add_argument('--subjects') + p.add_argument('--include-casa', action='store_true') + p.add_argument('--archive', type=Path, help='Convert one explicit source archive') + args = p.parse_args(argv) + if args.include_casa and args.workers != 1: + p.error('CASA can share sequence IDs with subject archives; convert it sequentially in a separate release') + archives = [args.archive.expanduser()] if args.archive else sorted( + {a for root in roots(args.root) for a in root.glob('subject*_v1_1.tar.gz')}) + if args.subjects and not args.archive: + requested = {'subject' + s.strip() for s in args.subjects.split(',')} + archives = [arc for arc in archives if arc.name.split('_', 1)[0] in requested] + if args.include_casa: + casa = find_file(args.root, 'h2o_CASA.tar') + if casa: + archives.append(casa) + if not archives: + p.error('no H2O archives found') + out = release(args, 'H2O') + source_mapping = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/h2o-RAW_TO_SHARED.md', + Path(__file__).resolve().parents[1] / 'doc/RAW_TO_SHARED.md', + out / 'doc/RAW_TO_SHARED.md') if p.is_file()) + mapping = out / 'doc/RAW_TO_SHARED.md' + if mapping.exists() and mapping.read_bytes() != source_mapping.read_bytes(): + raise ValueError('RAW_TO_SHARED.md changed; choose a new release-id') + if not mapping.exists(): + shutil.copyfile(source_mapping, mapping) + torch.set_num_threads(1) + models, splits = mano_models(args.mano_dir), load_splits(args.root) + with tempfile.TemporaryDirectory(prefix='h2o-assets-') as wd: + assets, asset_archive = load_assets(args.root, Path(wd)) + def convert_one(archive): + return convert_archive(archive, args, out, splits, models, assets, asset_archive) + if args.workers == 1: + for archive in archives: + convert_one(archive) + else: + with ThreadPoolExecutor(max_workers=args.workers) as pool: + for archive, count in zip(archives, pool.map(convert_one, archives), strict=True): + print(f'Archive {archive.name}: {count} sequences', flush=True) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) + +# TODO(v2.0): 以下旧 MANO 网格和渲染分割代码仅保留备查;v1.0 不生成标注。 +# def load_mano_model(path: Path): +# """MPI MANO pkl → numpy 字典。shapedirs 在 pkl 内为 chumpy Select(对 (778,3,20) 基 +# 底 flat 选取前 10 个 shape 分量;idxs 已核实等价于 base[:,:,:10])。""" +# with open(path, "rb") as f: +# d = _ManoUnpickler(f, encoding="latin1").load() +# sd = d["shapedirs"] +# base = np.asarray(sd.a.x, np.float64) # (778, 3, 20) +# shapedirs = base.reshape(-1)[np.asarray(sd.idxs)].reshape(base.shape[0], 3, -1) +# jreg = d["J_regressor"] +# jreg = np.asarray(jreg.todense()) if hasattr(jreg, "todense") else np.asarray(jreg) +# return {"v_template": np.asarray(d["v_template"], np.float64), +# "shapedirs": shapedirs, +# "posedirs": np.asarray(d["posedirs"], np.float64), +# "weights": np.asarray(d["weights"], np.float64), +# "J_regressor": np.asarray(jreg, np.float64), +# "kintree": np.asarray(d["kintree_table"], np.int64), +# "faces": np.asarray(d["f"], np.int64)} +# +# +# def rodrigues(r): +# """axis-angle (N,3) → 旋转矩阵 (N,3,3)。公式 I + sinθ·K + (1−cosθ)·K²(已对 scipy 核验)。""" +# r = np.asarray(r, np.float64).reshape(-1, 3) +# th = np.linalg.norm(r, axis=1) +# R = np.zeros((len(r), 3, 3)) +# nz = th > 1e-12 +# R[~nz] = np.eye(3) +# k = r[nz] / th[nz, None] +# K = np.zeros((len(k), 3, 3)) +# K[:, 0, 1], K[:, 0, 2], K[:, 1, 2] = -k[:, 2], k[:, 1], -k[:, 0] +# K[:, 1, 0], K[:, 2, 0], K[:, 2, 1] = k[:, 2], -k[:, 1], k[:, 0] +# s, c = np.sin(th[nz])[:, None, None], np.cos(th[nz])[:, None, None] +# R[nz] = np.eye(3) + s * K + (1 - c) * (K @ K) +# return R +# +# +# def _mano_chain(model, betas, pose): +# """返回 (v_shaped, J, Rs, G):G 为 16 个关节的全局变换(平移列 = 关节位置)。""" +# v = model["v_template"] + np.einsum("nkc,c->nk", model["shapedirs"], betas) +# J = model["J_regressor"] @ v +# Rs = rodrigues(np.asarray(pose, np.float64).reshape(16, 3)) +# kt = model["kintree"] +# G = np.zeros((16, 4, 4)) +# for j in range(16): +# p = kt[0, j] if j else -1 +# loc = np.eye(4) +# loc[:3, :3] = Rs[j] +# loc[:3, 3] = J[j] - (J[p] if j else 0.0) +# G[j] = loc if not j else G[p] @ loc +# return v, J, Rs, G +# +# +# def mano_forward(model, betas, pose, transl): +# """MANO LBS 前向(经典蒙皮 M_j = G_j·G0_j⁻¹;对 hand_pose 21 关节实证 0.0 mm)。 +# pose: 48 axis-angle([0:3] 全局);返回相机系米顶点 (778,3)。""" +# v, J, Rs, G = _mano_chain(model, betas, pose) +# lrot = (Rs[1:] - np.eye(3)).ravel() +# v_posed = v + np.einsum("nkc,c->nk", model["posedirs"], lrot) +# kt = model["kintree"] +# G0 = np.zeros((16, 4, 4)) +# for j in range(16): +# p = kt[0, j] if j else -1 +# loc = np.eye(4) +# loc[:3, 3] = J[j] - (J[p] if j else 0.0) +# G0[j] = loc if not j else G0[p] @ loc +# M = np.einsum("nj,jab->nab", model["weights"], G @ np.linalg.inv(G0)) +# out = np.einsum("nab,nb->na", M[:, :3, :3], v_posed) + M[:, :3, 3] +# return out + np.asarray(transl, np.float64) +# +# +# def mano_chain_joints(model, betas, pose, transl): +# """16 个关节位置(相机系米)= 链平移列;自检用。""" +# _, _, _, G = _mano_chain(model, betas, pose) +# return G[:, :3, 3] + np.asarray(transl, np.float64) +# +# +# def rasterize(verts_cam, faces, labels, W, H, fx, fy, cx, cy): +# z = verts_cam[:, 2] +# P = faces +# ok = (z[P] > 0.02).all(1) # 任一顶点在相机后 → 丢弃该三角形 +# P, labels = P[ok], labels[ok] +# if len(P) == 0: +# return np.zeros((H, W), np.uint16), np.zeros(0, np.int64) +# x = verts_cam[:, 0] / z * fx + cx +# y = verts_cam[:, 1] / z * fy + cy +# xa = np.maximum(0, np.minimum(np.floor(x[P[:, 0]]), np.minimum( +# np.floor(x[P[:, 1]]), np.floor(x[P[:, 2]]))).astype(np.int64)) +# xb = np.minimum(W - 1, np.maximum(np.ceil(x[P[:, 0]]), np.maximum( +# np.ceil(x[P[:, 1]]), np.ceil(x[P[:, 2]]))).astype(np.int64)) +# ya = np.maximum(0, np.minimum(np.floor(y[P[:, 0]]), np.minimum( +# np.floor(y[P[:, 1]]), np.floor(y[P[:, 2]]))).astype(np.int64)) +# yb = np.minimum(H - 1, np.maximum(np.ceil(y[P[:, 0]]), np.maximum( +# np.ceil(y[P[:, 1]]), np.ceil(y[P[:, 2]]))).astype(np.int64)) +# xa, ya = np.minimum(xa, xb), np.minimum(ya, yb) # 完全出画的三角形 → 空 bbox +# wdt, hgt = xb - xa + 1, yb - ya + 1 +# cnt = wdt * hgt +# tot = int(cnt.sum()) +# tri = np.repeat(np.arange(len(P)), cnt) +# k = np.arange(tot) - (np.cumsum(cnt) - cnt)[tri] +# px = xa[tri] + k % wdt[tri] + 0.5 +# py = ya[tri] + k // wdt[tri] + 0.5 +# ax, ay = x[P[tri, 0]], y[P[tri, 0]] +# bx, by = x[P[tri, 1]], y[P[tri, 1]] +# cx_, cy_ = x[P[tri, 2]], y[P[tri, 2]] +# area = ((x[P[:, 1]] - x[P[:, 0]]) * (y[P[:, 2]] - y[P[:, 0]]) +# - (y[P[:, 1]] - y[P[:, 0]]) * (x[P[:, 2]] - x[P[:, 0]])) +# areat = area[tri] +# e0 = (bx - ax) * (py - ay) - (by - ay) * (px - ax) +# e1 = (cx_ - bx) * (py - by) - (cy_ - by) * (px - bx) +# e2 = (ax - cx_) * (py - cy_) - (ay - cy_) * (px - cx_) +# s = np.sign(areat) +# inside = (np.abs(areat) > 1e-9) & ((e0 * s >= 0) & (e1 * s >= 0) & (e2 * s >= 0)) +# px, py, tri = px[inside], py[inside], tri[inside] +# at = areat[inside] +# w0, w1, w2 = e1[inside] / at, e2[inside] / at, e0[inside] / at +# zz = w0 * z[P[tri, 0]] + w1 * z[P[tri, 1]] + w2 * z[P[tri, 2]] +# pix = py.astype(np.int64) * W + px.astype(np.int64) +# order = np.lexsort((zz, pix)) # 同像素按深度升序 → 首条即最近 +# pix, tri = pix[order], tri[order] +# first = np.unique(pix, return_index=True)[1] +# mask = np.zeros(H * W, np.uint16) +# win = tri[first] +# mask[pix[first]] = labels[win] + 1 # 临时标签 +1(0=背景) +# return mask.reshape(H, W), np.bincount(labels[win] + 1) +# +# +# # ============================================================================ +# # ffmpeg 写出与核验(与 convert_dexycb.py 同构) +# # ============================================================================ +# verts, faces_all, labels = [], [], [] +# for ti, (tid, kind) in enumerate(tracks): +# if kind == "hand_left" and b["mano"][0] > 0.5: +# verts.append(mano_forward(mano_models["left"], b["mano"][52:62], +# b["mano"][4:52], b["mano"][1:4])) +# faces_all.append(mano_models["left"]["faces"]) +# elif kind == "hand_right" and b["mano"][62] > 0.5: +# verts.append(mano_forward(mano_models["right"], b["mano"][114:124], +# b["mano"][66:114], b["mano"][63:66])) +# faces_all.append(mano_models["right"]["faces"]) +# elif isinstance(kind, tuple) and int(b["objp"][0]) == kind[1]: +# M = np.asarray(b["objrt"][1:17], np.float64).reshape(4, 4) +# V0, F0 = meshes[kind[1]] +# verts.append(V0 @ M[:3, :3].T + M[:3, 3]) +# faces_all.append(F0) +# else: +# continue +# labels.append(np.full(len(faces_all[-1]), ti)) +# if verts: +# V = np.concatenate(verts) +# offs = np.cumsum([0] + [len(v) for v in verts[:-1]]) +# F = np.concatenate([fa + o for fa, o in zip(faces_all, offs)]) +# mask, counts = rasterize(V, F, np.concatenate(labels), +# IMG_W, IMG_H, fx, fy, cx, cy) +# else: +# mask, counts = np.zeros((IMG_H, IMG_W), np.uint16), np.zeros(0, np.int64) +# lut = np.zeros(n_tracks + 1, np.uint16) +# for ti in range(n_tracks): +# present = ti + 1 < len(counts) and counts[ti + 1] > 0 +# if present: +# presence[tracks[ti][0]][f] = True +# if active_id[ti] is None: +# pid = next(i for i in range(1, 65535) if i not in used) +# used.add(pid) +# active_id[ti], seg_start[ti] = pid, f +# frame_maps[ti].append({"id": pid}) +# lut[ti + 1] = active_id[ti] +# elif active_id[ti] is not None: +# frame_maps[ti][-1]["frames"] = [seg_start[ti], f - 1] +# segments[ti].append([seg_start[ti], f - 1]) +# used.discard(active_id[ti]) +# active_id[ti] = None +# mw.write(lut[mask]) + + +# TODO(v2.0): 旧物体尺寸派生代码;v1.0 仅保留源物体关键点。 +# pts = np.asarray(b["objp"][1:64], np.float64).reshape(21, 3) +# half = np.abs((pts[1:9] - pts[0]) @ M[:3, :3]).max(0) +# obj_recs.append({ +# "track_id": f"o{classes.index(c)}", "frame": f, +# "mesh_ref": f"h2o/{OBJ_CLASSES[c]}.obj", +# "pose": {"quat": rotmat_to_quat_wxyz(M[:3, :3])[0].tolist(), +# "trans": M[:3, 3].tolist()}, +# "bbox_center3d": pts[0].tolist(), +# "bbox_size": (2 * half).tolist()}) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_hoi4d_v1.0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_hoi4d_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..9d5914d64ae72ee62564897743dfe5a41923e08d --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_hoi4d_v1.0.py @@ -0,0 +1,595 @@ +#!/usr/bin/env python3 +"""HOI4D native observations and annotations → CONTRACT.md v1.0.""" +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from contextlib import ExitStack +from functools import lru_cache +import gzip +import io +import json +import os +from pathlib import Path +import pickle +import re +import shutil +import shlex +import posixpath +import subprocess +import tempfile +import tarfile +import threading +import zipfile + +# Each worker owns one Python thread; prevent native libraries spawning CPU pools. +for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): + os.environ[key] = '1' + +import numpy as np +from PIL import Image +from scipy.spatial.transform import Rotation + +import torch + +from warehouse_v1_0 import (View, build_record, check_mesh, decode_args, find_file, json_write, locator, + mano_models, model_profile, parser, probe, release, run, safe_member, sequence_dir) + +CATEGORIES = { + 1: dict(cad="rigid/ToyCar", groups=[("main", [1], "Toy Car", 1)], + hands={2: "right"}, objmap={"Toycar": "main"}), + 2: dict(cad="rigid/Mug", groups=[("a", [1], "Mug", 2), ("b", [3], "Mug", 2)], + hands={2: "right"}, objmap={"Watercup": "a"}), + 3: dict(cad="articulated/Laptop", groups=[("main", [1, 3], "Laptop", 3)], + hands={2: "right"}, + objmap={"Laptopdisplay": "main", "Laptopkeyboard": "main"}), + 4: dict(cad="articulated/StorageFurniture", + groups=[("main", [1, 3, 4], "Storage Furniture", 4), + ("bottle", [5], "Bottle", 5)], + hands={2: "right"}, + objmap={"Lockerbody": "main", "Lockersldingdoor": "main", + "Lockerdrawer": "main", "Safebox": "main"}), + 5: dict(cad="rigid/Bottle", groups=[("main", [1], "Bottle", 5), + ("mug", [3], "Mug", 2)], + hands={2: "right"}, objmap={"bottleddrinks": "main"}), + 6: dict(cad="articulated/Safe", groups=[("main", [1, 3], "Safe", 6), + ("bottle", [4], "Bottle", 5)], + hands={2: "right"}, objmap={"Safebox": "main", "Safedoor": "main"}), + 7: dict(cad="rigid/Bowl", groups=[("main", [1], "Bowl", 7), + ("ball", [3], "Ball", None)], + hands={2: "right"}, objmap={"bowl": "main"}), + 8: dict(cad="articulated/Bucket", + groups=[("a", [1, 3], "Bucket", 8), ("b", [4, 5], "Bucket", 8)], + hands={2: "right", 6: "left"}, + objmap={"bucket": "a", "Buckethandle": "a"}), + 9: dict(cad="articulated/Scissors", groups=[("main", [1, 3], "Scissors", 9)], + hands={2: "right"}, + objmap={"scissors": "main", "scissors2": None}), # scissors2:场景道具,无掩码 + 11: dict(cad="articulated/Pliers", groups=[("main", [1, 3], "Pliers", 11)], + hands={2: "right"}, objmap={"Pliersleft": "main", "Pliersright": "main"}), + 12: dict(cad="rigid/Kettle", groups=[("main", [1], "Kettle", 12), + ("mug", [3], "Mug", 2)], + hands={2: "right"}, objmap={"kettle": "main"}), + 13: dict(cad="rigid/Knife", groups=[("main", [1], "Knife", 13), + ("apple", [3], "Apple", None)], + hands={2: "right"}, objmap={"knife": "main"}), + 14: dict(cad="articulated/TrashCan", + groups=[("main", [1, 3], "Trash Can", 14), ("bottle", [4], "Bottle", 5)], + hands={2: "right"}, objmap={"Dustbinbase": "main", "Dustbincover": "main"}), + 17: dict(cad="articulated/Lamp", groups=[("main", [1, 3, 4, 5], "Lamp", 17)], + hands={2: "right", 6: "left"}, + objmap={"Lampbase": "main", "Tablelampfirstjoint": "main", + "Tablelampsecondjoint": "main", "Thirdjointoftablelamp": "main"}), + 18: dict(cad="articulated/Stapler", + groups=[("main", [1, 3, 4], "Stapler", 18), ("paper", [5], "Paper", None)], + hands={2: "right", 6: "left"}, # 6=左手:官方 label.csv 缺列,实测修正 + objmap={"Staplerbase": "main", "Staplercover": "main"}), + 20: dict(cad="rigid/Chair", groups=[("main", [1], "Chair", 20)], + hands={2: "right", 3: "left"}, objmap={"chair": "main"}), +} + + +# Official HOI4D definitions/motion segmentation/label.csv; no spatial side inference. +REGION_NAMES = {1: {1: 'Toy Car', 2: 'Right Hand'}, 2: {1: 'Mug', 2: 'Right Hand', 3: 'Mug'}, 3: {1: 'Screen', 2: 'Right Hand', 3: 'Keyboard'}, 4: {1: 'Door', 2: 'Right Hand', 3: 'Body of the Cabinet', 4: 'Drawer', 5: 'Bottle'}, 5: {1: 'Bottle', 2: 'Right Hand', 3: 'Mug'}, 6: {1: 'Body of the Safe', 2: 'Right Hand', 3: 'Door', 4: 'Bottle'}, 7: {1: 'Bowl', 2: 'Right Hand', 3: 'Ball'}, 8: {1: 'Body of the Bucket', 2: 'Right Hand', 3: 'Handle', 4: 'Body of the Bucket', 5: 'Handle', 6: 'Left Hand'}, 9: {1: 'Left Part of the Scissors', 2: 'Right Hand', 3: 'Right Part of the Scissors'}, 11: {1: 'Left Part of the Pliers', 2: 'Right Hand', 3: 'Right Part of the Pliers'}, 12: {1: 'Kettle', 2: 'Right Hand', 3: 'Mug'}, 13: {1: 'Knife', 2: 'Right Hand', 3: 'Apple'}, 14: {1: 'Body of the Trash Can', 2: 'Right Hand', 3: 'Lid', 4: 'Bottle'}, 17: {1: 'Base', 2: 'Right Hand', 3: 'Tube', 4: 'Top Link', 5: 'Bottom Link', 6: 'Left Hand'}, 18: {1: 'Base', 2: 'Right Hand', 3: 'Slot', 4: 'Lid', 5: 'Paper'}, 20: {1: 'Chair', 2: 'Right Hand', 3: 'Left Hand'}} + + +class SplitFiles(io.RawIOBase): + """Read concatenated source gzip parts without concatenating 119 GB on disk.""" + def __init__(self, paths): + self.paths = iter(paths) + self.current = None + + def readable(self): + return True + + def readinto(self, buffer): + while True: + if self.current is None: + path = next(self.paths, None) + if path is None: + return 0 + self.current = path.open('rb') + n = self.current.readinto(buffer) + if n: + return n + self.current.close() + self.current = None + + def close(self): + if self.current is not None: + self.current.close() + super().close() + + +def extract_depths(root, sequences, work): + directory = find_file(root, 'DEPTH') + if directory is None: + return {}, [] + parts = sorted(directory.glob('HOI4D_depth_video.tar.gz*'), key=lambda p: int(p.name.split('.gz')[1] or 0)) + if not parts: + return {}, [] + wanted = {f'HOI4D_depth_video/{seq}/align_depth/depth_video.avi': seq for seq in sequences} + found = {} + with SplitFiles(parts) as joined, io.BufferedReader(joined) as inp, gzip.GzipFile(fileobj=inp) as gz: + with tarfile.open(fileobj=gz, mode='r|') as tf: + for member in tf: + if member.isfile() and member.name in wanted: + seq = wanted[member.name] + dest = work / (seq.replace('/', '_') + '.avi') + with tf.extractfile(member) as src, dest.open('wb') as dst: + shutil.copyfileobj(src, dst) + found[seq] = (dest, {'files': [str(p.resolve()) for p in parts], 'member': member.name}) + if len(found) == len(wanted): + break + return found, parts + + +def palette_mask(data): + with Image.open(io.BytesIO(data)) as im: + arr = np.asarray(im) + if arr.ndim == 2: + return arr.astype(np.uint16) + if arr.shape[-1] != 3: + raise ValueError('unsupported HOI4D mask representation') + # VOC's 256-color palette interleaves eight label bits into the high RGB bits. + # Invert it directly instead of sorting every pixel with np.unique. + if np.any(arr & np.array([31, 31, 63], dtype=np.uint8)): + raise ValueError('source mask has colors outside official VOC palette') + mask = np.zeros(arr.shape[:2], dtype=np.uint16) + for bit in range(8): + mask |= ((arr[..., bit % 3] >> (7 - bit // 3)) & 1).astype(np.uint16) << bit + return mask + + +# Four workers each reuse annotation and hand indices instead of rebuilding the ZIP directory. +@lru_cache(maxsize=8) +def index_frames(z): + index = {} + for name in z.namelist(): + parent, _, filename = name.rpartition('/') + stem, dot, suffix = filename.rpartition('.') + if not dot or not stem.isdigit() or suffix not in ('png', 'json', 'pickle'): + continue + entries = index.setdefault((parent + '/', '.' + suffix), {}) + f = int(stem) + if f in entries: + raise ValueError(f'duplicate frame number under {parent}') + entries[f] = name + return index + + +def frame_members(z, prefix, suffix): + return index_frames(z).get((prefix, suffix), {}) + + +def convert_sequence(seq, args, target, rgbz, annz, hpz, calz, cadz, paths, models, depth): + # ponytail: cache only one sequence's encoded annotation bytes; no decoded masks or CAD cache. + @lru_cache(maxsize=None) + def read_annotation(archive, name): + return archive.read(name) + + category = int(re.search(r'/C(\d+)/', seq)[1]) + definition = CATEGORIES.get(category) + if definition is None: + raise ValueError(f'category mapping unavailable: {category}') + prefix = f'HOI4D_annotations/{seq}' + mask_members = frame_members(annz, prefix + '/2Dseg/mask/', '.png') + shifted = frame_members(annz, prefix + '/2Dseg/shift_mask/', '.png') + if not mask_members: + mask_members = shifted + pose_members = frame_members(annz, prefix + '/objpose/', '.json') + hand_members = {side: frame_members(hpz, f'Hand_pose/handpose_{side}_hand/{seq}/', '.pickle') + for side in ('left', 'right')} if hpz else {'left': {}, 'right': {}} + with tempfile.TemporaryDirectory(prefix='hoi4d-source-') as wd: + work = Path(wd) + member = f'HOI4D_release/{seq}/align_rgb/image.mp4' + video = work / 'rgb.mp4' + with rgbz.open(member) as src, video.open('wb') as dst: + shutil.copyfileobj(src, dst) + info = probe(video) + if 'nb_frames' not in info: + info['nb_frames'] = json.loads(run(['ffprobe', '-v', 'error', '-count_frames', '-select_streams', 'v:0', + '-show_entries', 'stream=nb_read_frames', '-of', 'json', str(video)], stdout=subprocess.PIPE).stdout)['streams'][0]['nb_read_frames'] + n = int(info['nb_frames']) + if args.max_frames: + n = min(n, args.max_frames) + if shifted and mask_members != shifted and any(f not in mask_members and f in shifted for f in range(n)): + raise ValueError('shift_mask has frames absent from mask; correspondence unverified') + frames = [] + for f in range(n): + sources = {} + if f in mask_members: + sources['segment'] = locator(paths['annotations'], mask_members[f], read_annotation(annz, mask_members[f])) + if f in pose_members: + sources['object'] = locator(paths['annotations'], pose_members[f], read_annotation(annz, pose_members[f])) + for side in ('left', 'right'): + if f in hand_members[side]: + sources['hand_' + side] = locator(paths['hand'], hand_members[side][f], read_annotation(hpz, hand_members[side][f])) + frames.append(dict(source_frame_id=f, source_locator=locator(paths['release'], member, frame=f), + component_sources=sources, annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None) for k in sources})) + view = View(target, 'HOI4D', args.release_id, seq.replace('/', '_'), 'ego', frames) + view.valid_rules = { + 'mano': 'Matched side pickle contains poseCoeff, beta, trans and corresponding model available; zero angles are not missing', + 'keypoints': 'Matched side pickle contains kps2D; independently provided source points, no visibility gate', + 'pose': 'Matched source object record contains rotation and center; record identity retained', + 'dimensions': 'Matched source object record contains dimensions; size/mesh relation remains source_unspecified', + 'segment': 'Source mask or shift_mask present with verified palette codes and entity/part mapping', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta['view_type'] = 'ego' + view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'source_sequence': seq} + view.rgb([], locator(paths['release'], member), video=video, count=n) + intr_name = f'camera_params/{seq.split("/")[0]}/intrin.npy' + if calz and intr_name in calz.namelist(): + view.camera(np.load(io.BytesIO(calz.read(intr_name))), locator(paths['camera'], intr_name)) + extr_name = prefix + '/3Dseg/output.log' + if extr_name in annz.NameToInfo: + lines = [line for line in annz.read(extr_name).decode().splitlines() if line.strip()] + if len(lines) % 5: + raise ValueError('invalid Open3D camera trajectory') + extr, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + for i in range(0, len(lines), 5): + idx = int(lines[i].split()[0]) + if idx < n: + if valid[idx]: + raise ValueError('duplicate trajectory index') + extr[idx] = np.linalg.inv(np.loadtxt(io.StringIO('\n'.join(lines[i + 1:i + 5])))) + valid[idx] = True + view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', extr, valid, + ['T', 'row', 'column'], locator(paths['annotations'], extr_name), + convention='T_camera_from_world', source_convention='Open3D LOG camera-to-world; inverted') + loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} + motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) + points, pv = np.full((n, 2, 21, 2), np.nan, np.float32), np.zeros((n, 2, 21), bool) + for slot, side in enumerate(('left', 'right')): + for f, name in hand_members[side].items(): + if f >= n: + continue + data = pickle.loads(read_annotation(hpz, name), encoding='latin1') + if all(k in data for k in ('poseCoeff', 'beta', 'trans')): + motion[f, slot] = np.r_[np.asarray(data['poseCoeff']).reshape(48), + np.asarray(data['beta']).reshape(10), np.asarray(data['trans']).reshape(3)] + mv[f, slot] = True # Zero angles are a valid pose, not a missing sentinel. + if 'kps2D' in data: + points[f, slot] = np.asarray(data['kps2D']).reshape(21, 2) + pv[f, slot] = True + if mv.any(): + if all(side in models for slot, side in enumerate(('left', 'right')) if mv[:, slot].any()): + view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, + ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) + else: + view.absent('mano', 'Source MANO exists; provide --mano-dir to fix model identity', 'dependency_missing') + if pv.any(): + view.tensor('keypoints_uv', 'keypoints/uv/v1', 'annotation/keypoints/uv.pt', points, pv, + ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='pixel', + source_method='Upstream fitted MANO projection already present in kps2D') + objects = {} + groups = {key: (vals, name, cls) for key, vals, name, cls in definition['groups']} + def ensure_object(key, source_loc, category_id=None, frame=None, source_id=None): + if key not in objects: + view.object(key, source_loc, scope='frame' if frame is not None else 'sequence', + scope_id=f'{seq}:{frame}' if frame is not None else None, + category_id=category_id, source_object_id=source_id) + objects[key] = {} + mappings = [] + mask_valid = [f in mask_members for f in range(n)] + if any(mask_valid): + width, height = view.meta['camera']['image_size'] + def masks(): + for f in range(n): + labels = [] + if f in mask_members: + mask = palette_mask(read_annotation(annz, mask_members[f])) + for value in np.unique(mask): + value = int(value) + if value in (0, 255): + if value == 255: + raise ValueError('HOI4D 255 region semantics unverified') + continue + if REGION_NAMES[category].get(value) in ('Left Hand', 'Right Hand'): + entity, part, cls = 'hand_' + REGION_NAMES[category][value].split()[0].lower(), None, 'hand' + else: + group = next((k for k, (vals, _, _) in groups.items() if value in vals), None) + entity = group or f'unknown_region_{value}' + cls = groups[group][2] if group else None + part = f'region_{value}' if group and len(groups[group][0]) > 1 else None + ensure_object(entity, frames[f]['component_sources']['segment'], cls) + if part: + objects[entity].setdefault('parts', {})[part] = {'part_id': part, 'parent_id': None, + 'has_model': False, 'mesh_ref': None, 'source_region_code': value, 'name': REGION_NAMES[category].get(value)} + labels.append(dict(mask_value=value, category_id=cls, entity_id=entity, + part_id=part, source_instance_id=value, + source_attributes={'region_name': REGION_NAMES[category].get(value)})) + else: + mask = np.zeros((height, width), np.uint16) + mappings.append(dict(frame_index=f, labels=labels)) + yield mask + view.raster('segment', masks(), mask_valid, loc, mappings) + view.meta['components']['segment']['coverage'] = {'kind': 'unknown'} + if any(label['part_id'] for row in mappings for label in row['labels']): + view.meta['components']['segment']['segmentation_type'] = 'part' + else: + view.absent('segment', 'No native segmentation for this source sequence') + records = {} + for f, name in pose_members.items(): + if f >= n: + continue + data = json.loads(read_annotation(annz, name)) + # isEffective is not used to erase existing numerical annotations. + source_records = data.get('dataList', data.get('objects')) + if source_records is None: + raise ValueError('unrecognized source object annotation structure') + if category == 2 and source_records and (len(source_records) != 1 or + source_records[0].get('id') != 1 or source_records[0].get('label') != 'Watercup'): + raise ValueError('C2 native pose differs from the verified one-object target; cannot map to mask region 1') + label_counts = Counter(record['label'] for record in source_records) + per_frame = set() + for record_index, record in enumerate(source_records): + label = record['label'] + group = definition['objmap'].get(label) + # Pinned official ObjTracking reads dataList[0] with segmentation label 1. + source_primary = category == 2 and record_index == 0 and record.get('id') == 1 and group == 'a' + ambiguous = group is not None and sum(g[2] == groups[group][2] for g in groups.values()) > 1 and not source_primary + ambiguous = ambiguous or (label_counts[label] > 1 and not source_primary) or group is None + entity = f'pose_frame_{f}_{record_index}' if ambiguous else group + ensure_object(entity, locator(paths['annotations'], name, record=record_index), + groups[group][2] if group else None, frame=f if ambiguous else None, source_id=record.get('id')) + if ambiguous: + view.build['unresolved'].append({'component': entity, 'status': 'source_semantics_unverified', + 'reason': 'Source pose retained with frame identity; no guessed association to same-class mask instances'}) + label_key = (entity, label) + if label_key in per_frame: + raise ValueError(f'ambiguous repeated object label {label}; source identity must be resolved') + per_frame.add(label_key) + records.setdefault(label_key, {})[f] = (record, locator(paths['annotations'], name, record=record.get('id'))) + if category == 2 and any(entity == 'a' for entity, _ in records): + view.build['validation'].append({'component': 'C2_source_pose_mask_identity', + 'rule': 'Official ObjTracking process_data.py reads dataList[0] with semantic mask label 1', + 'source_revision': 'afa7bf37b02b7e33cf245acd08b98c207ccc175c', + 'source_pose_id': 1, 'mask_value': 1, 'matched_frames': sum(len(by_frame) for (entity, _), by_frame in records.items() if entity == 'a')}) + for (entity, label), by_frame in records.items(): + part_labels = [k[1] for k in records if k[0] == entity] + articulated = definition['cad'].startswith('articulated/') and entity == definition['groups'][0][0] + part = 'pose_' + re.sub(r'[^a-zA-Z0-9_]', '_', label) if articulated or len(part_labels) > 1 else None + base = f'annotation/object/{entity}' + if part: + base += '/parts/' + part + objects[entity].setdefault('parts', {})[part] = dict(part_id=part, parent_id=None, + has_model=False, mesh_ref=None, source_label=label) + poses, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) + dimensions = np.full((n, 3), np.nan, np.float32) + dv = np.zeros(n, bool) + for f, (record, _) in by_frame.items(): + if all(k in record for k in ('rotation', 'center')): + poses[f] = np.eye(4) + poses[f, :3, :3] = Rotation.from_euler('XYZ', [record['rotation'][k] for k in ('x', 'y', 'z')]).as_matrix() + poses[f, :3, 3] = [record['center'][k] for k in ('x', 'y', 'z')] + valid[f] = True + if 'dimensions' in record: + dimensions[f] = [record['dimensions'][k] for k in ('length', 'width', 'height')] + dv[f] = True + key = entity + ('_' + part if part else '') + view.tensor('pose_' + key, 'transform/se3/v1' if part else 'object/rigid/v1', base + '/pose.pt', poses, valid, + ['T', 'row', 'column'], loc, convention='T_camera_from_part' if part else 'T_camera_from_object', + unit='m', source_label=label, source_euler_order='XYZ', + definition='https://github.com/hoi4d/ObjTracking/blob/main/process_data.py') + if dv.any(): + view.tensor('dimensions_' + key, 'object/dimensions/v1', base + '/dimensions.pt', dimensions, dv, + ['T', 'dimension'], loc, dimensions_semantics='source_unspecified', unit='m', scale_applied_to_mesh=False) + if cadz: + primary = definition['groups'][0][0] + if category != 2 and sum(g[2] == category for g in groups.values()) > 1: + primary = 'source_cad_instance' + instance = int(re.search(r'/N(\d+)/', seq)[1]) + mesh_prefix = f'HOI4D_CAD_Model_for_release/{definition["cad"]}/{instance:03d}' + candidates = [name for name in cadz.namelist() if not name.endswith('/') and + (name == mesh_prefix + '.obj' or name.startswith(mesh_prefix + '/'))] + if candidates: + # Retain OBJ material/texture dependencies beside their original names. + queue = list(candidates) + for name in queue: + if Path(name).suffix.lower() not in ('.obj', '.mtl'): + continue + for line in cadz.read(name).decode().splitlines(): + fields = shlex.split(line, comments=True) + if not fields: + continue + refs = fields[1:] if fields[0] == 'mtllib' else ([fields[-1]] if + fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal') else []) + for ref in refs: + dependency = posixpath.normpath(posixpath.join(posixpath.dirname(name), ref)) + if dependency not in cadz.NameToInfo: + raise ValueError(f'missing CAD dependency: {dependency}') + if dependency not in candidates: + candidates.append(dependency) + queue.append(dependency) + ensure_object(primary, locator(paths['cad'], mesh_prefix), category) + asset_dir = view.path / f'annotation/object/{primary}/assets' + asset_refs = [] + for name in candidates: + relative = posixpath.relpath(name, mesh_prefix if definition['cad'].startswith('articulated/') else posixpath.dirname(mesh_prefix)) + dest = safe_member(asset_dir, relative) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(cadz.read(name)) + ref = dest.relative_to(view.path).as_posix() + if dest.suffix.lower() == '.obj': + asset_key = re.sub(r'[^a-zA-Z0-9_]', '_', relative) + view.component('mesh_' + primary + '_' + asset_key, 'mesh/obj/v1', ref, ['vertex'], + locator(paths['cad'], name), unit='m', valid=True, + scale_applied_to_mesh=False, dimensions_semantics='source_unspecified') + asset_refs.append(ref) + if definition['cad'].startswith('articulated/'): + part_id = 'asset_' + asset_key + objects[primary].setdefault('parts', {})[part_id] = dict(part_id=part_id, + parent_id=None, has_model=True, mesh_ref=ref, source_asset=relative, + note='Source asset; correspondence to motion part labels remains unverified') + for asset_ref in asset_refs: + mesh_check = check_mesh(view.path / asset_ref, asset_dir) + view.build['validation'].append({'component': asset_ref, **mesh_check, + 'unit_basis': 'official ObjTracking loads source canonical CAD without scaling in metre camera coordinates', + 'geometric_acceptance': 'physical dimensions-to-mesh relation remains source_unspecified'}) + metadata_path = view.path / f'annotation/object/{primary}/metainfo.json' + metadata = json.loads(metadata_path.read_text()) + metadata.update(has_model=bool(asset_refs), asset_refs=asset_refs) + if definition['cad'].startswith('rigid/') and len(asset_refs) == 1: + metadata['mesh_ref'] = asset_refs[0] + json_write(metadata_path, metadata) + if definition['cad'].startswith('articulated/'): + view.build['unresolved'].append({'component': 'object_part_asset_association', + 'status': 'source_semantics_unverified', + 'reason': 'All source assets and motion labels retained, but no guessed correspondence or joint_state'}) + for entity, info in objects.items(): + if 'parts' in info: + ref = f'annotation/object/{entity}/articulation.json' + json_write(view.path / ref, {'parts': list(info['parts'].values()), 'joints': [], + 'hierarchy_semantics': 'semantic_containment', + 'note': 'Unassociated source region, motion and asset nodes; original CAD trees retained in assets'}) + view.component('articulation_' + entity, 'object/articulated/v1', ref, [], loc) + meta_path = view.path / f'annotation/object/{entity}/metainfo.json' + metadata = json.loads(meta_path.read_text()) + metadata['articulation_ref'] = ref + json_write(meta_path, metadata) + if depth is not None: + dpath, dloc = depth + dmeta = probe(dpath) + if [dmeta['width'], dmeta['height']] != view.meta['camera']['image_size']: + raise ValueError('HOI4D depth grid differs from RGB') + if dmeta['pix_fmt'] != 'gray16le': + raise ValueError('unexpected HOI4D depth pixel format') + width, height = view.meta['camera']['image_size'] + raw = work / 'depth.raw' + limits = ['-frames:v', str(n)] if args.max_frames else [] + run(decode_args(dpath, 'gray16le') + limits + ['-y', str(raw)]) + if raw.stat().st_size != n * width * height * 2: + raise ValueError('depth/RGB frame count or grid mismatch') + def depths(): + with raw.open('rb') as inp: + for _ in range(n): + yield np.frombuffer(inp.read(width * height * 2), ' best_iou + 0.1 and i > 0.15: +# best, best_iou = s[0], i +# if best != gk: +# gk, iou_fixups = best, iou_fixups + 1 diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_visor_v1.0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_visor_v1.0.py new file mode 100644 index 0000000000000000000000000000000000000000..8f0595bf5e89ae00c959472ff197dfda2d7a6ea6 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/convert_visor_v1.0.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +"""VISOR source polygons and contact → CONTRACT.md v1.0, without rasterization or side inference.""" +from collections import Counter +import hashlib +import json +import re +import shutil +import tempfile +from pathlib import Path +import zipfile + +import numpy as np +import torch + +from warehouse_v1_0 import (View, build_record, find_file, jsonl_write, locator, parser, + release, roots, sequence_dir, source) + +FRAME = re.compile(r'frame_(\d+)') +HAND = {300: 'left', 301: 'right'} +GLOVE = {303: 'left', 304: 'right'} +STATES = {'hand-not-in-contact': 'negative', 'glove-not-in-contact': 'negative', + 'none-of-the-above': 'target_unannotated', 'inconclusive': 'unknown'} + + +def hand_side(ann): + if ann['class_id'] in HAND: + return HAND[ann['class_id']] + if ann['class_id'] not in (60, 303, 304): + return None + raw = ann.get('on_which_hand') + raw = raw if isinstance(raw, list) else [raw] + sides = set() + for item in raw: + if item == 'left hand': + sides.add('left') + if item in ('right hand', 'rigth hand'): + sides.add('right') + if len(sides) == 1: + return next(iter(sides)) + if not sides and ann['class_id'] in GLOVE: + return GLOVE[ann['class_id']] + return None + + +def convert_video(video, split, annotation, ann_loc, rgb_zip, rgb_loc, mapping, args, target): + indexed = sorted(enumerate(annotation['video_annotations']), key=lambda row: int(FRAME.search(row[1]['image']['name'])[1])) + if args.max_frames: + indexed = indexed[:args.max_frames] + if len({row['image']['name'] for _, row in indexed}) != len(indexed): + raise ValueError('duplicate VISOR frame') + keys = lambda row, ann: (row['image']['subsequence'], ann['class_id'], ann['name']) + collisions = set() + for _, row in indexed: + collisions.update(key for key, number in Counter(keys(row, a) for a in row['annotations']).items() if number > 1) + frames, paths = [], [] + with tempfile.TemporaryDirectory(prefix='visor-rgb-') as wd, zipfile.ZipFile(rgb_zip) as z: + work = Path(wd) + for original_index, row in indexed: + name = row['image']['name'] + data = z.read(name) + path = work / Path(name).name + path.write_bytes(data) + paths.append(path) + loc = rgb_loc | {'nested_member': name, 'sha256': hashlib.sha256(data).hexdigest()} + frames.append(dict(source_frame_id=int(FRAME.search(name)[1]), source_locator=loc, + source_image=row['image'], original_frame_name=mapping.get(name), + annotation_matches={'segment': dict(source_frame_id=name, source_timestamp_ns=None, + clock_domain=None, match_method='index_map', delta_ns=None, + source_locator=ann_loc | {'record': f'video_annotations[{original_index}]'})})) + view = View(target, 'EPIC-KITCHENS-VISOR', args.release_id, video, 'ego', frames, sampling='sparse', split=split) + view.valid_rules = { + 'segment': 'Selected sparse annotation frame present; all source polygons finite with at least three vertices and entity mapping valid', + 'relations': 'At least one source in_contact_object value present; positive targets resolve in the same frame; unknown is an explicit usable status', + } + view.full_jpeg = getattr(args, 'jpeg_full_check', False) + view.meta.update(view_type='ego', split_scheme='VISOR_GroundTruth_SparseAnnotations', split_source_locator=ann_loc) + view.meta['sampling']['selection'] = {'representation': 'official sparse annotations', 'max_frames': args.max_frames} + view.rgb(paths, rgb_loc) + entities = {} + polygons, mappings, relations, relation_valid = [], [], [], [] + for f, (original_index, row) in enumerate(indexed): + frame_loc = ann_loc | {'record': f'video_annotations[{original_index}]'} + id_map, labels, polys = {}, [], [] + for code, ann in enumerate(row['annotations'], 1): + if code >= 65535: + raise ValueError('too many source instances') + sid = ann['id'] + if sid in id_map: + raise ValueError('duplicate source instance ID within a frame') + side = hand_side(ann) + if side is not None: + entity = 'hand_' + side + else: + key = keys(row, ann) + identity = key + (sid, row['image']['name']) if key in collisions else key + entity = 'object_' + hashlib.sha256(json.dumps(identity).encode()).hexdigest()[:20] + if entity not in entities: + scope = 'frame' if key in collisions else 'subsequence' + scope_id = f'{video}:{row["image"]["name"]}' if scope == 'frame' else f'{video}:{key[0]}' + view.object(entity, frame_loc | {'source_instance_id': sid}, scope, scope_id, + category_id=ann['class_id'], name=ann['name'], + association_basis='source_frame_instance' if scope == 'frame' else 'official_subsequence_entity_name') + entities[entity] = True + id_map[sid] = entity + for polygon in ann.get('segments', []): + p = np.asarray(polygon) + if p.ndim != 2 or p.shape[1] != 2 or len(p) < 3 or not np.isfinite(p).all(): + raise ValueError(f'invalid source polygon {sid}') + polys.append(dict(mask_value=code, polygons=ann.get('segments', []))) + labels.append(dict(mask_value=code, category_id=ann['class_id'], entity_id=entity, + part_id=None, source_instance_id=sid, + source_attributes={k: v for k, v in ann.items() if k != 'segments'})) + rr = [] + provided = False + for ann in row['annotations']: + raw = ann.get('in_contact_object') + values = raw if isinstance(raw, list) else [raw] + for value in values: + if value is None: + continue + provided = True + status = STATES.get(value) + obj = None + if status is None: + if value not in id_map: + raise ValueError(f'unresolved source contact target {value} in {video} frame {f}') + status, obj = 'positive', id_map[value] + rr.append(dict(relation_type='contact', subject_id=id_map[ann['id']], object_id=obj, + status=status, source_value=value, source_locator=frame_loc | {'source_instance_id': ann['id']}, + provenance=source('Resolve source contact ID against instances in this frame'))) + polygons.append(dict(frame_index=f, instances=polys)) + mappings.append(dict(frame_index=f, labels=labels)) + relations.append(dict(frame_index=f, relations=rr)) + relation_valid.append(provided) + jsonl_write(view.path / 'annotation/segment/polygons.jsonl', polygons) + jsonl_write(view.path / 'annotation/segment/instances.jsonl', mappings) + torch.save(torch.ones(len(frames), dtype=torch.bool, device='cpu'), view.path / 'annotation/segment/mask_valid.pt') + view.component('segment', 'segment/instance_polygons/v1', 'annotation/segment/polygons.jsonl', ['T'], ann_loc, + valid_ref='annotation/segment/mask_valid.pt', valid_axes=['T'], segmentation_type='instance', + mapping_ref='annotation/segment/instances.jsonl', coverage={'kind': 'unknown', 'exhaustive_ref': 'annotation/segment/instances.jsonl'}) + view.relations(relations, relation_valid, ann_loc) + for component in ('depth', 'mano', 'keypoints_uv', 'keypoints_xyz', 'intrinsic', 'extrinsic'): + view.absent(component, 'Not provided by VISOR sparse source annotations') + return view.finish() + + +def main(argv=None): + p = parser('EPIC-KITCHENS-VISOR', __doc__) + p.add_argument('--videos', help='Comma-separated video names') + p.add_argument('--splits', default='train,val') + args = p.parse_args(argv) + wanted = set(args.videos.split(',')) if args.videos else None + splits = set(args.splits.split(',')) + if not splits <= {'train', 'val'}: + p.error('only annotated train/val splits are available') + out = release(args, 'EPIC-KITCHENS-VISOR') + archive = find_file(args.root, 'EPIC-KITCHENS VISOR.zip') + with tempfile.TemporaryDirectory(prefix='visor-source-') as wd: + work = Path(wd) + if archive: + with zipfile.ZipFile(archive) as z: + suffix = 'GroundTruth-SparseAnnotations/annotations/' + members = [n for n in z.namelist() if suffix in n and n.endswith('.json')] + prefix = members[0].split(suffix)[0] + fm = json.loads(z.read(prefix + 'frame_mapping.json')) + done = 0 + for member in sorted(members): + split, filename = member.split(suffix)[1].split('/') + video = Path(filename).stem + if split not in splits or wanted and video not in wanted: + continue + data = z.read(member) + rgb_member = prefix + f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' + rgb_zip = work / (video + '.zip') + with z.open(rgb_member) as inp, rgb_zip.open('wb') as dest: + shutil.copyfileobj(inp, dest) + with sequence_dir(out, video) as dest: + report = convert_video(video, split, json.loads(data), locator(archive, member, data), + rgb_zip, locator(archive, rgb_member), fm.get(video, {}), args, dest / 'ego') + build_record(out, video, {'ego': report}) + rgb_zip.unlink() + done += 1 + print(f'Converted {video}', flush=True) + if args.limit and done >= args.limit: + break + else: + root = next((r for r in roots(args.root) if (r / 'GroundTruth-SparseAnnotations').is_dir()), None) + if root is None: + p.error('VISOR outer ZIP or extracted source directory not found') + fm = json.loads((root / 'frame_mapping.json').read_text()) if (root / 'frame_mapping.json').exists() else {} + done = 0 + for split in sorted(splits): + for ann in sorted((root / 'GroundTruth-SparseAnnotations/annotations' / split).glob('*.json')): + video = ann.stem + if wanted and video not in wanted: + continue + rgb = root / f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' + with sequence_dir(out, video) as dest: + report = convert_video(video, split, json.loads(ann.read_text()), locator(ann), rgb, + locator(rgb), fm.get(video, {}), args, dest / 'ego') + build_record(out, video, {'ego': report}) + done += 1 + if args.limit and done >= args.limit: + return 0 + if not done: + p.error('no matching annotated videos found') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) + +# TODO(v2.0): 旧距离猜侧和单层掩码生成仅注释保留;v1.0 不执行。 +# if side is None and len(frame_hands) == 1: +# # 空间门槛:脱下放在远处的手套不并入(实测双峰 0..25px / ≥44px) +# hb = frame_hands[0][1] +# gb = _bbox_of(polys) +# if hb and gb and _bbox_dist(gb, hb) <= GLOVE60_MERGE_BBOX_DIST: +# side = frame_hands[0][0] +# stats["glove60_merged_into_sole_hand"] += 1 +# if side is None: +# stats["dropped_glove60_unresolved"] += 1 +# id_disp[mid] = ("dropped", "glove60") +# continue +# def rasterize_and_encode(vdir, frames, frame_draw, zip_path, n, stats): +# """流式读 zip 内 jpg + 光栅化多边形 → rgb.mkv / mask.mkv;返回 (w, h)。""" +# from PIL import Image, ImageDraw +# +# with zipfile.ZipFile(zip_path) as zf: +# member_of = {} +# for nm in zf.namelist(): +# member_of[os.path.basename(nm)] = nm +# names = [im["name"] for im in frames] +# missing = [nm for nm in names if nm not in member_of] +# if missing: +# raise RuntimeError(f"{len(missing)} annotated frames missing in zip, " +# f"e.g. {missing[:3]}") +# stats["zip_extra_members"] = len(member_of) - len(names) +# +# # 首帧定分辨率(官方 1920×1080,实测每帧校验) +# img0 = Image.open(io.BytesIO(zf.read(member_of[names[0]]))).convert("RGB") +# w, h = img0.size +# +# bin_img = Image.new("L", (w, h), 0) +# bin_draw = ImageDraw.Draw(bin_img) +# canvas = np.zeros((h, w), np.uint16) +# with VideoPipe(vdir / "mask.mkv", w, h, FPS, "mask") as mw, \ +# VideoPipe(vdir / "rgb.mkv", w, h, FPS, "rgb") as rw: +# for f in range(n): +# canvas[:] = 0 +# for pid, polys in frame_draw[f]: +# bin_draw.rectangle((0, 0, w, h), fill=0) +# for poly in polys: +# bin_draw.polygon([(float(x), float(y)) for x, y in poly], fill=255) +# arr = np.asarray(bin_img) +# canvas[arr > 0] = pid # 后画覆盖先画:物体→手(modal) +# mw.write(canvas) +# img = img0 if f == 0 else Image.open( +# io.BytesIO(zf.read(member_of[names[f]]))).convert("RGB") +# if img.size != (w, h): +# raise RuntimeError(f"frame {names[f]}: size {img.size} != {(w, h)}") +# rw.write(np.asarray(img)) +# n_mask, n_rgb = mw.n, rw.n +# if (n_rgb, n_mask) != (n, n): +# raise RuntimeError(f"wrote rgb={n_rgb} mask={n_mask} != {n}") +# got = (count_frames(vdir / "rgb.mkv"), count_frames(vdir / "mask.mkv")) +# if got != (n, n): +# raise RuntimeError(f"encoded rgb={got[0]} mask={got[1]} != {n} (decode verify)") +# return w, h +# +# diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_dexycb_validation.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_dexycb_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..e8bb71e9ad9c5a44f85e5c50cee467a00512aa1d --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_dexycb_validation.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Audit a finished Dex-YCB release and render persisted modalities for manual review.""" +from collections import Counter +import hashlib +import json +from pathlib import Path +import sys + +from render_hoi4d_validation import render + + +def inspect(root): + data, doc, scripts = root / 'data', root / 'doc', root / 'script' + sequences = sorted(p for p in data.iterdir() if p.is_dir()) + assert len(sequences) == 1000, f'expected 1000 sequences, got {len(sequences)}' + assert len(list(doc.glob('*.build.json'))) == 1000 + assert not list(data.glob('*.tmp-*')), 'unfinished temporary sequences' + config = json.loads((scripts / 'config.json').read_text()) + assert all(config.get(k) is None for k in ('limit', 'max_frames', 'subjects', 'views')) + hashes = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in scripts.glob('*.py')} + subjects, splits, availability = Counter(), Counter(), Counter() + selected = [] + for seq in sequences: + views = sorted(p for p in seq.iterdir() if p.is_dir()) + assert len(views) == 8, (seq, len(views)) + build = json.loads((doc / (seq.name + '.build.json')).read_text()) + assert set(build['views']) == {p.name for p in views}, seq + assert all(hashes.get(k) == v for k, v in build['scripts'].items()), seq + subject = seq.name.split('_')[0] + subjects[subject] += 1 + if subjects[subject] == 1: + selected.append(views[0]) + if subject.endswith('subject-09'): + selected.append(views[-1]) # one more camera, different camera + if seq.name == '20201015-subject-09_20201015_150838': + selected.append(views[0]) # source-labelled left-hand sequence + for view in views: + meta = json.loads((view / 'metainfo.json').read_text()) + assert meta['sequence_id'] == seq.name and meta['camera_id'] == view.name, view + assert meta['dataset_id'] == 'dex-ycb' and meta['release_id'] == 'shared-v1.0', view + assert meta['num_frames'] > 0 and meta.get('view_type') == 'exo', view + assert (view / 'camera/frames.jsonl').is_file(), view + assert meta['components']['rgb']['available'], view + splits[meta['split']] += 1 + for key, part in meta['components'].items(): + if part.get('available'): + availability[key] += 1 + for ref in ('data_ref', 'valid_ref'): + if part.get(ref): + assert (view / part[ref]).is_file(), (view, key, ref) + assert len(subjects) == 10 and set(subjects.values()) == {100}, subjects + assert availability['depth'] == availability['rgb'] == 8000, availability + report = dict(sequences=len(sequences), views=sum(splits.values()), subjects=dict(subjects), + splits=dict(splits), available_views=dict(availability), config=config, + published_script_sha256=hashes, sampled_views=[str(v.relative_to(root)) for v in selected], + scope='Structure and file refs checked for all views; persisted QC and HTML only for sampled views. No manual visual approval yet.') + destination = doc / 'validation' + destination.mkdir(exist_ok=True) + (destination / 'STRUCTURAL_AUDIT.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') + for view in selected: + render(view, destination) + return report + + +if __name__ == '__main__': + print(json.dumps(inspect(Path(sys.argv[1]).expanduser().resolve()), ensure_ascii=False), flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_h2o_validation.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_h2o_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..b89e7c0827f45ec7f854ff8651234cb9a4223f79 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_h2o_validation.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Render stored H2O RGB-D, native camera-space hands/objects, and OBJ assets for review.""" +import argparse +import html +import json +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw +import torch + +from render_hoi4d_validation import mesh_preview, picture, snapshot +from warehouse_v1_0 import unpack_depth, validate_view + + +def load(view, item, n): + if not item.get('available') or not item.get('data_ref', '').endswith('.pt'): + return None, None + values = torch.load(view / item['data_ref'], map_location='cpu', weights_only=True).numpy() + valid = torch.load(view / item['valid_ref'], map_location='cpu', weights_only=True).numpy() if item.get('valid_ref') else None + return (values, valid) if values.ndim and values.shape[0] == n else (None, None) + + +def render(view, destination): + meta = json.loads((view / 'metainfo.json').read_text()) + if meta['dataset_id'] != 'H2O': + raise ValueError('H2O view required') + n = meta['num_frames'] + height, width = reversed(meta['camera']['image_size']) + parts = meta['components'] + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + assert len(frames) == n + selected = {0, n // 4, n // 2, 3 * n // 4, n - 1} + numeric = {} + for name, item in parts.items(): + if item.get('data_ref', '').endswith('.pt') and item.get('available'): + values, valid = load(view, item, n) + if values is not None: + numeric[name] = (values, valid) + if valid is not None: + indices = np.flatnonzero(valid.reshape(n, -1).any(axis=1)) + if len(indices): + selected.add(int(indices[0])) + selected = set(sorted(selected)[:12]) | {n - 1} + rgb = snapshot(view / parts['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected) + depth = snapshot(view / parts['depth']['data_ref'], 'gray16le', (height, 2 * width), ' 0: + u, v = intrinsic[i, 0, 0] * xyz[0] / xyz[2] + intrinsic[i, 0, 2], intrinsic[i, 1, 1] * xyz[1] / xyz[2] + intrinsic[i, 1, 2] + if 0 <= u < width and 0 <= v < height: + draw.ellipse((u-4, v-4, u+4, v+4), fill=color) + legend.append(name + ' ' + color) + panels = ['
' + picture(photo) + '
RGB + 原生 3D 关键点投影(仅预览:' + html.escape(', '.join(legend) or '当前帧无可投影点') + ')
'] + if i in depth: + z = unpack_depth(depth[i]) + luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8) + panels.append('
' + picture(Image.fromarray(luminance)) + '
深度 Z,黑=无效,白≥3 m;不改源深度
') + details = {'frame': frames[i]} + for name, (values, valid) in numeric.items(): + details[name] = {'value': values[i].tolist(), 'valid': None if valid is None else valid[i].tolist()} + pages.append('

帧 ' + str(i) + ' / ' + str(n) + '

' + ''.join(panels) + '
原帧号、全部数值标注及有效性
' + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '
') + assets = [] + for name, item in parts.items(): + if item.get('available') and item.get('data_ref', '').lower().endswith('.obj'): + assets.append('

' + html.escape(name) + '

' + mesh_preview(view / item['data_ref']) + '
源 OBJ 静态预览,不代表物体姿态投影
') + report = validate_view(view) + destination.mkdir(parents=True, exist_ok=True) + title = view.parent.name + '_' + view.name + style = 'body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;background:#f5f7fa;color:#18232f}section,details{background:white;padding:1rem;margin:1rem 0;border-radius:8px}.panels{display:flex;flex-wrap:wrap}img{max-width:100%}pre{white-space:pre-wrap;overflow:auto;font-size:12px}' + page = '' + html.escape(title) + '

' + html.escape(title) + '

预览只作人工核查;仅显示真实存在的标注,不合成分割。

' + ''.join(pages) + '

源网格

' + ''.join(assets) + '
全部组件元数据
' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '
持久化 QC
' + html.escape(json.dumps(report, ensure_ascii=False, indent=2)) + '
' + (destination / (title + '.html')).write_text(page) + (destination / (title + '.report.json')).write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') + links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html') + (destination / 'index.html').write_text('

H2O 试点预览

') + return destination / (title + '.html') + + +if __name__ == '__main__': + p = argparse.ArgumentParser() + p.add_argument('views', nargs='+', type=Path) + p.add_argument('--out', type=Path, required=True) + args = p.parse_args() + for view in args.views: + print(render(view, args.out), flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_hoi4d_source_review.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_hoi4d_source_review.py new file mode 100644 index 0000000000000000000000000000000000000000..79d7a58744572343670e9cbaecc4cc54ea07f1c1 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_hoi4d_source_review.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Evidence-only HTML: native HOI4D pose boxes over persisted RGB and native masks.""" +import argparse +import html +import json +from pathlib import Path +import shutil +import zipfile + +import numpy as np +from PIL import Image, ImageDraw + +from render_hoi4d_validation import picture, snapshot + + +def source_parts(view): + rows = [] + for source in view.glob('annotation/object/*/assets/result.json'): + def visit(node): + if isinstance(node, list): + for child in node: + visit(child) + return + if node.get('objs'): + rows.append({'source_part_id': node['id'], 'source_part_name': node['name'], + 'source_meshes': node['objs'], 'source_locator': str(source.relative_to(view))}) + for child in node.get('children', []): + visit(child) + visit(json.loads(source.read_text())) + return rows + + +def render(view, z, output): + output.mkdir(parents=True, exist_ok=True) + meta = json.loads((view / 'metainfo.json').read_text()) + seq = meta['sampling']['selection']['source_sequence'] + w, h = meta['camera']['image_size'] + chosen = sorted({0, meta['num_frames'] // 2, meta['num_frames'] - 1}) + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + rgb = snapshot(view / meta['components']['rgb']['data_ref'], 'rgb24', (h, w, 3), np.uint8, chosen) + segment = meta['components'].get('segment', {}) + masks = (snapshot(view / segment['data_ref'], 'gray16le', (h, w), '

' + html.escape(seq) + f' / frame {native_id}

' + picture(image) + + '

仅验收:伪彩=原生分割码,黄框=上游 2dBox;颜色和框不写回 shared,空间重叠不能代替身份依据。

' + + '
上游原记录与编码对照
'
+                      + html.escape(json.dumps(note, ensure_ascii=False, indent=2)) + '
') + parts = source_parts(view) + name = view.parent.name + '_' + view.name + '.html' + page = 'HOI4D source correspondence review

源姿态/原生分割/RGB 的证据图(非真值修改)

' + page += ''.join(panels) + '
CAD result.json 原生部件→OBJ;不等同逐帧姿态对应
'
+    page += html.escape(json.dumps(parts, ensure_ascii=False, indent=2)) + '
' + (output / name).write_text(page) + print(name, 'native_part_links',len(parts),flush=True) + return name + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--raw-root', type=Path, required=True) + p.add_argument('--release', type=Path, required=True) + p.add_argument('--out', type=Path, required=True) + args = p.parse_args(argv) + args.out.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(args.raw_root / 'HOI4D_annotations.zip') as z: + names = [] + for view in sorted((args.release / 'data').glob('*/ego')): + if any('/C' + category + '/' in json.loads((view / 'metainfo.json').read_text())['sampling']['selection']['source_sequence'] + for category in ('2', '3', '14', '17')): + names.append(render(view, z, args.out)) + links = ''.join(f'
  • {html.escape(name)}
  • ' for name in names) + (args.out / 'index.html').write_text('

    源依据对照(非物体几何验收通过)

      ' + links + '
    ') + shutil.copyfile(Path(__file__), args.out / 'renderer.py') + + +if __name__ == '__main__': + main() diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_hoi4d_validation.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_hoi4d_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..a7889a1b63b004e046b52fe4e4da0b2b4651b768 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/render_hoi4d_validation.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Standalone, offline HTML review of every persisted component in selected views.""" +import argparse +import base64 +import html +import io +import json +import random +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw +import torch + +from warehouse_v1_0 import video_frames, unpack_depth, validate_view + + +def snapshot(video, fmt, shape, dtype, indices): + return {i: frame.copy() for i, frame in enumerate(video_frames(video, fmt, shape, dtype)) if i in indices} + + +def picture(image): + image.thumbnail((800, 450)) # Previews only; released tensors and videos are not resized. + output = io.BytesIO() + image.save(output, format='PNG') + return '' + + +def preview_color(value, dataset_id): + # Dex-YCB reserves 255 for the native hand mask. The old mod-240 palette + # gave it the same color as YCB object 15; keep data codes untouched. + if dataset_id == 'dex-ycb' and value == 255: + return (255, 32, 64) + return tuple((value * factor) % 240 + 15 for factor in (89, 61, 131)) + + +def mesh_preview(path): + """Project the whole source asset; bound drawing cost without favoring early faces.""" + vertices, faces, referenced = [], [], set() + rng = random.Random(0) + face_count = 0 + with path.open(errors='replace') as stream: + for line in stream: + if line.startswith('v '): + vertices.append([float(v) for v in line.split()[1:4]]) + elif line.startswith('f '): + face = [] + for token in line.split()[1:]: + index = int(token.split('/')[0]) + face.append(index - 1 if index > 0 else len(vertices) + index) + if len(face) < 3: + continue + referenced.update(face) + face_count += 1 + # ponytail: bounded static preview; use a full OBJ viewer if 5000 faces miss fine detail. + if len(faces) < 5000: + faces.append(face) + else: + pick = rng.randrange(face_count) + if pick < len(faces): + faces[pick] = face + if not vertices or not faces: + return 'OBJ 未提供可绘制的顶点/面' + if min(referenced) < 0 or max(referenced) >= len(vertices): + raise ValueError(f'invalid OBJ face index: {path}') + xyz = np.asarray(vertices, dtype=np.float64) + if not np.isfinite(xyz).all(): + raise ValueError(f'nonfinite OBJ vertex: {path}') + # Fixed orthonormal isometric basis: geometry only, not an inferred camera pose. + projected = np.column_stack(((xyz[:, 0] - xyz[:, 2]) / np.sqrt(2), + (xyz[:, 0] + xyz[:, 2] - 2 * xyz[:, 1]) / np.sqrt(6))) + used = projected[np.fromiter(referenced, dtype=np.int64)] + lo, hi = used.min(axis=0), used.max(axis=0) + extent = (hi - lo).max() + if extent <= 0: + return 'OBJ 所有面投影到同一点' + projected = (projected - (lo + hi) / 2) * (380 / extent) + 215 + image = Image.new('RGB', (430, 430), 'white') + draw = ImageDraw.Draw(image) + for face in faces: + polygon = [tuple(projected[i]) for i in face] + draw.line(polygon + [polygon[0]], fill='#205caa', width=1) + return picture(image) + + +def render(view, destination): + meta = json.loads((view / 'metainfo.json').read_text()) + n = meta['num_frames'] + width, height = meta['camera']['image_size'] + components = meta['components'] + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + assert len(frames) == n + selected = {0, n // 4, n // 2, 3 * n // 4, n - 1} + for item in components.values(): + ref = item.get('valid_ref', '') + if ref.endswith('.pt'): + valid = torch.load(view / ref, map_location='cpu', weights_only=True).numpy() + if valid.shape[0] == n: + matching = np.flatnonzero(valid.reshape(n, -1).any(axis=1)) + if len(matching): + selected.add(int(matching[0])) + selected = set(sorted(selected)[:12]) | {n - 1} + rgb = snapshot(view / components['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected) + depth = (snapshot(view / components['depth']['data_ref'], 'gray16le', (height, 2 * width), '' + picture(image) + '
    RGB + 原生 2D 手关键点(若有)
    '] + if i in depth: + z = unpack_depth(depth[i]) + luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(luminance)) + '
    深度 Z(黑=无效,白≥3 m;仅预览)
    ') + if i in masks: + mask = masks[i] + colors = np.zeros((*mask.shape, 3), dtype=np.uint8) + for value in np.unique(mask): + if value not in (0, 65535): + colors[mask == value] = preview_color(int(value), meta['dataset_id']) + legend = ';'.join(f'{int(value)}=' + ('手' if value == 255 and meta['dataset_id'] == 'dex-ycb' else '物体' if meta['dataset_id'] == 'dex-ycb' else '区域') + f' #{bytes(preview_color(int(value), meta["dataset_id"])).hex()}' for value in np.unique(mask) if value not in (0, 65535)) + panels.append('
    ' + picture(Image.fromarray(colors)) + '
    原生分割整数编码的伪彩色预览(' + html.escape(legend) + ')
    ') + active = (mask != 0) & (mask != 65535) + overlay = rgb[i].copy() + overlay[active] = ((overlay[active].astype(np.uint16) + colors[active]) // 2).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(overlay)) + '
    原生分割叠加 RGB(仅预览)
    ') + details = {'frame': frames[i], 'segment_labels': labels.get(i, [])} + for name, component in components.items(): + ref = component.get('data_ref', '') + if component.get('available') and ref.endswith('.pt'): + values = torch.load(view / ref, map_location='cpu', weights_only=True) + if values.ndim and values.shape[0] == n: + details[name] = {'value': values[i].tolist()} + if component.get('valid_ref', '').endswith('.pt'): + valid = torch.load(view / component['valid_ref'], map_location='cpu', weights_only=True) + details[name]['valid'] = valid[i].tolist() + sections.append('

    帧 ' + str(i) + ' / ' + str(n) + '

    ' + ''.join(panels) + + '
    帧号、来源、全部数值组件与有效性
    '
    +                        + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '
    ') + assets = [] + for name, component in components.items(): + if component.get('available') and component['data_ref'].lower().endswith('.obj'): + ref = component['data_ref'] + assets.append('

    ' + html.escape(name) + '

    ' + mesh_preview(view / ref) + + '
    仅展示网格原生形状;未验证尺度/位姿对应。
    ') + result = validate_view(view) + destination.mkdir(parents=True, exist_ok=True) + title = view.parent.name + '_' + view.name + css = 'body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;background:#f5f7fa;color:#18232f}section,details{background:#fff;padding:1rem;margin:1rem 0;border-radius:8px}figure{margin:.5rem}figcaption{font-size:.85rem}.panels{display:flex;flex-wrap:wrap}img{max-width:100%;border:1px solid #ddd}pre{white-space:pre-wrap;overflow:auto;font-size:12px}' + page = '' + html.escape(title) + '

    ' + html.escape(title) + '

    预览图仅供人工审核,不是训练输入;未提供的模态在 metainfo 中保留原因。

    ' + ''.join(sections) + '

    原始物体模型(独立预览)

    ' + ''.join(assets) + '
    全部组件元信息及原始来源
    ' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '
    持久化 QC 结果
    ' + html.escape(json.dumps(result, ensure_ascii=False, indent=2)) + '
    ' + (destination / (title + '.html')).write_text(page) + (destination / (title + '.report.json')).write_text(json.dumps(result, ensure_ascii=False, indent=2)) + links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html') + (destination / 'index.html').write_text('' + html.escape(meta['dataset_id']) + ' review

    ' + html.escape(meta['dataset_id']) + ' 抽样人工审核

    选择视图;所有预览均来自已保存的 shared 数据。

    ') + print(destination / (title + '.html'), 'selected_frames', sorted(selected), flush=True) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('views', nargs='+', type=Path) + p.add_argument('--out', type=Path) + args = p.parse_args() + for view in args.views: + render(view, args.out or view.parents[2] / 'doc/validation') + + +if __name__ == '__main__': + main() diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/run-full.sh b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/run-full.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d27d5547332f029b9d2e92108469ad40bc121e6 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/run-full.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -u +base="$HOME/Datasets/uni-hoi-h2o-full-20260929-r1" +raw="$HOME/Datasets/Hand-Datasets-Raw/H2O" +cd "$HOME/Projects/uni-hoi-dataset" || exit 1 +mkdir -p "$base/scratch" +export TMPDIR="$base/scratch" PYTHONUNBUFFERED=1 +for n in 1 2 3 4; do test -s "$raw/raw/data/subject${n}_v1_1.tar.gz" || exit 2; done +test ! -e "$base/H2O/shared-v1.0" || exit 3 +cg=$(awk -F: '$1=="0" {print $3}' /proc/self/cgroup) +read -r quota period < "/sys/fs/cgroup$cg/cpu.max" +cpus=$(getconf _NPROCESSORS_ONLN) +printf 'START=%s\nWORKERS=2 CODEC_THREADS=4 SUBJECTS=1,2,3,4 CASA=false\nCPU_BUDGET_PERCENT=80 LOGICAL_CPUS=%s\nCGROUP=%s\nCPU_MAX=%s %s\n' "$(date -Is)" "$cpus" "$cg" "$quota" "$period" > "$base/full.status" +if [[ "$quota" == max ]] || (( quota * 100 > cpus * period * 80 )); then + printf 'EXIT=4 ERROR=CPU_QUOTA_NOT_ENFORCED\n' >> "$base/full.status" + exit 4 +fi +/usr/bin/time -v .venv/bin/python "$base/frozen-code/scripts/convert_h2o_v1.0.py" --root "$raw" --out "$base" --release-id shared-v1.0 --workers 2 --codec-threads 4 --mano-dir "$HOME/Projects/WiLoR/mano_data" > "$base/full.log" 2>&1 +code=$? +printf 'EXIT=%s END=%s\n' "$code" "$(date -Is)" >> "$base/full.status" +cat "/sys/fs/cgroup$cg/cpu.stat" >> "$base/full.status" +exit "$code" diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/warehouse_v1_0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/warehouse_v1_0.py new file mode 100644 index 0000000000000000000000000000000000000000..f705011bcea587bd320e1e228f99bed259b32b3a --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/script/warehouse_v1_0.py @@ -0,0 +1,931 @@ +"""Shared I/O for CONTRACT.md v1.0. No annotation synthesis.""" +import argparse +from contextlib import contextmanager +from functools import lru_cache +import hashlib +import json +import math +import shlex +from pathlib import Path +import pickle +import random +import shutil +import subprocess +import tempfile +import time + +import numpy as np +from PIL import Image +import torch + +SCHEMA_PATH = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/schema.json', + Path(__file__).resolve().parents[1] / 'doc/schema.json') if p.is_file()) +SCHEMA = json.loads(SCHEMA_PATH.read_text()) +RAW_ROOT = Path.home() / 'Datasets/Hand-Datasets-Raw' + + +def json_write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + '\n') + + +def jsonl_write(path, rows): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('w') as out: + for row in rows: + out.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + '\n') + + +def sha256(path): + with Path(path).open('rb') as f: + return hashlib.file_digest(f, 'sha256').hexdigest() + + +def locator(path, member=None, data=None, **extra): + result = {'file': str(Path(path).resolve())} + if member is not None: + result['member'] = member + if data is not None: + result['sha256'] = hashlib.sha256(data).hexdigest() + return result | extra + + +def source(method='Copy source annotation; normalize storage only'): + return {'kind': 'format_conversion', 'method': method} + + +def run(args, **kwargs): + return subprocess.run(args, check=True, stderr=subprocess.PIPE, **kwargs) + + +@lru_cache(maxsize=1) +def ffversion(): + return run(['ffmpeg', '-version'], stdout=subprocess.PIPE).stdout.decode().splitlines()[0] + + +def probe(path): + return json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', + '-show_streams', '-of', 'json', str(path)], + stdout=subprocess.PIPE).stdout)['streams'][0] + + +def decode_args(path, pixel_format): + return ['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', '1', '-threads', '1', '-noautorotate', + '-i', str(path), '-map', '0:v:0', '-vsync', '0', '-threads', '1', + '-f', 'rawvideo', '-pix_fmt', pixel_format] + + +def decoded_digest(path, pixel_format): + start = time.monotonic() + with tempfile.TemporaryFile() as err: + proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'], + stdout=subprocess.PIPE, stderr=err) + digest, size = hashlib.sha256(), 0 + with proc.stdout: + while chunk := proc.stdout.read(1024 * 1024): + digest.update(chunk) + size += len(chunk) + if proc.wait(): + err.seek(0) + raise RuntimeError(err.read().decode(errors='replace')) + return digest.hexdigest(), size, time.monotonic() - start + + +def video_frames(path, pixel_format, shape, dtype): + frame_bytes = int(np.prod(shape)) * np.dtype(dtype).itemsize + with tempfile.TemporaryFile() as err: + proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'], stdout=subprocess.PIPE, stderr=err) + completed = False + try: + while True: + data = proc.stdout.read(frame_bytes) + if not data: + break + if len(data) != frame_bytes: + raise ValueError('truncated decoded video frame') + yield np.frombuffer(data, dtype=dtype).reshape(shape) + if proc.wait(): + err.seek(0) + raise ValueError(err.read().decode(errors='replace')) + completed = True + finally: + proc.stdout.close() + if not completed and proc.poll() is None: + proc.terminate() + proc.wait() + + +def storage(path, profile, parameters, source_lossy): + info = probe(path) + if info['codec_name'] == 'h264': + frames = json.loads(run(['ffprobe', '-v', 'error', '-threads', '1', '-select_streams', 'v:0', + '-show_entries', 'frame=key_frame', '-of', 'json', str(path)], stdout=subprocess.PIPE).stdout)['frames'] + parameters = parameters | {'keyframe_indices': [i for i, f in enumerate(frames) if f['key_frame']]} + return {'profile': profile, 'codec': info['codec_name'], + 'pixel_format': info['pix_fmt'], 'encoded_size': [info['width'], info['height']], + 'decoder': {'name': 'ffmpeg', 'version': ffversion(), 'autorotate': False, + 'color_space': info.get('color_space', 'unknown'), + 'color_range': info.get('color_range', 'unknown'), + 'color_primaries': info.get('color_primaries', 'unknown'), + 'color_transfer': info.get('color_transfer', 'unknown')}, + 'encoder_parameters': {'version': ffversion()} | parameters, + 'source_lossy': source_lossy, 'storage_fps': 30, 'timebase_role': 'index_only'} + + +def encode_raw(raw, target, width, height, pixel_format, profile, codec='ffv1', extra=(), threads=1): + start = time.monotonic() + run(['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', '1', '-y', '-f', 'rawvideo', + '-pixel_format', pixel_format, '-video_size', f'{width}x{height}', '-framerate', '30', + '-i', str(raw), '-an', '-c:v', codec, '-threads', str(threads), *extra, str(target)]) + digest, size, decode_seconds = decoded_digest(target, pixel_format) + if size != Path(raw).stat().st_size or digest != sha256(raw): + raise ValueError(f'lossless roundtrip failed: {target}') + config = storage(target, profile, {'name': codec, 'arguments': list(extra), 'threads': threads}, False) + return config, {'bytes': target.stat().st_size, 'encode_seconds': time.monotonic() - start - decode_seconds, + 'decode_seconds': decode_seconds, 'decoded_sha256': digest, 'all_frames_exact': True} + + +def measure_rgb_access(video, raw, width, height, count): + index = count // 2 + start = time.monotonic() + data = run(['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', '1', '-threads', '1', '-noautorotate', + '-i', str(video), '-vf', f'select=eq(n\\,{index})', '-frames:v', '1', '-threads', '1', + '-f', 'rawvideo', '-pix_fmt', 'rgb24', 'pipe:1'], stdout=subprocess.PIPE).stdout + with raw.open('rb') as inp: + inp.seek(index * width * height * 3) + if data != inp.read(width * height * 3): + raise ValueError('exact indexed RGB read failed') + return {'random_access_strategy': 'decode from first keyframe; select exact presentation index', + 'random_frame_index': index, 'random_frame_read_seconds': time.monotonic() - start} + + +def jpeg_sample_indices(sequence, camera, count): + seed = int.from_bytes(hashlib.sha256(f'{sequence}/{camera}/20260920'.encode()).digest()[:8], 'big') + indices = {0, count - 1, count // 4, count // 2, 3 * count // 4} + indices.update(random.Random(seed).sample([i for i in range(count) if i not in indices], + min(count, 16) - len(indices))) + return sorted(indices), seed + + +def check_jpeg_copy(target, paths, hashes, size, sequence, camera, full): + packets = json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', + '-show_packets', '-show_data_hash', 'sha256', '-of', 'json', str(target)], + stdout=subprocess.PIPE).stdout)['packets'] + if [p['data_hash'].split(':', 1)[1].lower() for p in packets] != hashes: + raise ValueError('JPEG packet hashes/order/count differ') + info = probe(target) + if [info['width'], info['height']] != list(size): + raise ValueError('JPEG container dimensions differ') + indices, seed = jpeg_sample_indices(sequence, camera, len(paths)) + if full: + indices = list(range(len(paths))) + select = '+'.join(f'eq(n\\,{i})' for i in indices) + frame_bytes = size[0] * size[1] * 3 + # Spool selected frames to disk, keeping RAM bounded for full-view audits. + with tempfile.TemporaryFile() as decoded: + run(decode_args(target, 'rgb24') + ([] if full else ['-vf', 'select=' + select]) + ['pipe:1'], stdout=decoded) + decoded.seek(0) + for i in indices: + expected = run(decode_args(paths[i], 'rgb24') + ['pipe:1'], stdout=subprocess.PIPE).stdout + if len(expected) != frame_bytes or decoded.read(frame_bytes) != expected: + raise ValueError(f'JPEG decoded pixels differ at frame {i}') + if decoded.read(1): + raise ValueError('JPEG selected pixel count differs') + return {'policy': 'jpeg-packets-all-rgb-sample16/v1', 'seed': seed, + 'selected_frame_indices': indices, 'pixel_frames_checked': len(indices), + 'packet_frames_checked': len(paths), 'jpeg_packets_exact': True, + 'packet_count_order_dimensions_exact': True, 'sampled_pixels_exact': True, + 'all_frames_exact': len(indices) == len(paths), 'full_view_audit': full} + + +def rgb_video(paths, target, work, video=None, count=None, sequence="", camera="", full_jpeg=False, + ffv1_first=False, codec_threads=1): + """JPEG packet proof plus deterministic pixels; re-encodings compare all pixels.""" + target.parent.mkdir(parents=True, exist_ok=True) + raw = work / 'rgb.raw' + packets = [] + has_missing = video is None and any(p is None for p in paths) + if has_missing: + present = next((p for p in paths if p is not None), None) + if present is None: + raise ValueError('no source RGB image to establish the pixel format/grid') + original = probe(present) + width, height = original['width'], original['height'] + with raw.open('wb') as dest: + for path in paths: + if path is None: + dest.write(bytes(width * height * 3)) + else: + with Image.open(path) as im: + if im.mode != 'RGB' or im.size != (width, height): + raise ValueError('source RGB grid/type changes within view') + run(decode_args(path, 'rgb24') + ['pipe:1'], stdout=dest) + lossy, count = 'unknown', len(paths) + input_args = None + elif video is None: + if not paths: + raise ValueError('RGB timeline must contain existing source images') + suffix = paths[0].suffix.lower() + if suffix not in ('.jpg', '.jpeg', '.png'): + raise ValueError('unsupported source RGB format') + images = work / 'rgb_source' + images.mkdir() + dimensions = None + for i, path in enumerate(paths): + with Image.open(path) as im: + if im.mode != 'RGB' or (dimensions is not None and dimensions != im.size): + raise ValueError('RGB must be homogeneous 8-bit RGB, with no silent color/size conversion') + dimensions = im.size + if im.format == 'PNG' and path.read_bytes()[24] != 8: + raise ValueError('high bit depth RGB needs a registered schema') + dest = images / f'{i:08d}{suffix}' + shutil.copyfile(path, dest) + packets.append(sha256(path)) + width, height = dimensions + input_args = ['-framerate', '30', '-i', str(images / ('%08d' + suffix))] + count = len(paths) + original = probe(paths[0]) + lossy = suffix in ('.jpg', '.jpeg') + else: + original = probe(video) + if int(original.get('bits_per_raw_sample') or 8) > 8 or any( + x in original.get('pix_fmt', '') for x in ('10', '12', '16', 'f32')): + raise ValueError('high bit depth RGB needs a registered schema') + width, height = original['width'], original['height'] + input_args = ['-i', str(video)] + lossy = 'unknown' + limits = ['-frames:v', str(count)] if count else [] + records = [] + if video is None and not has_missing and suffix in ('.jpg', '.jpeg'): + start = time.monotonic() + try: + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0', + *limits, '-c:v', 'copy', '-an', str(target)]) + encode_seconds = time.monotonic() - start + validation = check_jpeg_copy(target, paths, packets, (width, height), sequence, camera, full_jpeg) + cfg = storage(target, 'mkv/mjpeg_copy/v1', {'stream_copy': True}, lossy) + cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in + ('color_space', 'color_range', 'color_primaries', 'color_transfer')} + records.append(validation | {'profile': cfg['profile'], 'bytes': target.stat().st_size, + 'encode_seconds': encode_seconds, 'validation_seconds': time.monotonic() - start - encode_seconds}) + return cfg, [width, height], records, count + except (subprocess.CalledProcessError, ValueError) as exc: + records.append({'profile': 'mkv/mjpeg_copy/v1', 'rejected': str(exc)}) + target.unlink(missing_ok=True) + if not has_missing: + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', '-threads', '1', '-noautorotate', + *input_args, '-map', '0:v:0', *limits, '-vsync', '0', '-threads', '1', + '-f', 'rawvideo', '-pix_fmt', 'rgb24', str(raw)]) + frame_bytes = width * height * 3 + actual, remainder = divmod(raw.stat().st_size, frame_bytes) + if remainder or not actual or (count is not None and actual != count): + raise ValueError('source RGB frame count mismatch') + expected_hash = sha256(raw) + can_copy = video is not None + if can_copy: + start = time.monotonic() + try: + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0', + *limits, '-c:v', 'copy', '-an', str(target)]) + digest, size, seconds = decoded_digest(target, 'rgb24') + if digest != expected_hash or size != raw.stat().st_size: + raise ValueError('stream-copy RGB bytes/order/count mismatch') + cfg = storage(target, 'mkv/source_copy/v1', + {'stream_copy': True}, lossy) + if video: + cfg['storage_fps'] = original.get('avg_frame_rate') + cfg['preserve_source_pts'] = True + records.append({'profile': cfg['profile'], 'all_frames_exact': True, + 'decoded_sha256': digest, + 'bytes': target.stat().st_size, 'decode_seconds': seconds, + 'encode_seconds': time.monotonic() - start - seconds}) + records[-1].update(measure_rgb_access(target, raw, width, height, actual)) + return cfg, [width, height], records, actual + except (subprocess.CalledProcessError, ValueError) as exc: + records.append({'profile': 'stream_copy', 'rejected': str(exc)}) + target.unlink(missing_ok=True) + candidates = [] + for profile, codec, params in [ + ('mkv/ffv1_rgb/v1', 'ffv1', ['-level', '3', '-pix_fmt', 'bgr0']), + ('mkv/h264_rgb_lossless/v1', 'libx264rgb', ['-crf', '0', '-preset', 'medium', '-g', '30'])]: + path = work / (codec + '.mkv') + try: + cfg, record = encode_raw(raw, path, width, height, 'rgb24', profile, codec, params, + codec_threads if codec == 'ffv1' else 1) + cfg['source_lossy'] = lossy + cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in + ('color_space', 'color_range', 'color_primaries', 'color_transfer')} + record['profile'] = profile + record.update(measure_rgb_access(path, raw, width, height, actual)) + records.append(record) + candidates.append((path.stat().st_size, path, cfg)) + if ffv1_first and codec == 'ffv1': + break # Keep the H.264 fallback only if the preferred exact encoder fails. + except subprocess.CalledProcessError as exc: + records.append({'profile': profile, 'rejected': exc.stderr.decode(errors='replace')}) + if not candidates: + raise ValueError('no supported lossless RGB encoder') + _, chosen, cfg = min(candidates, key=lambda x: x[0]) + shutil.move(chosen, target) + return cfg, [width, height], records, actual + + +def pack_depth(depth): + bits = np.ascontiguousarray(depth, dtype='> 16).astype(' 0) + arr[~good] = np.nan + out.write(pack_depth(arr).tobytes()) + vo.write(good.astype(np.uint8).tobytes()) + else: + if not np.issubdtype(arr.dtype, np.integer) or arr.min() < 0 or arr.max() > 65535: + raise ValueError('invalid segmentation region codes') + out.write(arr.astype(' vertices: + raise ValueError('empty or invalid mesh') + def dependency(parent, name): + dep = (parent / name).resolve() + if not dep.is_relative_to(asset_root) or not dep.is_file(): + raise ValueError(f'missing or escaping asset dependency: {name}') + return dep + dependencies = [] + for name in materials: + mtl = dependency(path.parent, name) + dependencies.append(mtl) + for line in mtl.read_text().splitlines(): + fields = shlex.split(line, comments=True) + if fields and (fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal')): + dependencies.append(dependency(mtl.parent, fields[-1])) + return {'vertices': vertices, 'faces': faces, 'sha256': sha256(path), + 'dependencies': {p.relative_to(asset_root).as_posix(): sha256(p) for p in dependencies}} + + +def mesh_asset(view, oid, directory, obj, loc): + dest = view.path / f'annotation/object/{oid}/assets' + shutil.copytree(directory, dest) + ref = (dest / Path(obj).relative_to(directory)).relative_to(view.path).as_posix() + mesh_check = check_mesh(dest / Path(obj).relative_to(directory), dest) + view.build['validation'].append({'component': f'mesh_{oid}', **mesh_check}) + view.component(f'mesh_{oid}', 'mesh/obj/v1', ref, ['vertex'], loc, valid=True, unit='m') + p = view.path / f'annotation/object/{oid}/metainfo.json' + info = json.loads(p.read_text()) + info.update(has_model=True, mesh_ref=ref) + json_write(p, info) + + +def safe_member(root, name): + path = (Path(root) / name).resolve() + if not path.is_relative_to(Path(root).resolve()): + raise ValueError(f'unsafe archive path: {name}') + return path + + +class ChumpyStub: + def __setstate__(self, state): + self.__dict__.update(state) + + +class ManoUnpickler(pickle.Unpickler): + def find_class(self, module, name): + if module.startswith('chumpy'): + return ChumpyStub + return super().find_class(module, name) + + +def mano_models(directory): + result = {} + if directory is None: + return result + for side in ('left', 'right'): + path = Path(directory).expanduser() / f'MANO_{side.upper()}.pkl' + if not path.exists(): + continue + with path.open('rb') as f: + data = ManoUnpickler(f, encoding='latin1').load() + result[side] = {'components': np.asarray(data['hands_components']), + 'mean': np.asarray(data['hands_mean']), 'sha256': sha256(path), + 'file': path.name} + return result + + +def model_profile(models): + identity = json.dumps({side: d['sha256'] for side, d in sorted(models.items())}).encode() + return {'version': 'sha256:' + hashlib.sha256(identity).hexdigest(), 'flat_hand_mean': True, + 'left_shapedirs_correction': 'not_applied', + 'models': {side: {'file': d['file'], 'sha256': d['sha256']} for side, d in models.items()}} + + +def pca_to_axis_angle(coeffs, model): + coeffs = np.asarray(coeffs) + if coeffs.shape[-1:] != (45,) or not np.isfinite(coeffs).all(): + raise ValueError('invalid MANO PCA coefficients') + return coeffs @ model['components'] + model['mean'] + + +def parser(dataset, description): + p = argparse.ArgumentParser(description=description) + p.add_argument('--root', f'--{dataset.lower()}-root', dest='root', type=Path, default=RAW_ROOT / dataset) + p.add_argument('--out', type=Path, default=Path('converted')) + p.add_argument('--release-id', default='v1.0') + p.add_argument('--limit', type=int, help='Maximum sequences to convert') + p.add_argument('--max-frames', type=int, help='First N source frame indices per view (recorded as sampling)') + p.add_argument('--mano-dir', type=Path) + p.add_argument('--views', help='Comma-separated source camera IDs') + p.add_argument('--jpeg-full-check', action='store_true', help='Full decoded RGB check for selected JPEG pilot/final views') + return p + + +def roots(root): + root = Path(root).expanduser() + return [p for p in (root / 'raw/data', root / 'raw', root) if p.is_dir()] + + +def find_file(root, name): + return next((p / name for p in roots(root) if (p / name).exists()), None) + + +def release(args, dataset): + if not args.release_id or Path(args.release_id).name != args.release_id or args.release_id in ('.', '..'): + raise ValueError('release-id must be a single directory name') + if args.limit is not None and args.limit < 1 or args.max_frames is not None and args.max_frames < 1: + raise ValueError('limits must be positive') + out = args.out.expanduser().resolve() / dataset / args.release_id + raw = args.root.expanduser().resolve() + if out == raw or out.is_relative_to(raw): + raise ValueError('output must not modify the raw source tree') + (out / 'data').mkdir(parents=True, exist_ok=True) + (out / 'doc').mkdir(exist_ok=True) + (out / 'script').mkdir(exist_ok=True) + scripts = list(Path(__file__).resolve().parent.glob('*.py')) + existing = {p.name for p in (out / 'script').glob('*.py')} + if existing and existing != {p.name for p in scripts}: + raise ValueError('converter files changed; choose a new --release-id') + copies = [(SCHEMA_PATH.parent / name, out / 'doc' / name) for name in ('CONTRACT.md', 'schema.json')] + copies += [(path, out / 'script' / path.name) for path in scripts] + # Check every existing file before changing any published definition or script. + for src, dest in copies: + if dest.exists() and sha256(dest) != sha256(src): + raise ValueError('converter or contract changed within an existing release; choose a new --release-id') + for src, dest in copies: + if src.resolve() != dest.resolve(): + shutil.copyfile(src, dest) + json_write(out / 'script/config.json', {k: str(v) if isinstance(v, Path) else v for k, v in vars(args).items()}) + return out + + +@contextmanager +def sequence_dir(out, sequence): + if Path(sequence).name != sequence: + raise ValueError('sequence ID must be a single path component') + final = out / 'data' / sequence + with tempfile.TemporaryDirectory(prefix=sequence + '.tmp-', dir=out / 'data') as wd: + tmp = Path(wd) + yield tmp + if final.exists(): + if any((final / child.name).exists() for child in tmp.iterdir()): + raise FileExistsError('view already published; use a new release-id to preserve it') + for child in list(tmp.iterdir()): + child.rename(final / child.name) + else: + tmp.rename(final) + + +def build_record(out, sequence, reports): + path = out / 'doc' / (sequence + '.build.json') + previous = json.loads(path.read_text()) if path.exists() else {} + config = json.loads((out / 'script/config.json').read_text()) + for report in reports.values(): + report['configuration'] = config + json_write(path, {'sequence_id': sequence, 'storage_revision': SCHEMA['storage_revision'], + 'scripts': {p.name: sha256(p) for p in (out / 'script').glob('*.py')}, + 'runtime': {'torch': torch.__version__, 'ffmpeg': ffversion()}, + 'views': previous.get('views', {}) | reports}) + + +def check_view_type(meta): + # The pinned ARCTIC contract makes view_type optional; adapters still supply known views. + if 'view_type' not in meta: + return + if meta['view_type'] not in ('ego', 'exo', 'unknown'): + raise ValueError('view_type must be ego/exo/unknown') + expected = {'dex-ycb': 'exo', 'EPIC-KITCHENS-VISOR': 'ego', 'HOI4D': 'ego'}.get(meta['dataset_id']) + if meta['dataset_id'] == 'H2O': + expected = 'ego' if meta['camera_id'] == 'cam4' else 'exo' if meta['camera_id'] in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown' + if expected and meta['view_type'] not in (expected, 'unknown'): + raise ValueError('view_type contradicts known source capture setup') + + +def check_valid_policy(component, count): + policy = component.get('valid_policy', {}) + for field in ('revision', 'meaning', 'source_rule', 'source_locator', 'scope', 'numerical_checks', + 'official_qa', 'local_excluded_frame_indices', 'local_exclusion_reasons', 'visibility_independent'): + if field not in policy: + raise ValueError(f'valid_policy missing {field}') + if policy['revision'] != SCHEMA['validity_revision'] or policy['meaning'] != SCHEMA['annotation_validity']['meaning']: + raise ValueError('outdated annotation validity semantics') + if not policy['source_rule'] or not policy['numerical_checks'] or policy['scope'] != component['valid_axes']: + raise ValueError('incomplete validity rule/scope') + if policy['official_qa'].get('status') != 'not_provided' or not policy['official_qa'].get('reason'): + raise ValueError('official QA requires a verified adapter; supervision acceptance paused') + excluded = policy['local_excluded_frame_indices'] + if any(type(i) is not int or not 0 <= i < count for i in excluded): + raise ValueError('invalid local exclusion frame index') + if excluded: + raise ValueError('local exclusions require a reviewed rule/report; not supported by these adapters') + if policy['visibility_independent'] is not True: + raise ValueError('visibility must remain independent of validity') + + +def validate_view(path): + """Validate the persisted contract, not a rendering of the source labels.""" + path = Path(path) + meta = json.loads((path / 'metainfo.json').read_text()) + n = meta['num_frames'] + check_view_type(meta) + if meta['schema_version'] != SCHEMA['schema_version'] or meta['hand_slots'] != ['left', 'right'] or n < 1: + raise ValueError('invalid view header') + def resolve(ref): + if Path(ref).is_absolute() or '\\' in ref: + raise ValueError('component reference must be relative POSIX') + dest = safe_member(path, ref) + if not dest.is_file(): + raise ValueError(f'referenced file missing: {ref}') + return dest + def tensor(ref): + def cpu_storage(storage, location): + if location != 'cpu': + raise ValueError('PT storage must be on CPU') + return storage + value = torch.load(resolve(ref), map_location=cpu_storage, weights_only=True) + if not isinstance(value, torch.Tensor) or value.device.type != 'cpu': + raise ValueError('PT must contain only a CPU Tensor') + return value.numpy() + frames = [json.loads(line) for line in resolve(meta['sampling']['frames_ref']).read_text().splitlines()] + if len(frames) != n or [f['frame_index'] for f in frames] != list(range(n)): + raise ValueError('frame index/count mismatch') + for f in frames: + if not all(k in f for k in ('source_frame_id', 'timestamp_ns', 'clock_domain', 'source_locator')): + raise ValueError('incomplete frame provenance') + entities = {'hand_left', 'hand_right'} + parts = {} + for p in (path / 'annotation/object').glob('*/metainfo.json'): + obj = json.loads(p.read_text()) + if obj['object_id'] != p.parent.name or obj['identity_scope'] not in ('frame', 'subsequence', 'sequence'): + raise ValueError('invalid object identity') + entities.add(obj['object_id']) + if obj.get('mesh_ref'): + if not resolve(obj['mesh_ref']).is_relative_to(p.parent.resolve()): + raise ValueError('mesh must belong to its object') + if obj.get('articulation_ref'): + art = json.loads(resolve(obj['articulation_ref']).read_text()) + part_ids = {part['part_id'] for part in art['parts']} + if len(part_ids) != len(art['parts']): + raise ValueError('duplicate part ID') + parents = {part['part_id']: part['parent_id'] for part in art['parts']} + for part_id in parents: + visited, cur = set(), part_id + while cur is not None: + if cur in visited or cur not in parents: + raise ValueError('invalid or cyclic part hierarchy') + visited.add(cur) + cur = parents[cur] + parts[obj['object_id']] = part_ids + video_stats = {} + for key, component in meta['components'].items(): + if not component.get('available'): + if not component.get('reason'): + raise ValueError('unavailable component needs a reason') + continue + schema = SCHEMA['components'][component['schema_id']] + for required in ('axes', 'provenance', 'source_locator'): + if required not in component: + raise ValueError(f'{key}: {required} missing') + for required in schema.get('required_metadata', []): + if required not in component: + raise ValueError(f'{key}: {required} missing') + if component['provenance']['kind'] == 'derived': + raise ValueError('v1.0 must not synthesize annotations') + if component['data_ref'].startswith('annotation/') and schema.get('valid_shape'): + if not component.get('valid_ref') or not component.get('valid_axes'): + raise ValueError(f'{key}: annotation validity reference/axes missing') + check_valid_policy(component, n) + data_path = resolve(component['data_ref']) + valid = tensor(component['valid_ref']) if component.get('valid_ref', '').endswith('.pt') else None + valid_shape = schema.get('valid_shape') + if valid is not None and valid_shape and (len(valid_shape) != valid.ndim or any( + isinstance(s, int) and valid.shape[i] != s for i, s in enumerate(valid_shape))): + raise ValueError(f'{key}: validity schema shape mismatch') + if valid is not None and (valid.dtype != bool or valid.shape[0] != n): + raise ValueError(f'{key}: invalid validity tensor') + if component['schema_id'] == 'mesh/obj/v1': + objroot = next((parent for parent in data_path.parents if parent.parent.name == 'object'), None) + if objroot is None: + raise ValueError('mesh must be owned by an object') + check_mesh(data_path, objroot) + if data_path.suffix == '.pt': + arr = tensor(component['data_ref']) + if arr.dtype != np.float32 or arr.shape[0] != n: + raise ValueError(f'{key}: float dtype or timeline mismatch') + shape = schema.get('shape') + if shape and (len(shape) != arr.ndim or any(isinstance(s, int) and arr.shape[i] != s for i, s in enumerate(shape))): + raise ValueError(f'{key}: schema shape mismatch') + if valid is not None: + if arr.shape[:valid.ndim] != valid.shape or not np.isfinite(arr[valid]).all() or not np.isnan(arr[~valid]).all(): + raise ValueError(f'{key}: invalid finite/NaN/validity values') + if component['schema_id'] in ('object/rigid/v1', 'transform/se3/v1'): + check_transform(arr[valid]) + if data_path.suffix == '.mkv': + cfg = component['storage'] + if cfg['profile'] not in SCHEMA['storage_profiles']: + raise ValueError('unregistered video profile') + for field in SCHEMA['video_metadata']['required']: + if field not in cfg: + raise ValueError('video storage declaration incomplete') + w, h = meta['camera']['image_size'] + if cfg['encoded_size'] != [w * (2 if key == 'depth' else 1), h]: + raise ValueError('encoded raster differs from logical RGB grid') + actual = probe(data_path) + if (actual['codec_name'] != cfg['codec'] or actual['pix_fmt'] != cfg['pixel_format'] or + [actual['width'], actual['height']] != cfg['encoded_size']): + raise ValueError('video storage metadata differs from file') + if key == 'rgb': + fmt, bpp = 'rgb24', 3 + else: + fmt, bpp = 'gray16le', 2 + digest, size, _ = decoded_digest(data_path, fmt) + w, h = cfg['encoded_size'] + if size != n * w * h * bpp: + raise ValueError('raster timeline mismatch') + video_stats[key] = {'decoded_sha256': digest, 'frames': n} + if key == 'depth': + validity = component['valid_storage'] + vp = resolve(component['valid_ref']) + actual_valid = probe(vp) + if (validity['profile'] != 'mkv/bool_ffv1/v1' or actual_valid['codec_name'] != 'ffv1' + or actual_valid['pix_fmt'] != 'gray' or [actual_valid['width'], actual_valid['height']] != [w // 2, h]): + raise ValueError('invalid depth validity video') + count = 0 + for encoded, mask in zip(video_frames(data_path, 'gray16le', (h, w), ' 0)).all() or not np.isnan(depth[~good]).all(): + raise ValueError('invalid depth/validity semantics') + count += 1 + if count != n: + raise ValueError('depth validity timeline mismatch') + if component['schema_id'].startswith('segment/') and component.get('mapping_ref'): + rows = [json.loads(line) for line in resolve(component['mapping_ref']).read_text().splitlines()] + if len(rows) != n or [row['frame_index'] for row in rows] != list(range(n)): + raise ValueError('segmentation mapping timeline mismatch') + for row in rows: + labels = row['labels'] + if len({a['mask_value'] for a in labels}) != len(labels): + raise ValueError('duplicate region mapping') + for label in labels: + if label['entity_id'] is not None and label['entity_id'] not in entities: + raise ValueError('unresolved segmentation entity') + if label['part_id'] is not None and label['part_id'] not in parts.get(label['entity_id'], set()): + raise ValueError('unresolved segmentation part') + if component['schema_id'] == 'segment/uint16_labels/v1': + width, height = meta['camera']['image_size'] + for i, mask in enumerate(video_frames(data_path, 'gray16le', (height, width), ' + raise SystemExit(main()) + ^^^^^^ + File "/home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10/frozen-code/scripts/convert_h2o_v1.0.py", line 316, in main + out = release(args, 'H2O') + ^^^^^^^^^^^^^^^^^^^^ + File "/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10/frozen-code/scripts/warehouse_v1_0.py", line 676, in release + raise ValueError('converter files changed; choose a new --release-id') +ValueError: converter files changed; choose a new --release-id +Command exited with non-zero status 1 + Command being timed: ".venv/bin/python /home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10/frozen-code/scripts/convert_h2o_v1.0.py --root /home/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O --out /home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10 --release-id shared-v1.0 --workers 4 --codec-threads 10 --mano-dir /home/xuzhefeng/Projects/WiLoR/mano_data" + User time (seconds): 1.71 + System time (seconds): 0.20 + Percent of CPU this job got: 99% + Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.93 + Average shared text size (kbytes): 0 + Average unshared data size (kbytes): 0 + Average stack size (kbytes): 0 + Average total size (kbytes): 0 + Maximum resident set size (kbytes): 229832 + Average resident set size (kbytes): 0 + Major (requiring I/O) page faults: 0 + Minor (reclaiming a frame) page faults: 39947 + Voluntary context switches: 42 + Involuntary context switches: 48 + Swaps: 0 + File system inputs: 0 + File system outputs: 8 + Socket messages sent: 0 + Socket messages received: 0 + Signals delivered: 0 + Page size (bytes): 4096 + Exit status: 1 diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/startup-failure/full.status b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/startup-failure/full.status new file mode 100644 index 0000000000000000000000000000000000000000..58188531e6b6b0a46f29659f2317b364902fc1ed --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/startup-failure/full.status @@ -0,0 +1,10 @@ +START=2026-09-30T10:21:04+08:00 +WORKERS=4 CODEC_THREADS=10 SUBJECTS=1,2,3,4 CASA=false +CPU_LIMIT=none +CGROUP=/user.slice/user-25044.slice/user@25044.service/app.slice/h2o-full-w4c10-20260930.scope +CPU_MAX=max controller_disabled +EXIT=1 END=2026-09-30T10:21:06+08:00 +usage_usec 1945180 +user_usec 1723590 +system_usec 221590 +core_sched.force_idle_usec 0 diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/startup-failure/prepare-w4-c10.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/startup-failure/prepare-w4-c10.py new file mode 100644 index 0000000000000000000000000000000000000000..ea7952ec80912d5efd7f6cba4d7dbb88999c3f06 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/startup-failure/prepare-w4-c10.py @@ -0,0 +1,52 @@ +"""Preserve completed r1 sequences without re-encoding or touching source files.""" +import datetime +import json +import os +from pathlib import Path +import shutil + +old = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260929-r1') +new = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10') +snapshot = Path('/tmp/h2o-w4-c10-recovery') +new.mkdir() +shutil.copytree(snapshot / 'scripts', new / 'frozen-code/scripts') +shutil.copytree(snapshot / 'docs', new / 'frozen-code/docs') +shutil.copytree(snapshot / 'tests', new / 'frozen-code/tests') +release = new / 'H2O/shared-v1.0' +for directory in ('data', 'doc', 'script', 'script/provenance/r1'): + (release / directory).mkdir(parents=True, exist_ok=True) +history = release / 'script/provenance/r1' +shutil.copytree(old / 'H2O/shared-v1.0/script', history / 'script') +shutil.copytree(old / 'frozen-code/docs', history / 'docs') +for name in ('full.log', 'full.status', 'run-full.sh'): + shutil.copy2(old / name, history / name) +records = [] +for record in sorted((old / 'H2O/shared-v1.0/doc').glob('*.build.json')): + build = json.loads(record.read_text()) + seq = build['sequence_id'] + assert Path(seq).name == seq and seq not in ('.', '..') + assert set(build['views']) == {f'cam{i}' for i in range(5)}, seq + data = old / 'H2O/shared-v1.0/data' / seq + frames = {} + for cam in build['views']: + meta = json.loads((data / cam / 'metainfo.json').read_text()) + frames[cam] = sum(1 for _ in (data / cam / 'camera/frames.jsonl').open()) + assert frames[cam] > 0 + shutil.copytree(data, release / 'data' / seq, copy_function=os.link) + shutil.copy2(record, release / 'doc' / record.name) + records.append({'sequence_id': seq, 'frames_by_camera': frames, + 'original_script_sha256': build['scripts']}) +manifest = {'time': datetime.datetime.now().astimezone().isoformat(), + 'source_run': str(old), 'destination_run': str(new), + 'reason': 'User requested four archive workers, ten threads per encoder, no CPU quota', + 'reuse': 'Hard-linked immutable completed views; frames and component source SHA256 rechecked during resume', + 'excluded': 'Unpublished .tmp directories; historical 62-sequence output; failed initial full run', + 'original_runtime_provenance': 'script/provenance/r1', 'sequences': records} +(release / 'doc/RESTART_PROVENANCE.json').write_text(json.dumps(manifest, indent=2) + '\n') +for source, target in (('/tmp/h2o-prepare-w4-c10.py', 'prepare-w4-c10.py'), + ('/tmp/h2o-reconfigure-w4-c10.sh', 'reconfigure-w4-c10.sh'), + ('/tmp/h2o-run-w4-c10.sh', 'run-full.sh')): + shutil.copy2(source, release / 'script' / target) +shutil.copy2('/tmp/h2o-run-w4-c10.sh', new / 'run-full.sh') +shutil.copy2('/tmp/h2o-w4-c10-frozen-tests.log', history.parent / 'worker4-codec10-regression.log') +print(f'REUSED_SEQUENCES={len(records)} REUSED_VIEWS={sum(len(r["frames_by_camera"]) for r in records)}', flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/worker4-codec10-final-regression.log b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/worker4-codec10-final-regression.log new file mode 100644 index 0000000000000000000000000000000000000000..1567daf867ed1a6ddda45dc8e52f659325c17b2c --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/worker4-codec10-final-regression.log @@ -0,0 +1,29 @@ +Converted subject1/h1/0 +Converted subject2/h1/0 +Converted subject3/h1/0 +Converted subject4/h1/0 +Converted subject2/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Converted subject3/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Archive subject3_v1_1.tar.gz: 1 sequences +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +PASS H2O four archive workers, codec 1/4/10, RGB FFV1-only, depth and persistent QC diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/worker4-codec10-regression.log b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/worker4-codec10-regression.log new file mode 100644 index 0000000000000000000000000000000000000000..5382e73ffa63d0b26e08739134fe21ab7b25155a --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/provenance/worker4-codec10-regression.log @@ -0,0 +1,29 @@ +Converted subject1/h1/0 +Converted subject2/h1/0 +Converted subject3/h1/0 +Converted subject4/h1/0 +Converted subject2/h1/0 +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Converted subject2/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Archive subject4_v1_1.tar.gz: 1 sequences +Converted subject1/h1/0 +Archive subject1_v1_1.tar.gz: 1 sequences +Converted subject2/h1/0 +Archive subject2_v1_1.tar.gz: 1 sequences +Converted subject3/h1/0 +Archive subject3_v1_1.tar.gz: 1 sequences +Converted subject4/h1/0 +Archive subject4_v1_1.tar.gz: 1 sequences +PASS H2O four archive workers, codec 1/4/10, RGB FFV1-only, depth and persistent QC diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/reconfigure-w4-c10.sh b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/reconfigure-w4-c10.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a6af7e0bec22e511e06d11ee33c8429cdd2a9bd --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/reconfigure-w4-c10.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail +cd /home/xuzhefeng/Projects/uni-hoi-dataset +test "$(cat /tmp/h2o-w4-c10-frozen-tests.exit)" = 0 +test ! -e /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10 +scope=h2o-full-r1-20260929.scope +test "$(systemctl --user show --no-pager "$scope" -p ActiveState --value)" = active +printf '\nRECONFIGURE=%s REASON=user_requested_worker4_codec10 CPU_LIMIT=none\n' "$(date -Is)" >> /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260929-r1/full.status +systemctl --user stop "$scope" +.venv/bin/python /tmp/h2o-prepare-w4-c10.py +systemd-run --user --scope --unit=h2o-full-w4c10-20260930 -p CPUAccounting=yes /bin/bash /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10/run-full.sh diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/render_dexycb_validation.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/render_dexycb_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..e8bb71e9ad9c5a44f85e5c50cee467a00512aa1d --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/render_dexycb_validation.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Audit a finished Dex-YCB release and render persisted modalities for manual review.""" +from collections import Counter +import hashlib +import json +from pathlib import Path +import sys + +from render_hoi4d_validation import render + + +def inspect(root): + data, doc, scripts = root / 'data', root / 'doc', root / 'script' + sequences = sorted(p for p in data.iterdir() if p.is_dir()) + assert len(sequences) == 1000, f'expected 1000 sequences, got {len(sequences)}' + assert len(list(doc.glob('*.build.json'))) == 1000 + assert not list(data.glob('*.tmp-*')), 'unfinished temporary sequences' + config = json.loads((scripts / 'config.json').read_text()) + assert all(config.get(k) is None for k in ('limit', 'max_frames', 'subjects', 'views')) + hashes = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in scripts.glob('*.py')} + subjects, splits, availability = Counter(), Counter(), Counter() + selected = [] + for seq in sequences: + views = sorted(p for p in seq.iterdir() if p.is_dir()) + assert len(views) == 8, (seq, len(views)) + build = json.loads((doc / (seq.name + '.build.json')).read_text()) + assert set(build['views']) == {p.name for p in views}, seq + assert all(hashes.get(k) == v for k, v in build['scripts'].items()), seq + subject = seq.name.split('_')[0] + subjects[subject] += 1 + if subjects[subject] == 1: + selected.append(views[0]) + if subject.endswith('subject-09'): + selected.append(views[-1]) # one more camera, different camera + if seq.name == '20201015-subject-09_20201015_150838': + selected.append(views[0]) # source-labelled left-hand sequence + for view in views: + meta = json.loads((view / 'metainfo.json').read_text()) + assert meta['sequence_id'] == seq.name and meta['camera_id'] == view.name, view + assert meta['dataset_id'] == 'dex-ycb' and meta['release_id'] == 'shared-v1.0', view + assert meta['num_frames'] > 0 and meta.get('view_type') == 'exo', view + assert (view / 'camera/frames.jsonl').is_file(), view + assert meta['components']['rgb']['available'], view + splits[meta['split']] += 1 + for key, part in meta['components'].items(): + if part.get('available'): + availability[key] += 1 + for ref in ('data_ref', 'valid_ref'): + if part.get(ref): + assert (view / part[ref]).is_file(), (view, key, ref) + assert len(subjects) == 10 and set(subjects.values()) == {100}, subjects + assert availability['depth'] == availability['rgb'] == 8000, availability + report = dict(sequences=len(sequences), views=sum(splits.values()), subjects=dict(subjects), + splits=dict(splits), available_views=dict(availability), config=config, + published_script_sha256=hashes, sampled_views=[str(v.relative_to(root)) for v in selected], + scope='Structure and file refs checked for all views; persisted QC and HTML only for sampled views. No manual visual approval yet.') + destination = doc / 'validation' + destination.mkdir(exist_ok=True) + (destination / 'STRUCTURAL_AUDIT.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') + for view in selected: + render(view, destination) + return report + + +if __name__ == '__main__': + print(json.dumps(inspect(Path(sys.argv[1]).expanduser().resolve()), ensure_ascii=False), flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/render_h2o_validation.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/render_h2o_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..b89e7c0827f45ec7f854ff8651234cb9a4223f79 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/render_h2o_validation.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Render stored H2O RGB-D, native camera-space hands/objects, and OBJ assets for review.""" +import argparse +import html +import json +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw +import torch + +from render_hoi4d_validation import mesh_preview, picture, snapshot +from warehouse_v1_0 import unpack_depth, validate_view + + +def load(view, item, n): + if not item.get('available') or not item.get('data_ref', '').endswith('.pt'): + return None, None + values = torch.load(view / item['data_ref'], map_location='cpu', weights_only=True).numpy() + valid = torch.load(view / item['valid_ref'], map_location='cpu', weights_only=True).numpy() if item.get('valid_ref') else None + return (values, valid) if values.ndim and values.shape[0] == n else (None, None) + + +def render(view, destination): + meta = json.loads((view / 'metainfo.json').read_text()) + if meta['dataset_id'] != 'H2O': + raise ValueError('H2O view required') + n = meta['num_frames'] + height, width = reversed(meta['camera']['image_size']) + parts = meta['components'] + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + assert len(frames) == n + selected = {0, n // 4, n // 2, 3 * n // 4, n - 1} + numeric = {} + for name, item in parts.items(): + if item.get('data_ref', '').endswith('.pt') and item.get('available'): + values, valid = load(view, item, n) + if values is not None: + numeric[name] = (values, valid) + if valid is not None: + indices = np.flatnonzero(valid.reshape(n, -1).any(axis=1)) + if len(indices): + selected.add(int(indices[0])) + selected = set(sorted(selected)[:12]) | {n - 1} + rgb = snapshot(view / parts['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected) + depth = snapshot(view / parts['depth']['data_ref'], 'gray16le', (height, 2 * width), ' 0: + u, v = intrinsic[i, 0, 0] * xyz[0] / xyz[2] + intrinsic[i, 0, 2], intrinsic[i, 1, 1] * xyz[1] / xyz[2] + intrinsic[i, 1, 2] + if 0 <= u < width and 0 <= v < height: + draw.ellipse((u-4, v-4, u+4, v+4), fill=color) + legend.append(name + ' ' + color) + panels = ['
    ' + picture(photo) + '
    RGB + 原生 3D 关键点投影(仅预览:' + html.escape(', '.join(legend) or '当前帧无可投影点') + ')
    '] + if i in depth: + z = unpack_depth(depth[i]) + luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(luminance)) + '
    深度 Z,黑=无效,白≥3 m;不改源深度
    ') + details = {'frame': frames[i]} + for name, (values, valid) in numeric.items(): + details[name] = {'value': values[i].tolist(), 'valid': None if valid is None else valid[i].tolist()} + pages.append('

    帧 ' + str(i) + ' / ' + str(n) + '

    ' + ''.join(panels) + '
    原帧号、全部数值标注及有效性
    ' + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '
    ') + assets = [] + for name, item in parts.items(): + if item.get('available') and item.get('data_ref', '').lower().endswith('.obj'): + assets.append('

    ' + html.escape(name) + '

    ' + mesh_preview(view / item['data_ref']) + '
    源 OBJ 静态预览,不代表物体姿态投影
    ') + report = validate_view(view) + destination.mkdir(parents=True, exist_ok=True) + title = view.parent.name + '_' + view.name + style = 'body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;background:#f5f7fa;color:#18232f}section,details{background:white;padding:1rem;margin:1rem 0;border-radius:8px}.panels{display:flex;flex-wrap:wrap}img{max-width:100%}pre{white-space:pre-wrap;overflow:auto;font-size:12px}' + page = '' + html.escape(title) + '

    ' + html.escape(title) + '

    预览只作人工核查;仅显示真实存在的标注,不合成分割。

    ' + ''.join(pages) + '

    源网格

    ' + ''.join(assets) + '
    全部组件元数据
    ' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '
    持久化 QC
    ' + html.escape(json.dumps(report, ensure_ascii=False, indent=2)) + '
    ' + (destination / (title + '.html')).write_text(page) + (destination / (title + '.report.json')).write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') + links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html') + (destination / 'index.html').write_text('

    H2O 试点预览

    ') + return destination / (title + '.html') + + +if __name__ == '__main__': + p = argparse.ArgumentParser() + p.add_argument('views', nargs='+', type=Path) + p.add_argument('--out', type=Path, required=True) + args = p.parse_args() + for view in args.views: + print(render(view, args.out), flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/render_hoi4d_source_review.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/render_hoi4d_source_review.py new file mode 100644 index 0000000000000000000000000000000000000000..79d7a58744572343670e9cbaecc4cc54ea07f1c1 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/render_hoi4d_source_review.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Evidence-only HTML: native HOI4D pose boxes over persisted RGB and native masks.""" +import argparse +import html +import json +from pathlib import Path +import shutil +import zipfile + +import numpy as np +from PIL import Image, ImageDraw + +from render_hoi4d_validation import picture, snapshot + + +def source_parts(view): + rows = [] + for source in view.glob('annotation/object/*/assets/result.json'): + def visit(node): + if isinstance(node, list): + for child in node: + visit(child) + return + if node.get('objs'): + rows.append({'source_part_id': node['id'], 'source_part_name': node['name'], + 'source_meshes': node['objs'], 'source_locator': str(source.relative_to(view))}) + for child in node.get('children', []): + visit(child) + visit(json.loads(source.read_text())) + return rows + + +def render(view, z, output): + output.mkdir(parents=True, exist_ok=True) + meta = json.loads((view / 'metainfo.json').read_text()) + seq = meta['sampling']['selection']['source_sequence'] + w, h = meta['camera']['image_size'] + chosen = sorted({0, meta['num_frames'] // 2, meta['num_frames'] - 1}) + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + rgb = snapshot(view / meta['components']['rgb']['data_ref'], 'rgb24', (h, w, 3), np.uint8, chosen) + segment = meta['components'].get('segment', {}) + masks = (snapshot(view / segment['data_ref'], 'gray16le', (h, w), '

    ' + html.escape(seq) + f' / frame {native_id}

    ' + picture(image) + + '

    仅验收:伪彩=原生分割码,黄框=上游 2dBox;颜色和框不写回 shared,空间重叠不能代替身份依据。

    ' + + '
    上游原记录与编码对照
    '
    +                      + html.escape(json.dumps(note, ensure_ascii=False, indent=2)) + '
    ') + parts = source_parts(view) + name = view.parent.name + '_' + view.name + '.html' + page = 'HOI4D source correspondence review

    源姿态/原生分割/RGB 的证据图(非真值修改)

    ' + page += ''.join(panels) + '
    CAD result.json 原生部件→OBJ;不等同逐帧姿态对应
    '
    +    page += html.escape(json.dumps(parts, ensure_ascii=False, indent=2)) + '
    ' + (output / name).write_text(page) + print(name, 'native_part_links',len(parts),flush=True) + return name + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--raw-root', type=Path, required=True) + p.add_argument('--release', type=Path, required=True) + p.add_argument('--out', type=Path, required=True) + args = p.parse_args(argv) + args.out.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(args.raw_root / 'HOI4D_annotations.zip') as z: + names = [] + for view in sorted((args.release / 'data').glob('*/ego')): + if any('/C' + category + '/' in json.loads((view / 'metainfo.json').read_text())['sampling']['selection']['source_sequence'] + for category in ('2', '3', '14', '17')): + names.append(render(view, z, args.out)) + links = ''.join(f'
  • {html.escape(name)}
  • ' for name in names) + (args.out / 'index.html').write_text('

    源依据对照(非物体几何验收通过)

      ' + links + '
    ') + shutil.copyfile(Path(__file__), args.out / 'renderer.py') + + +if __name__ == '__main__': + main() diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/render_hoi4d_validation.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/render_hoi4d_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..a7889a1b63b004e046b52fe4e4da0b2b4651b768 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/render_hoi4d_validation.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Standalone, offline HTML review of every persisted component in selected views.""" +import argparse +import base64 +import html +import io +import json +import random +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw +import torch + +from warehouse_v1_0 import video_frames, unpack_depth, validate_view + + +def snapshot(video, fmt, shape, dtype, indices): + return {i: frame.copy() for i, frame in enumerate(video_frames(video, fmt, shape, dtype)) if i in indices} + + +def picture(image): + image.thumbnail((800, 450)) # Previews only; released tensors and videos are not resized. + output = io.BytesIO() + image.save(output, format='PNG') + return '' + + +def preview_color(value, dataset_id): + # Dex-YCB reserves 255 for the native hand mask. The old mod-240 palette + # gave it the same color as YCB object 15; keep data codes untouched. + if dataset_id == 'dex-ycb' and value == 255: + return (255, 32, 64) + return tuple((value * factor) % 240 + 15 for factor in (89, 61, 131)) + + +def mesh_preview(path): + """Project the whole source asset; bound drawing cost without favoring early faces.""" + vertices, faces, referenced = [], [], set() + rng = random.Random(0) + face_count = 0 + with path.open(errors='replace') as stream: + for line in stream: + if line.startswith('v '): + vertices.append([float(v) for v in line.split()[1:4]]) + elif line.startswith('f '): + face = [] + for token in line.split()[1:]: + index = int(token.split('/')[0]) + face.append(index - 1 if index > 0 else len(vertices) + index) + if len(face) < 3: + continue + referenced.update(face) + face_count += 1 + # ponytail: bounded static preview; use a full OBJ viewer if 5000 faces miss fine detail. + if len(faces) < 5000: + faces.append(face) + else: + pick = rng.randrange(face_count) + if pick < len(faces): + faces[pick] = face + if not vertices or not faces: + return 'OBJ 未提供可绘制的顶点/面' + if min(referenced) < 0 or max(referenced) >= len(vertices): + raise ValueError(f'invalid OBJ face index: {path}') + xyz = np.asarray(vertices, dtype=np.float64) + if not np.isfinite(xyz).all(): + raise ValueError(f'nonfinite OBJ vertex: {path}') + # Fixed orthonormal isometric basis: geometry only, not an inferred camera pose. + projected = np.column_stack(((xyz[:, 0] - xyz[:, 2]) / np.sqrt(2), + (xyz[:, 0] + xyz[:, 2] - 2 * xyz[:, 1]) / np.sqrt(6))) + used = projected[np.fromiter(referenced, dtype=np.int64)] + lo, hi = used.min(axis=0), used.max(axis=0) + extent = (hi - lo).max() + if extent <= 0: + return 'OBJ 所有面投影到同一点' + projected = (projected - (lo + hi) / 2) * (380 / extent) + 215 + image = Image.new('RGB', (430, 430), 'white') + draw = ImageDraw.Draw(image) + for face in faces: + polygon = [tuple(projected[i]) for i in face] + draw.line(polygon + [polygon[0]], fill='#205caa', width=1) + return picture(image) + + +def render(view, destination): + meta = json.loads((view / 'metainfo.json').read_text()) + n = meta['num_frames'] + width, height = meta['camera']['image_size'] + components = meta['components'] + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + assert len(frames) == n + selected = {0, n // 4, n // 2, 3 * n // 4, n - 1} + for item in components.values(): + ref = item.get('valid_ref', '') + if ref.endswith('.pt'): + valid = torch.load(view / ref, map_location='cpu', weights_only=True).numpy() + if valid.shape[0] == n: + matching = np.flatnonzero(valid.reshape(n, -1).any(axis=1)) + if len(matching): + selected.add(int(matching[0])) + selected = set(sorted(selected)[:12]) | {n - 1} + rgb = snapshot(view / components['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected) + depth = (snapshot(view / components['depth']['data_ref'], 'gray16le', (height, 2 * width), '' + picture(image) + '
    RGB + 原生 2D 手关键点(若有)
    '] + if i in depth: + z = unpack_depth(depth[i]) + luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(luminance)) + '
    深度 Z(黑=无效,白≥3 m;仅预览)
    ') + if i in masks: + mask = masks[i] + colors = np.zeros((*mask.shape, 3), dtype=np.uint8) + for value in np.unique(mask): + if value not in (0, 65535): + colors[mask == value] = preview_color(int(value), meta['dataset_id']) + legend = ';'.join(f'{int(value)}=' + ('手' if value == 255 and meta['dataset_id'] == 'dex-ycb' else '物体' if meta['dataset_id'] == 'dex-ycb' else '区域') + f' #{bytes(preview_color(int(value), meta["dataset_id"])).hex()}' for value in np.unique(mask) if value not in (0, 65535)) + panels.append('
    ' + picture(Image.fromarray(colors)) + '
    原生分割整数编码的伪彩色预览(' + html.escape(legend) + ')
    ') + active = (mask != 0) & (mask != 65535) + overlay = rgb[i].copy() + overlay[active] = ((overlay[active].astype(np.uint16) + colors[active]) // 2).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(overlay)) + '
    原生分割叠加 RGB(仅预览)
    ') + details = {'frame': frames[i], 'segment_labels': labels.get(i, [])} + for name, component in components.items(): + ref = component.get('data_ref', '') + if component.get('available') and ref.endswith('.pt'): + values = torch.load(view / ref, map_location='cpu', weights_only=True) + if values.ndim and values.shape[0] == n: + details[name] = {'value': values[i].tolist()} + if component.get('valid_ref', '').endswith('.pt'): + valid = torch.load(view / component['valid_ref'], map_location='cpu', weights_only=True) + details[name]['valid'] = valid[i].tolist() + sections.append('

    帧 ' + str(i) + ' / ' + str(n) + '

    ' + ''.join(panels) + + '
    帧号、来源、全部数值组件与有效性
    '
    +                        + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '
    ') + assets = [] + for name, component in components.items(): + if component.get('available') and component['data_ref'].lower().endswith('.obj'): + ref = component['data_ref'] + assets.append('

    ' + html.escape(name) + '

    ' + mesh_preview(view / ref) + + '
    仅展示网格原生形状;未验证尺度/位姿对应。
    ') + result = validate_view(view) + destination.mkdir(parents=True, exist_ok=True) + title = view.parent.name + '_' + view.name + css = 'body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;background:#f5f7fa;color:#18232f}section,details{background:#fff;padding:1rem;margin:1rem 0;border-radius:8px}figure{margin:.5rem}figcaption{font-size:.85rem}.panels{display:flex;flex-wrap:wrap}img{max-width:100%;border:1px solid #ddd}pre{white-space:pre-wrap;overflow:auto;font-size:12px}' + page = '' + html.escape(title) + '

    ' + html.escape(title) + '

    预览图仅供人工审核,不是训练输入;未提供的模态在 metainfo 中保留原因。

    ' + ''.join(sections) + '

    原始物体模型(独立预览)

    ' + ''.join(assets) + '
    全部组件元信息及原始来源
    ' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '
    持久化 QC 结果
    ' + html.escape(json.dumps(result, ensure_ascii=False, indent=2)) + '
    ' + (destination / (title + '.html')).write_text(page) + (destination / (title + '.report.json')).write_text(json.dumps(result, ensure_ascii=False, indent=2)) + links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html') + (destination / 'index.html').write_text('' + html.escape(meta['dataset_id']) + ' review

    ' + html.escape(meta['dataset_id']) + ' 抽样人工审核

    选择视图;所有预览均来自已保存的 shared 数据。

    ') + print(destination / (title + '.html'), 'selected_frames', sorted(selected), flush=True) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('views', nargs='+', type=Path) + p.add_argument('--out', type=Path) + args = p.parse_args() + for view in args.views: + render(view, args.out or view.parents[2] / 'doc/validation') + + +if __name__ == '__main__': + main() diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/run-full.sh b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/run-full.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b9267d75a5fb7c4d1729397219e7f8ca2a688c4 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/run-full.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -u +base="$HOME/Datasets/uni-hoi-h2o-full-20260930-w4-c10" +raw="$HOME/Datasets/Hand-Datasets-Raw/H2O" +cd "$HOME/Projects/uni-hoi-dataset" || exit 1 +mkdir -p "$base/scratch" +export TMPDIR="$base/scratch" PYTHONUNBUFFERED=1 +for n in 1 2 3 4; do test -s "$raw/raw/data/subject${n}_v1_1.tar.gz" || exit 2; done +test ! -e "$base/full.status" || exit 3 +cg=$(awk -F: '$1=="0" {print $3}' /proc/self/cgroup) +if [[ -f "/sys/fs/cgroup$cg/cpu.max" ]]; then + read -r quota period < "/sys/fs/cgroup$cg/cpu.max" +else + quota=max + period=controller_disabled +fi +printf 'START=%s\nWORKERS=4 CODEC_THREADS=10 SUBJECTS=1,2,3,4 CASA=false\nCPU_LIMIT=none\nCGROUP=%s\nCPU_MAX=%s %s\n' "$(date -Is)" "$cg" "$quota" "$period" > "$base/full.status" +if [[ "$quota" != max ]]; then + printf 'EXIT=4 ERROR=UNEXPECTED_CPU_QUOTA\n' >> "$base/full.status" + exit 4 +fi +/usr/bin/time -v .venv/bin/python "$base/frozen-code/scripts/convert_h2o_v1.0.py" --root "$raw" --out "$base" --release-id shared-v1.0 --workers 4 --codec-threads 10 --mano-dir "$HOME/Projects/WiLoR/mano_data" > "$base/full.log" 2>&1 +code=$? +printf 'EXIT=%s END=%s\n' "$code" "$(date -Is)" >> "$base/full.status" +if [[ -f "/sys/fs/cgroup$cg/cpu.stat" ]]; then cat "/sys/fs/cgroup$cg/cpu.stat" >> "$base/full.status"; fi +exit "$code" diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/warehouse_v1_0.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/warehouse_v1_0.py new file mode 100644 index 0000000000000000000000000000000000000000..f705011bcea587bd320e1e228f99bed259b32b3a --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/provenance/previous-run/script/warehouse_v1_0.py @@ -0,0 +1,931 @@ +"""Shared I/O for CONTRACT.md v1.0. No annotation synthesis.""" +import argparse +from contextlib import contextmanager +from functools import lru_cache +import hashlib +import json +import math +import shlex +from pathlib import Path +import pickle +import random +import shutil +import subprocess +import tempfile +import time + +import numpy as np +from PIL import Image +import torch + +SCHEMA_PATH = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/schema.json', + Path(__file__).resolve().parents[1] / 'doc/schema.json') if p.is_file()) +SCHEMA = json.loads(SCHEMA_PATH.read_text()) +RAW_ROOT = Path.home() / 'Datasets/Hand-Datasets-Raw' + + +def json_write(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + '\n') + + +def jsonl_write(path, rows): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('w') as out: + for row in rows: + out.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + '\n') + + +def sha256(path): + with Path(path).open('rb') as f: + return hashlib.file_digest(f, 'sha256').hexdigest() + + +def locator(path, member=None, data=None, **extra): + result = {'file': str(Path(path).resolve())} + if member is not None: + result['member'] = member + if data is not None: + result['sha256'] = hashlib.sha256(data).hexdigest() + return result | extra + + +def source(method='Copy source annotation; normalize storage only'): + return {'kind': 'format_conversion', 'method': method} + + +def run(args, **kwargs): + return subprocess.run(args, check=True, stderr=subprocess.PIPE, **kwargs) + + +@lru_cache(maxsize=1) +def ffversion(): + return run(['ffmpeg', '-version'], stdout=subprocess.PIPE).stdout.decode().splitlines()[0] + + +def probe(path): + return json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', + '-show_streams', '-of', 'json', str(path)], + stdout=subprocess.PIPE).stdout)['streams'][0] + + +def decode_args(path, pixel_format): + return ['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', '1', '-threads', '1', '-noautorotate', + '-i', str(path), '-map', '0:v:0', '-vsync', '0', '-threads', '1', + '-f', 'rawvideo', '-pix_fmt', pixel_format] + + +def decoded_digest(path, pixel_format): + start = time.monotonic() + with tempfile.TemporaryFile() as err: + proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'], + stdout=subprocess.PIPE, stderr=err) + digest, size = hashlib.sha256(), 0 + with proc.stdout: + while chunk := proc.stdout.read(1024 * 1024): + digest.update(chunk) + size += len(chunk) + if proc.wait(): + err.seek(0) + raise RuntimeError(err.read().decode(errors='replace')) + return digest.hexdigest(), size, time.monotonic() - start + + +def video_frames(path, pixel_format, shape, dtype): + frame_bytes = int(np.prod(shape)) * np.dtype(dtype).itemsize + with tempfile.TemporaryFile() as err: + proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'], stdout=subprocess.PIPE, stderr=err) + completed = False + try: + while True: + data = proc.stdout.read(frame_bytes) + if not data: + break + if len(data) != frame_bytes: + raise ValueError('truncated decoded video frame') + yield np.frombuffer(data, dtype=dtype).reshape(shape) + if proc.wait(): + err.seek(0) + raise ValueError(err.read().decode(errors='replace')) + completed = True + finally: + proc.stdout.close() + if not completed and proc.poll() is None: + proc.terminate() + proc.wait() + + +def storage(path, profile, parameters, source_lossy): + info = probe(path) + if info['codec_name'] == 'h264': + frames = json.loads(run(['ffprobe', '-v', 'error', '-threads', '1', '-select_streams', 'v:0', + '-show_entries', 'frame=key_frame', '-of', 'json', str(path)], stdout=subprocess.PIPE).stdout)['frames'] + parameters = parameters | {'keyframe_indices': [i for i, f in enumerate(frames) if f['key_frame']]} + return {'profile': profile, 'codec': info['codec_name'], + 'pixel_format': info['pix_fmt'], 'encoded_size': [info['width'], info['height']], + 'decoder': {'name': 'ffmpeg', 'version': ffversion(), 'autorotate': False, + 'color_space': info.get('color_space', 'unknown'), + 'color_range': info.get('color_range', 'unknown'), + 'color_primaries': info.get('color_primaries', 'unknown'), + 'color_transfer': info.get('color_transfer', 'unknown')}, + 'encoder_parameters': {'version': ffversion()} | parameters, + 'source_lossy': source_lossy, 'storage_fps': 30, 'timebase_role': 'index_only'} + + +def encode_raw(raw, target, width, height, pixel_format, profile, codec='ffv1', extra=(), threads=1): + start = time.monotonic() + run(['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', '1', '-y', '-f', 'rawvideo', + '-pixel_format', pixel_format, '-video_size', f'{width}x{height}', '-framerate', '30', + '-i', str(raw), '-an', '-c:v', codec, '-threads', str(threads), *extra, str(target)]) + digest, size, decode_seconds = decoded_digest(target, pixel_format) + if size != Path(raw).stat().st_size or digest != sha256(raw): + raise ValueError(f'lossless roundtrip failed: {target}') + config = storage(target, profile, {'name': codec, 'arguments': list(extra), 'threads': threads}, False) + return config, {'bytes': target.stat().st_size, 'encode_seconds': time.monotonic() - start - decode_seconds, + 'decode_seconds': decode_seconds, 'decoded_sha256': digest, 'all_frames_exact': True} + + +def measure_rgb_access(video, raw, width, height, count): + index = count // 2 + start = time.monotonic() + data = run(['ffmpeg', '-v', 'error', '-nostdin', '-filter_threads', '1', '-threads', '1', '-noautorotate', + '-i', str(video), '-vf', f'select=eq(n\\,{index})', '-frames:v', '1', '-threads', '1', + '-f', 'rawvideo', '-pix_fmt', 'rgb24', 'pipe:1'], stdout=subprocess.PIPE).stdout + with raw.open('rb') as inp: + inp.seek(index * width * height * 3) + if data != inp.read(width * height * 3): + raise ValueError('exact indexed RGB read failed') + return {'random_access_strategy': 'decode from first keyframe; select exact presentation index', + 'random_frame_index': index, 'random_frame_read_seconds': time.monotonic() - start} + + +def jpeg_sample_indices(sequence, camera, count): + seed = int.from_bytes(hashlib.sha256(f'{sequence}/{camera}/20260920'.encode()).digest()[:8], 'big') + indices = {0, count - 1, count // 4, count // 2, 3 * count // 4} + indices.update(random.Random(seed).sample([i for i in range(count) if i not in indices], + min(count, 16) - len(indices))) + return sorted(indices), seed + + +def check_jpeg_copy(target, paths, hashes, size, sequence, camera, full): + packets = json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', + '-show_packets', '-show_data_hash', 'sha256', '-of', 'json', str(target)], + stdout=subprocess.PIPE).stdout)['packets'] + if [p['data_hash'].split(':', 1)[1].lower() for p in packets] != hashes: + raise ValueError('JPEG packet hashes/order/count differ') + info = probe(target) + if [info['width'], info['height']] != list(size): + raise ValueError('JPEG container dimensions differ') + indices, seed = jpeg_sample_indices(sequence, camera, len(paths)) + if full: + indices = list(range(len(paths))) + select = '+'.join(f'eq(n\\,{i})' for i in indices) + frame_bytes = size[0] * size[1] * 3 + # Spool selected frames to disk, keeping RAM bounded for full-view audits. + with tempfile.TemporaryFile() as decoded: + run(decode_args(target, 'rgb24') + ([] if full else ['-vf', 'select=' + select]) + ['pipe:1'], stdout=decoded) + decoded.seek(0) + for i in indices: + expected = run(decode_args(paths[i], 'rgb24') + ['pipe:1'], stdout=subprocess.PIPE).stdout + if len(expected) != frame_bytes or decoded.read(frame_bytes) != expected: + raise ValueError(f'JPEG decoded pixels differ at frame {i}') + if decoded.read(1): + raise ValueError('JPEG selected pixel count differs') + return {'policy': 'jpeg-packets-all-rgb-sample16/v1', 'seed': seed, + 'selected_frame_indices': indices, 'pixel_frames_checked': len(indices), + 'packet_frames_checked': len(paths), 'jpeg_packets_exact': True, + 'packet_count_order_dimensions_exact': True, 'sampled_pixels_exact': True, + 'all_frames_exact': len(indices) == len(paths), 'full_view_audit': full} + + +def rgb_video(paths, target, work, video=None, count=None, sequence="", camera="", full_jpeg=False, + ffv1_first=False, codec_threads=1): + """JPEG packet proof plus deterministic pixels; re-encodings compare all pixels.""" + target.parent.mkdir(parents=True, exist_ok=True) + raw = work / 'rgb.raw' + packets = [] + has_missing = video is None and any(p is None for p in paths) + if has_missing: + present = next((p for p in paths if p is not None), None) + if present is None: + raise ValueError('no source RGB image to establish the pixel format/grid') + original = probe(present) + width, height = original['width'], original['height'] + with raw.open('wb') as dest: + for path in paths: + if path is None: + dest.write(bytes(width * height * 3)) + else: + with Image.open(path) as im: + if im.mode != 'RGB' or im.size != (width, height): + raise ValueError('source RGB grid/type changes within view') + run(decode_args(path, 'rgb24') + ['pipe:1'], stdout=dest) + lossy, count = 'unknown', len(paths) + input_args = None + elif video is None: + if not paths: + raise ValueError('RGB timeline must contain existing source images') + suffix = paths[0].suffix.lower() + if suffix not in ('.jpg', '.jpeg', '.png'): + raise ValueError('unsupported source RGB format') + images = work / 'rgb_source' + images.mkdir() + dimensions = None + for i, path in enumerate(paths): + with Image.open(path) as im: + if im.mode != 'RGB' or (dimensions is not None and dimensions != im.size): + raise ValueError('RGB must be homogeneous 8-bit RGB, with no silent color/size conversion') + dimensions = im.size + if im.format == 'PNG' and path.read_bytes()[24] != 8: + raise ValueError('high bit depth RGB needs a registered schema') + dest = images / f'{i:08d}{suffix}' + shutil.copyfile(path, dest) + packets.append(sha256(path)) + width, height = dimensions + input_args = ['-framerate', '30', '-i', str(images / ('%08d' + suffix))] + count = len(paths) + original = probe(paths[0]) + lossy = suffix in ('.jpg', '.jpeg') + else: + original = probe(video) + if int(original.get('bits_per_raw_sample') or 8) > 8 or any( + x in original.get('pix_fmt', '') for x in ('10', '12', '16', 'f32')): + raise ValueError('high bit depth RGB needs a registered schema') + width, height = original['width'], original['height'] + input_args = ['-i', str(video)] + lossy = 'unknown' + limits = ['-frames:v', str(count)] if count else [] + records = [] + if video is None and not has_missing and suffix in ('.jpg', '.jpeg'): + start = time.monotonic() + try: + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0', + *limits, '-c:v', 'copy', '-an', str(target)]) + encode_seconds = time.monotonic() - start + validation = check_jpeg_copy(target, paths, packets, (width, height), sequence, camera, full_jpeg) + cfg = storage(target, 'mkv/mjpeg_copy/v1', {'stream_copy': True}, lossy) + cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in + ('color_space', 'color_range', 'color_primaries', 'color_transfer')} + records.append(validation | {'profile': cfg['profile'], 'bytes': target.stat().st_size, + 'encode_seconds': encode_seconds, 'validation_seconds': time.monotonic() - start - encode_seconds}) + return cfg, [width, height], records, count + except (subprocess.CalledProcessError, ValueError) as exc: + records.append({'profile': 'mkv/mjpeg_copy/v1', 'rejected': str(exc)}) + target.unlink(missing_ok=True) + if not has_missing: + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', '-threads', '1', '-noautorotate', + *input_args, '-map', '0:v:0', *limits, '-vsync', '0', '-threads', '1', + '-f', 'rawvideo', '-pix_fmt', 'rgb24', str(raw)]) + frame_bytes = width * height * 3 + actual, remainder = divmod(raw.stat().st_size, frame_bytes) + if remainder or not actual or (count is not None and actual != count): + raise ValueError('source RGB frame count mismatch') + expected_hash = sha256(raw) + can_copy = video is not None + if can_copy: + start = time.monotonic() + try: + run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0', + *limits, '-c:v', 'copy', '-an', str(target)]) + digest, size, seconds = decoded_digest(target, 'rgb24') + if digest != expected_hash or size != raw.stat().st_size: + raise ValueError('stream-copy RGB bytes/order/count mismatch') + cfg = storage(target, 'mkv/source_copy/v1', + {'stream_copy': True}, lossy) + if video: + cfg['storage_fps'] = original.get('avg_frame_rate') + cfg['preserve_source_pts'] = True + records.append({'profile': cfg['profile'], 'all_frames_exact': True, + 'decoded_sha256': digest, + 'bytes': target.stat().st_size, 'decode_seconds': seconds, + 'encode_seconds': time.monotonic() - start - seconds}) + records[-1].update(measure_rgb_access(target, raw, width, height, actual)) + return cfg, [width, height], records, actual + except (subprocess.CalledProcessError, ValueError) as exc: + records.append({'profile': 'stream_copy', 'rejected': str(exc)}) + target.unlink(missing_ok=True) + candidates = [] + for profile, codec, params in [ + ('mkv/ffv1_rgb/v1', 'ffv1', ['-level', '3', '-pix_fmt', 'bgr0']), + ('mkv/h264_rgb_lossless/v1', 'libx264rgb', ['-crf', '0', '-preset', 'medium', '-g', '30'])]: + path = work / (codec + '.mkv') + try: + cfg, record = encode_raw(raw, path, width, height, 'rgb24', profile, codec, params, + codec_threads if codec == 'ffv1' else 1) + cfg['source_lossy'] = lossy + cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in + ('color_space', 'color_range', 'color_primaries', 'color_transfer')} + record['profile'] = profile + record.update(measure_rgb_access(path, raw, width, height, actual)) + records.append(record) + candidates.append((path.stat().st_size, path, cfg)) + if ffv1_first and codec == 'ffv1': + break # Keep the H.264 fallback only if the preferred exact encoder fails. + except subprocess.CalledProcessError as exc: + records.append({'profile': profile, 'rejected': exc.stderr.decode(errors='replace')}) + if not candidates: + raise ValueError('no supported lossless RGB encoder') + _, chosen, cfg = min(candidates, key=lambda x: x[0]) + shutil.move(chosen, target) + return cfg, [width, height], records, actual + + +def pack_depth(depth): + bits = np.ascontiguousarray(depth, dtype='> 16).astype(' 0) + arr[~good] = np.nan + out.write(pack_depth(arr).tobytes()) + vo.write(good.astype(np.uint8).tobytes()) + else: + if not np.issubdtype(arr.dtype, np.integer) or arr.min() < 0 or arr.max() > 65535: + raise ValueError('invalid segmentation region codes') + out.write(arr.astype(' vertices: + raise ValueError('empty or invalid mesh') + def dependency(parent, name): + dep = (parent / name).resolve() + if not dep.is_relative_to(asset_root) or not dep.is_file(): + raise ValueError(f'missing or escaping asset dependency: {name}') + return dep + dependencies = [] + for name in materials: + mtl = dependency(path.parent, name) + dependencies.append(mtl) + for line in mtl.read_text().splitlines(): + fields = shlex.split(line, comments=True) + if fields and (fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal')): + dependencies.append(dependency(mtl.parent, fields[-1])) + return {'vertices': vertices, 'faces': faces, 'sha256': sha256(path), + 'dependencies': {p.relative_to(asset_root).as_posix(): sha256(p) for p in dependencies}} + + +def mesh_asset(view, oid, directory, obj, loc): + dest = view.path / f'annotation/object/{oid}/assets' + shutil.copytree(directory, dest) + ref = (dest / Path(obj).relative_to(directory)).relative_to(view.path).as_posix() + mesh_check = check_mesh(dest / Path(obj).relative_to(directory), dest) + view.build['validation'].append({'component': f'mesh_{oid}', **mesh_check}) + view.component(f'mesh_{oid}', 'mesh/obj/v1', ref, ['vertex'], loc, valid=True, unit='m') + p = view.path / f'annotation/object/{oid}/metainfo.json' + info = json.loads(p.read_text()) + info.update(has_model=True, mesh_ref=ref) + json_write(p, info) + + +def safe_member(root, name): + path = (Path(root) / name).resolve() + if not path.is_relative_to(Path(root).resolve()): + raise ValueError(f'unsafe archive path: {name}') + return path + + +class ChumpyStub: + def __setstate__(self, state): + self.__dict__.update(state) + + +class ManoUnpickler(pickle.Unpickler): + def find_class(self, module, name): + if module.startswith('chumpy'): + return ChumpyStub + return super().find_class(module, name) + + +def mano_models(directory): + result = {} + if directory is None: + return result + for side in ('left', 'right'): + path = Path(directory).expanduser() / f'MANO_{side.upper()}.pkl' + if not path.exists(): + continue + with path.open('rb') as f: + data = ManoUnpickler(f, encoding='latin1').load() + result[side] = {'components': np.asarray(data['hands_components']), + 'mean': np.asarray(data['hands_mean']), 'sha256': sha256(path), + 'file': path.name} + return result + + +def model_profile(models): + identity = json.dumps({side: d['sha256'] for side, d in sorted(models.items())}).encode() + return {'version': 'sha256:' + hashlib.sha256(identity).hexdigest(), 'flat_hand_mean': True, + 'left_shapedirs_correction': 'not_applied', + 'models': {side: {'file': d['file'], 'sha256': d['sha256']} for side, d in models.items()}} + + +def pca_to_axis_angle(coeffs, model): + coeffs = np.asarray(coeffs) + if coeffs.shape[-1:] != (45,) or not np.isfinite(coeffs).all(): + raise ValueError('invalid MANO PCA coefficients') + return coeffs @ model['components'] + model['mean'] + + +def parser(dataset, description): + p = argparse.ArgumentParser(description=description) + p.add_argument('--root', f'--{dataset.lower()}-root', dest='root', type=Path, default=RAW_ROOT / dataset) + p.add_argument('--out', type=Path, default=Path('converted')) + p.add_argument('--release-id', default='v1.0') + p.add_argument('--limit', type=int, help='Maximum sequences to convert') + p.add_argument('--max-frames', type=int, help='First N source frame indices per view (recorded as sampling)') + p.add_argument('--mano-dir', type=Path) + p.add_argument('--views', help='Comma-separated source camera IDs') + p.add_argument('--jpeg-full-check', action='store_true', help='Full decoded RGB check for selected JPEG pilot/final views') + return p + + +def roots(root): + root = Path(root).expanduser() + return [p for p in (root / 'raw/data', root / 'raw', root) if p.is_dir()] + + +def find_file(root, name): + return next((p / name for p in roots(root) if (p / name).exists()), None) + + +def release(args, dataset): + if not args.release_id or Path(args.release_id).name != args.release_id or args.release_id in ('.', '..'): + raise ValueError('release-id must be a single directory name') + if args.limit is not None and args.limit < 1 or args.max_frames is not None and args.max_frames < 1: + raise ValueError('limits must be positive') + out = args.out.expanduser().resolve() / dataset / args.release_id + raw = args.root.expanduser().resolve() + if out == raw or out.is_relative_to(raw): + raise ValueError('output must not modify the raw source tree') + (out / 'data').mkdir(parents=True, exist_ok=True) + (out / 'doc').mkdir(exist_ok=True) + (out / 'script').mkdir(exist_ok=True) + scripts = list(Path(__file__).resolve().parent.glob('*.py')) + existing = {p.name for p in (out / 'script').glob('*.py')} + if existing and existing != {p.name for p in scripts}: + raise ValueError('converter files changed; choose a new --release-id') + copies = [(SCHEMA_PATH.parent / name, out / 'doc' / name) for name in ('CONTRACT.md', 'schema.json')] + copies += [(path, out / 'script' / path.name) for path in scripts] + # Check every existing file before changing any published definition or script. + for src, dest in copies: + if dest.exists() and sha256(dest) != sha256(src): + raise ValueError('converter or contract changed within an existing release; choose a new --release-id') + for src, dest in copies: + if src.resolve() != dest.resolve(): + shutil.copyfile(src, dest) + json_write(out / 'script/config.json', {k: str(v) if isinstance(v, Path) else v for k, v in vars(args).items()}) + return out + + +@contextmanager +def sequence_dir(out, sequence): + if Path(sequence).name != sequence: + raise ValueError('sequence ID must be a single path component') + final = out / 'data' / sequence + with tempfile.TemporaryDirectory(prefix=sequence + '.tmp-', dir=out / 'data') as wd: + tmp = Path(wd) + yield tmp + if final.exists(): + if any((final / child.name).exists() for child in tmp.iterdir()): + raise FileExistsError('view already published; use a new release-id to preserve it') + for child in list(tmp.iterdir()): + child.rename(final / child.name) + else: + tmp.rename(final) + + +def build_record(out, sequence, reports): + path = out / 'doc' / (sequence + '.build.json') + previous = json.loads(path.read_text()) if path.exists() else {} + config = json.loads((out / 'script/config.json').read_text()) + for report in reports.values(): + report['configuration'] = config + json_write(path, {'sequence_id': sequence, 'storage_revision': SCHEMA['storage_revision'], + 'scripts': {p.name: sha256(p) for p in (out / 'script').glob('*.py')}, + 'runtime': {'torch': torch.__version__, 'ffmpeg': ffversion()}, + 'views': previous.get('views', {}) | reports}) + + +def check_view_type(meta): + # The pinned ARCTIC contract makes view_type optional; adapters still supply known views. + if 'view_type' not in meta: + return + if meta['view_type'] not in ('ego', 'exo', 'unknown'): + raise ValueError('view_type must be ego/exo/unknown') + expected = {'dex-ycb': 'exo', 'EPIC-KITCHENS-VISOR': 'ego', 'HOI4D': 'ego'}.get(meta['dataset_id']) + if meta['dataset_id'] == 'H2O': + expected = 'ego' if meta['camera_id'] == 'cam4' else 'exo' if meta['camera_id'] in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown' + if expected and meta['view_type'] not in (expected, 'unknown'): + raise ValueError('view_type contradicts known source capture setup') + + +def check_valid_policy(component, count): + policy = component.get('valid_policy', {}) + for field in ('revision', 'meaning', 'source_rule', 'source_locator', 'scope', 'numerical_checks', + 'official_qa', 'local_excluded_frame_indices', 'local_exclusion_reasons', 'visibility_independent'): + if field not in policy: + raise ValueError(f'valid_policy missing {field}') + if policy['revision'] != SCHEMA['validity_revision'] or policy['meaning'] != SCHEMA['annotation_validity']['meaning']: + raise ValueError('outdated annotation validity semantics') + if not policy['source_rule'] or not policy['numerical_checks'] or policy['scope'] != component['valid_axes']: + raise ValueError('incomplete validity rule/scope') + if policy['official_qa'].get('status') != 'not_provided' or not policy['official_qa'].get('reason'): + raise ValueError('official QA requires a verified adapter; supervision acceptance paused') + excluded = policy['local_excluded_frame_indices'] + if any(type(i) is not int or not 0 <= i < count for i in excluded): + raise ValueError('invalid local exclusion frame index') + if excluded: + raise ValueError('local exclusions require a reviewed rule/report; not supported by these adapters') + if policy['visibility_independent'] is not True: + raise ValueError('visibility must remain independent of validity') + + +def validate_view(path): + """Validate the persisted contract, not a rendering of the source labels.""" + path = Path(path) + meta = json.loads((path / 'metainfo.json').read_text()) + n = meta['num_frames'] + check_view_type(meta) + if meta['schema_version'] != SCHEMA['schema_version'] or meta['hand_slots'] != ['left', 'right'] or n < 1: + raise ValueError('invalid view header') + def resolve(ref): + if Path(ref).is_absolute() or '\\' in ref: + raise ValueError('component reference must be relative POSIX') + dest = safe_member(path, ref) + if not dest.is_file(): + raise ValueError(f'referenced file missing: {ref}') + return dest + def tensor(ref): + def cpu_storage(storage, location): + if location != 'cpu': + raise ValueError('PT storage must be on CPU') + return storage + value = torch.load(resolve(ref), map_location=cpu_storage, weights_only=True) + if not isinstance(value, torch.Tensor) or value.device.type != 'cpu': + raise ValueError('PT must contain only a CPU Tensor') + return value.numpy() + frames = [json.loads(line) for line in resolve(meta['sampling']['frames_ref']).read_text().splitlines()] + if len(frames) != n or [f['frame_index'] for f in frames] != list(range(n)): + raise ValueError('frame index/count mismatch') + for f in frames: + if not all(k in f for k in ('source_frame_id', 'timestamp_ns', 'clock_domain', 'source_locator')): + raise ValueError('incomplete frame provenance') + entities = {'hand_left', 'hand_right'} + parts = {} + for p in (path / 'annotation/object').glob('*/metainfo.json'): + obj = json.loads(p.read_text()) + if obj['object_id'] != p.parent.name or obj['identity_scope'] not in ('frame', 'subsequence', 'sequence'): + raise ValueError('invalid object identity') + entities.add(obj['object_id']) + if obj.get('mesh_ref'): + if not resolve(obj['mesh_ref']).is_relative_to(p.parent.resolve()): + raise ValueError('mesh must belong to its object') + if obj.get('articulation_ref'): + art = json.loads(resolve(obj['articulation_ref']).read_text()) + part_ids = {part['part_id'] for part in art['parts']} + if len(part_ids) != len(art['parts']): + raise ValueError('duplicate part ID') + parents = {part['part_id']: part['parent_id'] for part in art['parts']} + for part_id in parents: + visited, cur = set(), part_id + while cur is not None: + if cur in visited or cur not in parents: + raise ValueError('invalid or cyclic part hierarchy') + visited.add(cur) + cur = parents[cur] + parts[obj['object_id']] = part_ids + video_stats = {} + for key, component in meta['components'].items(): + if not component.get('available'): + if not component.get('reason'): + raise ValueError('unavailable component needs a reason') + continue + schema = SCHEMA['components'][component['schema_id']] + for required in ('axes', 'provenance', 'source_locator'): + if required not in component: + raise ValueError(f'{key}: {required} missing') + for required in schema.get('required_metadata', []): + if required not in component: + raise ValueError(f'{key}: {required} missing') + if component['provenance']['kind'] == 'derived': + raise ValueError('v1.0 must not synthesize annotations') + if component['data_ref'].startswith('annotation/') and schema.get('valid_shape'): + if not component.get('valid_ref') or not component.get('valid_axes'): + raise ValueError(f'{key}: annotation validity reference/axes missing') + check_valid_policy(component, n) + data_path = resolve(component['data_ref']) + valid = tensor(component['valid_ref']) if component.get('valid_ref', '').endswith('.pt') else None + valid_shape = schema.get('valid_shape') + if valid is not None and valid_shape and (len(valid_shape) != valid.ndim or any( + isinstance(s, int) and valid.shape[i] != s for i, s in enumerate(valid_shape))): + raise ValueError(f'{key}: validity schema shape mismatch') + if valid is not None and (valid.dtype != bool or valid.shape[0] != n): + raise ValueError(f'{key}: invalid validity tensor') + if component['schema_id'] == 'mesh/obj/v1': + objroot = next((parent for parent in data_path.parents if parent.parent.name == 'object'), None) + if objroot is None: + raise ValueError('mesh must be owned by an object') + check_mesh(data_path, objroot) + if data_path.suffix == '.pt': + arr = tensor(component['data_ref']) + if arr.dtype != np.float32 or arr.shape[0] != n: + raise ValueError(f'{key}: float dtype or timeline mismatch') + shape = schema.get('shape') + if shape and (len(shape) != arr.ndim or any(isinstance(s, int) and arr.shape[i] != s for i, s in enumerate(shape))): + raise ValueError(f'{key}: schema shape mismatch') + if valid is not None: + if arr.shape[:valid.ndim] != valid.shape or not np.isfinite(arr[valid]).all() or not np.isnan(arr[~valid]).all(): + raise ValueError(f'{key}: invalid finite/NaN/validity values') + if component['schema_id'] in ('object/rigid/v1', 'transform/se3/v1'): + check_transform(arr[valid]) + if data_path.suffix == '.mkv': + cfg = component['storage'] + if cfg['profile'] not in SCHEMA['storage_profiles']: + raise ValueError('unregistered video profile') + for field in SCHEMA['video_metadata']['required']: + if field not in cfg: + raise ValueError('video storage declaration incomplete') + w, h = meta['camera']['image_size'] + if cfg['encoded_size'] != [w * (2 if key == 'depth' else 1), h]: + raise ValueError('encoded raster differs from logical RGB grid') + actual = probe(data_path) + if (actual['codec_name'] != cfg['codec'] or actual['pix_fmt'] != cfg['pixel_format'] or + [actual['width'], actual['height']] != cfg['encoded_size']): + raise ValueError('video storage metadata differs from file') + if key == 'rgb': + fmt, bpp = 'rgb24', 3 + else: + fmt, bpp = 'gray16le', 2 + digest, size, _ = decoded_digest(data_path, fmt) + w, h = cfg['encoded_size'] + if size != n * w * h * bpp: + raise ValueError('raster timeline mismatch') + video_stats[key] = {'decoded_sha256': digest, 'frames': n} + if key == 'depth': + validity = component['valid_storage'] + vp = resolve(component['valid_ref']) + actual_valid = probe(vp) + if (validity['profile'] != 'mkv/bool_ffv1/v1' or actual_valid['codec_name'] != 'ffv1' + or actual_valid['pix_fmt'] != 'gray' or [actual_valid['width'], actual_valid['height']] != [w // 2, h]): + raise ValueError('invalid depth validity video') + count = 0 + for encoded, mask in zip(video_frames(data_path, 'gray16le', (h, w), ' 0)).all() or not np.isnan(depth[~good]).all(): + raise ValueError('invalid depth/validity semantics') + count += 1 + if count != n: + raise ValueError('depth validity timeline mismatch') + if component['schema_id'].startswith('segment/') and component.get('mapping_ref'): + rows = [json.loads(line) for line in resolve(component['mapping_ref']).read_text().splitlines()] + if len(rows) != n or [row['frame_index'] for row in rows] != list(range(n)): + raise ValueError('segmentation mapping timeline mismatch') + for row in rows: + labels = row['labels'] + if len({a['mask_value'] for a in labels}) != len(labels): + raise ValueError('duplicate region mapping') + for label in labels: + if label['entity_id'] is not None and label['entity_id'] not in entities: + raise ValueError('unresolved segmentation entity') + if label['part_id'] is not None and label['part_id'] not in parts.get(label['entity_id'], set()): + raise ValueError('unresolved segmentation part') + if component['schema_id'] == 'segment/uint16_labels/v1': + width, height = meta['camera']['image_size'] + for i, mask in enumerate(video_frames(data_path, 'gray16le', (height, width), ' 0 and meta.get('view_type') == 'exo', view + assert (view / 'camera/frames.jsonl').is_file(), view + assert meta['components']['rgb']['available'], view + splits[meta['split']] += 1 + for key, part in meta['components'].items(): + if part.get('available'): + availability[key] += 1 + for ref in ('data_ref', 'valid_ref'): + if part.get(ref): + assert (view / part[ref]).is_file(), (view, key, ref) + assert len(subjects) == 10 and set(subjects.values()) == {100}, subjects + assert availability['depth'] == availability['rgb'] == 8000, availability + report = dict(sequences=len(sequences), views=sum(splits.values()), subjects=dict(subjects), + splits=dict(splits), available_views=dict(availability), config=config, + published_script_sha256=hashes, sampled_views=[str(v.relative_to(root)) for v in selected], + scope='Structure and file refs checked for all views; persisted QC and HTML only for sampled views. No manual visual approval yet.') + destination = doc / 'validation' + destination.mkdir(exist_ok=True) + (destination / 'STRUCTURAL_AUDIT.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') + for view in selected: + render(view, destination) + return report + + +if __name__ == '__main__': + print(json.dumps(inspect(Path(sys.argv[1]).expanduser().resolve()), ensure_ascii=False), flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/render_h2o_validation.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/render_h2o_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..b89e7c0827f45ec7f854ff8651234cb9a4223f79 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/render_h2o_validation.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Render stored H2O RGB-D, native camera-space hands/objects, and OBJ assets for review.""" +import argparse +import html +import json +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw +import torch + +from render_hoi4d_validation import mesh_preview, picture, snapshot +from warehouse_v1_0 import unpack_depth, validate_view + + +def load(view, item, n): + if not item.get('available') or not item.get('data_ref', '').endswith('.pt'): + return None, None + values = torch.load(view / item['data_ref'], map_location='cpu', weights_only=True).numpy() + valid = torch.load(view / item['valid_ref'], map_location='cpu', weights_only=True).numpy() if item.get('valid_ref') else None + return (values, valid) if values.ndim and values.shape[0] == n else (None, None) + + +def render(view, destination): + meta = json.loads((view / 'metainfo.json').read_text()) + if meta['dataset_id'] != 'H2O': + raise ValueError('H2O view required') + n = meta['num_frames'] + height, width = reversed(meta['camera']['image_size']) + parts = meta['components'] + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + assert len(frames) == n + selected = {0, n // 4, n // 2, 3 * n // 4, n - 1} + numeric = {} + for name, item in parts.items(): + if item.get('data_ref', '').endswith('.pt') and item.get('available'): + values, valid = load(view, item, n) + if values is not None: + numeric[name] = (values, valid) + if valid is not None: + indices = np.flatnonzero(valid.reshape(n, -1).any(axis=1)) + if len(indices): + selected.add(int(indices[0])) + selected = set(sorted(selected)[:12]) | {n - 1} + rgb = snapshot(view / parts['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected) + depth = snapshot(view / parts['depth']['data_ref'], 'gray16le', (height, 2 * width), ' 0: + u, v = intrinsic[i, 0, 0] * xyz[0] / xyz[2] + intrinsic[i, 0, 2], intrinsic[i, 1, 1] * xyz[1] / xyz[2] + intrinsic[i, 1, 2] + if 0 <= u < width and 0 <= v < height: + draw.ellipse((u-4, v-4, u+4, v+4), fill=color) + legend.append(name + ' ' + color) + panels = ['
    ' + picture(photo) + '
    RGB + 原生 3D 关键点投影(仅预览:' + html.escape(', '.join(legend) or '当前帧无可投影点') + ')
    '] + if i in depth: + z = unpack_depth(depth[i]) + luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(luminance)) + '
    深度 Z,黑=无效,白≥3 m;不改源深度
    ') + details = {'frame': frames[i]} + for name, (values, valid) in numeric.items(): + details[name] = {'value': values[i].tolist(), 'valid': None if valid is None else valid[i].tolist()} + pages.append('

    帧 ' + str(i) + ' / ' + str(n) + '

    ' + ''.join(panels) + '
    原帧号、全部数值标注及有效性
    ' + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '
    ') + assets = [] + for name, item in parts.items(): + if item.get('available') and item.get('data_ref', '').lower().endswith('.obj'): + assets.append('

    ' + html.escape(name) + '

    ' + mesh_preview(view / item['data_ref']) + '
    源 OBJ 静态预览,不代表物体姿态投影
    ') + report = validate_view(view) + destination.mkdir(parents=True, exist_ok=True) + title = view.parent.name + '_' + view.name + style = 'body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;background:#f5f7fa;color:#18232f}section,details{background:white;padding:1rem;margin:1rem 0;border-radius:8px}.panels{display:flex;flex-wrap:wrap}img{max-width:100%}pre{white-space:pre-wrap;overflow:auto;font-size:12px}' + page = '' + html.escape(title) + '

    ' + html.escape(title) + '

    预览只作人工核查;仅显示真实存在的标注,不合成分割。

    ' + ''.join(pages) + '

    源网格

    ' + ''.join(assets) + '
    全部组件元数据
    ' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '
    持久化 QC
    ' + html.escape(json.dumps(report, ensure_ascii=False, indent=2)) + '
    ' + (destination / (title + '.html')).write_text(page) + (destination / (title + '.report.json')).write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') + links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html') + (destination / 'index.html').write_text('

    H2O 试点预览

    ') + return destination / (title + '.html') + + +if __name__ == '__main__': + p = argparse.ArgumentParser() + p.add_argument('views', nargs='+', type=Path) + p.add_argument('--out', type=Path, required=True) + args = p.parse_args() + for view in args.views: + print(render(view, args.out), flush=True) diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/render_hoi4d_source_review.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/render_hoi4d_source_review.py new file mode 100644 index 0000000000000000000000000000000000000000..79d7a58744572343670e9cbaecc4cc54ea07f1c1 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/render_hoi4d_source_review.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Evidence-only HTML: native HOI4D pose boxes over persisted RGB and native masks.""" +import argparse +import html +import json +from pathlib import Path +import shutil +import zipfile + +import numpy as np +from PIL import Image, ImageDraw + +from render_hoi4d_validation import picture, snapshot + + +def source_parts(view): + rows = [] + for source in view.glob('annotation/object/*/assets/result.json'): + def visit(node): + if isinstance(node, list): + for child in node: + visit(child) + return + if node.get('objs'): + rows.append({'source_part_id': node['id'], 'source_part_name': node['name'], + 'source_meshes': node['objs'], 'source_locator': str(source.relative_to(view))}) + for child in node.get('children', []): + visit(child) + visit(json.loads(source.read_text())) + return rows + + +def render(view, z, output): + output.mkdir(parents=True, exist_ok=True) + meta = json.loads((view / 'metainfo.json').read_text()) + seq = meta['sampling']['selection']['source_sequence'] + w, h = meta['camera']['image_size'] + chosen = sorted({0, meta['num_frames'] // 2, meta['num_frames'] - 1}) + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + rgb = snapshot(view / meta['components']['rgb']['data_ref'], 'rgb24', (h, w, 3), np.uint8, chosen) + segment = meta['components'].get('segment', {}) + masks = (snapshot(view / segment['data_ref'], 'gray16le', (h, w), '

    ' + html.escape(seq) + f' / frame {native_id}

    ' + picture(image) + + '

    仅验收:伪彩=原生分割码,黄框=上游 2dBox;颜色和框不写回 shared,空间重叠不能代替身份依据。

    ' + + '
    上游原记录与编码对照
    '
    +                      + html.escape(json.dumps(note, ensure_ascii=False, indent=2)) + '
    ') + parts = source_parts(view) + name = view.parent.name + '_' + view.name + '.html' + page = 'HOI4D source correspondence review

    源姿态/原生分割/RGB 的证据图(非真值修改)

    ' + page += ''.join(panels) + '
    CAD result.json 原生部件→OBJ;不等同逐帧姿态对应
    '
    +    page += html.escape(json.dumps(parts, ensure_ascii=False, indent=2)) + '
    ' + (output / name).write_text(page) + print(name, 'native_part_links',len(parts),flush=True) + return name + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('--raw-root', type=Path, required=True) + p.add_argument('--release', type=Path, required=True) + p.add_argument('--out', type=Path, required=True) + args = p.parse_args(argv) + args.out.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(args.raw_root / 'HOI4D_annotations.zip') as z: + names = [] + for view in sorted((args.release / 'data').glob('*/ego')): + if any('/C' + category + '/' in json.loads((view / 'metainfo.json').read_text())['sampling']['selection']['source_sequence'] + for category in ('2', '3', '14', '17')): + names.append(render(view, z, args.out)) + links = ''.join(f'
  • {html.escape(name)}
  • ' for name in names) + (args.out / 'index.html').write_text('

    源依据对照(非物体几何验收通过)

      ' + links + '
    ') + shutil.copyfile(Path(__file__), args.out / 'renderer.py') + + +if __name__ == '__main__': + main() diff --git a/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/render_hoi4d_validation.py b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/render_hoi4d_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..a7889a1b63b004e046b52fe4e4da0b2b4651b768 --- /dev/null +++ b/H2O/shared-v1.1/script/v1_0_snapshot/script/provenance/previous-run/script/render_hoi4d_validation.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Standalone, offline HTML review of every persisted component in selected views.""" +import argparse +import base64 +import html +import io +import json +import random +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw +import torch + +from warehouse_v1_0 import video_frames, unpack_depth, validate_view + + +def snapshot(video, fmt, shape, dtype, indices): + return {i: frame.copy() for i, frame in enumerate(video_frames(video, fmt, shape, dtype)) if i in indices} + + +def picture(image): + image.thumbnail((800, 450)) # Previews only; released tensors and videos are not resized. + output = io.BytesIO() + image.save(output, format='PNG') + return '' + + +def preview_color(value, dataset_id): + # Dex-YCB reserves 255 for the native hand mask. The old mod-240 palette + # gave it the same color as YCB object 15; keep data codes untouched. + if dataset_id == 'dex-ycb' and value == 255: + return (255, 32, 64) + return tuple((value * factor) % 240 + 15 for factor in (89, 61, 131)) + + +def mesh_preview(path): + """Project the whole source asset; bound drawing cost without favoring early faces.""" + vertices, faces, referenced = [], [], set() + rng = random.Random(0) + face_count = 0 + with path.open(errors='replace') as stream: + for line in stream: + if line.startswith('v '): + vertices.append([float(v) for v in line.split()[1:4]]) + elif line.startswith('f '): + face = [] + for token in line.split()[1:]: + index = int(token.split('/')[0]) + face.append(index - 1 if index > 0 else len(vertices) + index) + if len(face) < 3: + continue + referenced.update(face) + face_count += 1 + # ponytail: bounded static preview; use a full OBJ viewer if 5000 faces miss fine detail. + if len(faces) < 5000: + faces.append(face) + else: + pick = rng.randrange(face_count) + if pick < len(faces): + faces[pick] = face + if not vertices or not faces: + return 'OBJ 未提供可绘制的顶点/面' + if min(referenced) < 0 or max(referenced) >= len(vertices): + raise ValueError(f'invalid OBJ face index: {path}') + xyz = np.asarray(vertices, dtype=np.float64) + if not np.isfinite(xyz).all(): + raise ValueError(f'nonfinite OBJ vertex: {path}') + # Fixed orthonormal isometric basis: geometry only, not an inferred camera pose. + projected = np.column_stack(((xyz[:, 0] - xyz[:, 2]) / np.sqrt(2), + (xyz[:, 0] + xyz[:, 2] - 2 * xyz[:, 1]) / np.sqrt(6))) + used = projected[np.fromiter(referenced, dtype=np.int64)] + lo, hi = used.min(axis=0), used.max(axis=0) + extent = (hi - lo).max() + if extent <= 0: + return 'OBJ 所有面投影到同一点' + projected = (projected - (lo + hi) / 2) * (380 / extent) + 215 + image = Image.new('RGB', (430, 430), 'white') + draw = ImageDraw.Draw(image) + for face in faces: + polygon = [tuple(projected[i]) for i in face] + draw.line(polygon + [polygon[0]], fill='#205caa', width=1) + return picture(image) + + +def render(view, destination): + meta = json.loads((view / 'metainfo.json').read_text()) + n = meta['num_frames'] + width, height = meta['camera']['image_size'] + components = meta['components'] + frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()] + assert len(frames) == n + selected = {0, n // 4, n // 2, 3 * n // 4, n - 1} + for item in components.values(): + ref = item.get('valid_ref', '') + if ref.endswith('.pt'): + valid = torch.load(view / ref, map_location='cpu', weights_only=True).numpy() + if valid.shape[0] == n: + matching = np.flatnonzero(valid.reshape(n, -1).any(axis=1)) + if len(matching): + selected.add(int(matching[0])) + selected = set(sorted(selected)[:12]) | {n - 1} + rgb = snapshot(view / components['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected) + depth = (snapshot(view / components['depth']['data_ref'], 'gray16le', (height, 2 * width), '' + picture(image) + '
    RGB + 原生 2D 手关键点(若有)
    '] + if i in depth: + z = unpack_depth(depth[i]) + luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(luminance)) + '
    深度 Z(黑=无效,白≥3 m;仅预览)
    ') + if i in masks: + mask = masks[i] + colors = np.zeros((*mask.shape, 3), dtype=np.uint8) + for value in np.unique(mask): + if value not in (0, 65535): + colors[mask == value] = preview_color(int(value), meta['dataset_id']) + legend = ';'.join(f'{int(value)}=' + ('手' if value == 255 and meta['dataset_id'] == 'dex-ycb' else '物体' if meta['dataset_id'] == 'dex-ycb' else '区域') + f' #{bytes(preview_color(int(value), meta["dataset_id"])).hex()}' for value in np.unique(mask) if value not in (0, 65535)) + panels.append('
    ' + picture(Image.fromarray(colors)) + '
    原生分割整数编码的伪彩色预览(' + html.escape(legend) + ')
    ') + active = (mask != 0) & (mask != 65535) + overlay = rgb[i].copy() + overlay[active] = ((overlay[active].astype(np.uint16) + colors[active]) // 2).astype(np.uint8) + panels.append('
    ' + picture(Image.fromarray(overlay)) + '
    原生分割叠加 RGB(仅预览)
    ') + details = {'frame': frames[i], 'segment_labels': labels.get(i, [])} + for name, component in components.items(): + ref = component.get('data_ref', '') + if component.get('available') and ref.endswith('.pt'): + values = torch.load(view / ref, map_location='cpu', weights_only=True) + if values.ndim and values.shape[0] == n: + details[name] = {'value': values[i].tolist()} + if component.get('valid_ref', '').endswith('.pt'): + valid = torch.load(view / component['valid_ref'], map_location='cpu', weights_only=True) + details[name]['valid'] = valid[i].tolist() + sections.append('

    帧 ' + str(i) + ' / ' + str(n) + '

    ' + ''.join(panels) + + '
    帧号、来源、全部数值组件与有效性
    '
    +                        + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '
    ') + assets = [] + for name, component in components.items(): + if component.get('available') and component['data_ref'].lower().endswith('.obj'): + ref = component['data_ref'] + assets.append('

    ' + html.escape(name) + '

    ' + mesh_preview(view / ref) + + '
    仅展示网格原生形状;未验证尺度/位姿对应。
    ') + result = validate_view(view) + destination.mkdir(parents=True, exist_ok=True) + title = view.parent.name + '_' + view.name + css = 'body{font:16px sans-serif;max-width:1500px;margin:auto;padding:1rem;background:#f5f7fa;color:#18232f}section,details{background:#fff;padding:1rem;margin:1rem 0;border-radius:8px}figure{margin:.5rem}figcaption{font-size:.85rem}.panels{display:flex;flex-wrap:wrap}img{max-width:100%;border:1px solid #ddd}pre{white-space:pre-wrap;overflow:auto;font-size:12px}' + page = '' + html.escape(title) + '

    ' + html.escape(title) + '

    预览图仅供人工审核,不是训练输入;未提供的模态在 metainfo 中保留原因。

    ' + ''.join(sections) + '

    原始物体模型(独立预览)

    ' + ''.join(assets) + '
    全部组件元信息及原始来源
    ' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '
    持久化 QC 结果
    ' + html.escape(json.dumps(result, ensure_ascii=False, indent=2)) + '
    ' + (destination / (title + '.html')).write_text(page) + (destination / (title + '.report.json')).write_text(json.dumps(result, ensure_ascii=False, indent=2)) + links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html') + (destination / 'index.html').write_text('' + html.escape(meta['dataset_id']) + ' review

    ' + html.escape(meta['dataset_id']) + ' 抽样人工审核

    选择视图;所有预览均来自已保存的 shared 数据。

    ') + print(destination / (title + '.html'), 'selected_frames', sorted(selected), flush=True) + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument('views', nargs='+', type=Path) + p.add_argument('--out', type=Path) + args = p.parse_args() + for view in args.views: + render(view, args.out or view.parents[2] / 'doc/validation') + + +if __name__ == '__main__': + main()