orz2333 commited on
Commit
804a923
·
verified ·
1 Parent(s): 1ac102a

Upload folder using huggingface_hub (part 34)

Browse files
Files changed (32) hide show
  1. dex-ycb/shared-v1.0/doc/validation/20201015-subject-09_20201015_142601_932122062010.report.json +19 -0
  2. dex-ycb/shared-v1.0/doc/validation/20201015-subject-09_20201015_150838_836212060125.html +0 -0
  3. dex-ycb/shared-v1.0/doc/validation/20201015-subject-09_20201015_150838_836212060125.report.json +19 -0
  4. dex-ycb/shared-v1.0/doc/validation/20201022-subject-10_20201022_110806_836212060125.html +0 -0
  5. dex-ycb/shared-v1.0/doc/validation/20201022-subject-10_20201022_110806_836212060125.report.json +19 -0
  6. dex-ycb/shared-v1.0/doc/validation/CONTRACT.md +459 -0
  7. dex-ycb/shared-v1.0/doc/validation/KEYPOINT_PROJECTION_QC.json +77 -0
  8. dex-ycb/shared-v1.0/doc/validation/SOURCE_FRAME_COVERAGE.json +16 -0
  9. dex-ycb/shared-v1.0/doc/validation/SOURCE_FRAME_COVERAGE.log +1 -0
  10. dex-ycb/shared-v1.0/doc/validation/SOURCE_FRAME_COVERAGE.status +2 -0
  11. dex-ycb/shared-v1.0/doc/validation/STRUCTURAL_AUDIT.json +108 -0
  12. dex-ycb/shared-v1.0/doc/validation/colorfix-run.log +13 -0
  13. dex-ycb/shared-v1.0/doc/validation/colorfix-run.status +2 -0
  14. dex-ycb/shared-v1.0/doc/validation/index.html +1 -0
  15. dex-ycb/shared-v1.0/doc/validation/render_dexycb_validation.before-color-fix.py +64 -0
  16. dex-ycb/shared-v1.0/doc/validation/render_hoi4d_validation.before-color-fix.py +173 -0
  17. dex-ycb/shared-v1.0/doc/validation/validation-run.log +12 -0
  18. dex-ycb/shared-v1.0/doc/validation/validation-run.status +1 -0
  19. dex-ycb/shared-v1.0/script/__pycache__/render_dexycb_validation.py.cpython-38.pyc +0 -0
  20. dex-ycb/shared-v1.0/script/__pycache__/render_hoi4d_validation.cpython-312.pyc +0 -0
  21. dex-ycb/shared-v1.0/script/__pycache__/render_hoi4d_validation.py.cpython-38.pyc +0 -0
  22. dex-ycb/shared-v1.0/script/__pycache__/warehouse_v1_0.cpython-312.pyc +0 -0
  23. dex-ycb/shared-v1.0/script/check_dexycb_coverage.py +55 -0
  24. dex-ycb/shared-v1.0/script/check_dexycb_projection.py +31 -0
  25. dex-ycb/shared-v1.0/script/config.json +11 -0
  26. dex-ycb/shared-v1.0/script/convert_dexycb_v1.0.py +349 -0
  27. dex-ycb/shared-v1.0/script/convert_h2o_v1.0.py +476 -0
  28. dex-ycb/shared-v1.0/script/convert_hoi4d_v1.0.py +534 -0
  29. dex-ycb/shared-v1.0/script/convert_visor_v1.0.py +271 -0
  30. dex-ycb/shared-v1.0/script/render_dexycb_validation.py +66 -0
  31. dex-ycb/shared-v1.0/script/render_hoi4d_validation.py +182 -0
  32. dex-ycb/shared-v1.0/script/warehouse_v1_0.py +922 -0
dex-ycb/shared-v1.0/doc/validation/20201015-subject-09_20201015_142601_932122062010.report.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "view": "/data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/data/20201015-subject-09_20201015_142601/932122062010",
3
+ "num_frames": 74,
4
+ "videos": {
5
+ "rgb": {
6
+ "decoded_sha256": "55990cf7832291abaa44e240e5d6d86cb507e5408fa1b77abc76cf094a7491ce",
7
+ "frames": 74
8
+ },
9
+ "segment": {
10
+ "decoded_sha256": "ca78a90aefff56e61dee441e574bb85e5be08e4b83b933189a0bbf395d2e51f8",
11
+ "frames": 74
12
+ },
13
+ "depth": {
14
+ "decoded_sha256": "6fc9d7f73efff1adaada3a333f2806892b7d793f3b695338340f59ce2528a6ea",
15
+ "frames": 74
16
+ }
17
+ },
18
+ "validated": true
19
+ }
dex-ycb/shared-v1.0/doc/validation/20201015-subject-09_20201015_150838_836212060125.html ADDED
The diff for this file is too large to render. See raw diff
 
dex-ycb/shared-v1.0/doc/validation/20201015-subject-09_20201015_150838_836212060125.report.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "view": "/data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/data/20201015-subject-09_20201015_150838/836212060125",
3
+ "num_frames": 74,
4
+ "videos": {
5
+ "rgb": {
6
+ "decoded_sha256": "418f4c8c573c0b2336058a7ec4f382091006cd9a34b9c50abfdc7dd5b106f698",
7
+ "frames": 74
8
+ },
9
+ "segment": {
10
+ "decoded_sha256": "05b5d799d50dd67c5ef70147e04384b1126ad311067a2d7c8c0028f82c9a4d25",
11
+ "frames": 74
12
+ },
13
+ "depth": {
14
+ "decoded_sha256": "562f8467a5bf72b0816505b6e98f275f61b601372b32a1b6bc21ba4b55816633",
15
+ "frames": 74
16
+ }
17
+ },
18
+ "validated": true
19
+ }
dex-ycb/shared-v1.0/doc/validation/20201022-subject-10_20201022_110806_836212060125.html ADDED
The diff for this file is too large to render. See raw diff
 
dex-ycb/shared-v1.0/doc/validation/20201022-subject-10_20201022_110806_836212060125.report.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "view": "/data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/data/20201022-subject-10_20201022_110806/836212060125",
3
+ "num_frames": 72,
4
+ "videos": {
5
+ "rgb": {
6
+ "decoded_sha256": "b64194bea3d31c1e60da8eb8a51448cbc5e009e5ea73518667ad257b1ba2cd21",
7
+ "frames": 72
8
+ },
9
+ "segment": {
10
+ "decoded_sha256": "442eb3348fd2d2048634c49e99cb634fdb64582fcd31b4010a948e51d081e723",
11
+ "frames": 72
12
+ },
13
+ "depth": {
14
+ "decoded_sha256": "0232612cef8f28afb7d0ae78be87a59c705fc467420b32cec22cfa121d298fd8",
15
+ "frames": 72
16
+ }
17
+ },
18
+ "validated": true
19
+ }
dex-ycb/shared-v1.0/doc/validation/CONTRACT.md ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 手物数据仓库统一约定 v1.0
2
+
3
+ 格式版本:`hand-warehouse/1.0`。存储约定:`lossless-video-2026-09-18`。
4
+
5
+ 范围限于手物交互重建。按本任务纳入的源模态转换,不要求每个数据集填满所有组件。缺失模态、尚未下载、语义未核实分别报告,不能互相替代。
6
+
7
+ shared 层不是 raw 的完整镜像。处理者只需提取本次任务范围明确要求、语义已经核实且能够按本规范可靠转换的字段和模态。raw 中其余字段可以不纳入 shared,但必须在 `RAW_TO_SHARED.md` 中列出主要未纳入内容及原因。不得为了覆盖全部 raw 字段而猜测语义、虚构模态或保存未经定义的字段。未纳入 shared 不等于源数据不存在,原始信息仍以 raw 为准。
8
+
9
+ 本文定义各字段的含义与使用规则,机器可读注册表见 [schema.json](schema.json)。两者互相补充;如有冲突,应先核实并统一定义。
10
+
11
+ ## 1. 目录
12
+
13
+ ```text
14
+ hand-datasets/
15
+ <dataset_name>/
16
+ raw/
17
+ doc/ # 官方说明、来源与校验记录
18
+ script/ # 官方下载脚本、必要包装脚本
19
+ data/ # 保留原始包,不原地解压或改写
20
+ <dataset_version>/
21
+ doc/ # 发布说明、schema、来源清单
22
+ script/ # 转换、校验脚本及运行配置
23
+ data/
24
+ <sequence_id>/
25
+ <camera_id>/
26
+ metainfo.json
27
+ observation/
28
+ rgb.mkv
29
+ rgb_valid.pt
30
+ depth.mkv # float32 深度的可逆视频编码
31
+ depth_valid.mkv # 逐像素 bool 的无损视频编码
32
+ camera/
33
+ frames.jsonl
34
+ intrinsic.pt
35
+ intrinsic_valid.pt
36
+ extrinsic.pt
37
+ extrinsic_valid.pt
38
+ annotation/
39
+ mano/
40
+ motion.pt
41
+ motion_valid.pt
42
+ visibility.pt
43
+ keypoints/
44
+ uv.pt
45
+ uv_valid.pt
46
+ xyz.pt
47
+ xyz_valid.pt
48
+ visibility.pt # 源数据有时提供
49
+ object/
50
+ <object_id>/
51
+ assets/ # 该物体的网格、材质、纹理及部件资产
52
+ <mesh_id>.obj
53
+ pose.pt
54
+ pose_valid.pt
55
+ visibility.pt
56
+ metainfo.json # 物体身份、类别、mesh、尺寸与部件引用
57
+ articulation.json
58
+ keypoints/
59
+ vertex_part_ids.pt
60
+ joint_state.pt
61
+ joint_state_valid.pt
62
+ parts/<part_id>/pose.pt
63
+ parts/<part_id>/pose_valid.pt
64
+ segment/
65
+ mask.mkv
66
+ mask_valid.pt
67
+ instances.jsonl
68
+ contact/
69
+ relations.jsonl
70
+ <subject_id>__<object_id>/ # 对应实体间的距离/接触区域
71
+ ```
72
+
73
+ 目录展示可能存在的组件,不要求填满。具体文件、字段和缺省规则分别见后续对应小节。原始包的解压发生在临时工作区,raw 内原始包保持不变。
74
+
75
+ ## 2. 相机视图的 metainfo.json
76
+
77
+ ### 2.1 顶层字段与发布信息
78
+
79
+ 每个相机视图必须有 `metainfo.json`。以下字段除另行说明外均为必填:
80
+
81
+ | 字段 | 填写内容 |
82
+ |---|---|
83
+ | schema_version | 结构版本,本版为 `hand-warehouse/1.0` |
84
+ | dataset_id | 数据集的逻辑标识 |
85
+ | release_id | 本次数据发布版本,对应目录中的 dataset_version |
86
+ | sequence_id | 所属序列或独立图片样本的标识 |
87
+ | camera_id | 当前相机视图标识 |
88
+ | sample_type | `image` 或 `video`,规则见 2.2 |
89
+ | num_frames | 当前视图帧数 T,所有随帧组件按同一时间轴组织 |
90
+ | hand_slots | 固定为 `["left", "right"]`;解剖学左右的使用规则见 5.1 |
91
+ | sampling | 采样类型、源 FPS、帧索引引用及选择策略,见 2.2 |
92
+ | camera | 当前相机模型与图像尺寸,见 2.3 |
93
+ | components | 实际提供的组件及其文件、schema、有效性和来源,见 2.5 |
94
+ | split | `train/val/test/unknown`,划分协议见 2.4 |
95
+ | view_type | 必填,固定为 `ego/exo/unknown`。源数据或采集设置明确相机视角时必须填写 `ego` 或 `exo`;只有无法从可信来源确定时才填写 `unknown`,不得省略或主观猜测。多相机序列须逐视图分别填写。 |
96
+
97
+ `dataset_version` 是数据发布版本;`schema_version` 是结构版本,两者独立。原始包校验摘要、官方来源和转换配置应记录在发布清单中。解压发生在临时工作区,原始包保持不变。
98
+
99
+ ### 2.2 图片、视频与 sampling
100
+
101
+ `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。合成背景变体不视为真实多相机。
102
+
103
+ `sample_type=video`:`sampling.type=dense/sparse`;`source_fps` 是真实采集 FPS,未知为 null。非连续取样必须保留源帧号和已知源时间,不可用采样后索引除以 FPS 冒充源时间。可另记采样策略与步长。
104
+
105
+ shared 可以仅存所选 RGB 帧对应的数据。OakInk2 图像/动捕不同采样率时用 annotation_matches 明确映射;不要求将未采样动捕点硬塞进 T。多视角身份和源同步关系要保留;选择了哪些帧/相机及原因写在 sampling 中。
106
+
107
+ `sampling.frames_ref` 指向 `camera/frames.jsonl`。帧号、逐帧时间、同步与标注匹配记录的结构见 4.1;MKV 封装时间的约定见 3.1。
108
+
109
+ ### 2.3 camera 模型声明
110
+
111
+ `camera` 至少包含 `model`、`schema_id`、`image_size:[W,H]`。模型未知使用 `unknown` 和 `null`,不猜成针孔。实际内参、畸变及外参数组放在 `camera/`,各模型的固定结构见第 4 节。
112
+
113
+ ### 2.4 split 与划分协议
114
+
115
+ 保留上游划分,不将同一采集序列的相邻帧随意拆到不同集合。
116
+
117
+ 有官方划分时必填 split_scheme 和 split_source_locator,split_scheme 区分如 Dex-YCB s0/s1、ARCTIC P1/P2 等选定协议;不知道时 split=unknown 并给理由,不凭空分配。每发布可选择一种协议;存在逐帧差异时 frames 中的 split 覆盖视图默认值,并登记其来源。
118
+
119
+ ### 2.5 components 组件登记
120
+
121
+ 组件表的键是本发布内唯一名称,例如 `rgb`、`depth`、`mano`、`keypoints_uv`。每个已提供组件声明以下信息;模态特有参数在第 3–5 节对应小节中定义。
122
+
123
+ | 字段 | 约定 |
124
+ |---|---|
125
+ | available | 本发布是否提供该组件;缺省也表示未提供 |
126
+ | schema_id | 已登记的具体存储与语义类型,不得临时创造未登记名称 |
127
+ | data_ref | 数据文件路径,相对当前相机视图根目录,使用 POSIX 路径 |
128
+ | axes | 数组各维度的含义 |
129
+ | valid_ref / valid_axes | 有效性文件及其维度;语义由所属组件规定 |
130
+ | storage / valid_storage | 视频数据/视频有效性的存储配置;包含已登记 profile、实际 codec、pixel_format、encoded_size,见 3.1;非视频组件按原数组规则 |
131
+ | provenance | source / format_conversion / derived,以及转换或生成方法 |
132
+ | source_locator | 原文件、压缩包成员和记录/帧的定位信息 |
133
+
134
+ 不存在的组件允许缺省或写作 `{ "available": false, "reason": "..." }`,不用引用不存在的文件。静态网格可声明标量有效性;具体见 5.4。观测的 valid 见第 3 节,标注的 valid 与 visibility 区分见 5.1。
135
+
136
+ `provenance.kind` 使用 source/format_conversion/derived,`method` 说明转换或生成方法;发布清单补充脚本版本、参数、输入摘要。`source_locator` 定位到原始文件/压缩包成员和记录、帧号;允许引用有完整溯源清单的前一发布,但链条最终应能回到 raw。不得仅写一个无法定位记录的数据集名字。
137
+
138
+ `.pt` 仅保存 CPU Tensor,不保存 Python 自定义对象;浮点默认 float32,有效性为 bool,浮点无效位置填 NaN。所有随帧数组保留首维 T,单帧也不 squeeze;静态资产按其 schema 单独声明。单位、坐标及固定形状见各组件小节。
139
+
140
+ 机器注册表 `schema.json` 中,`components` 固定解码后的数据类型、形状、单位和语义;`storage_profiles` 固定视频内的编码/还原方式。不得临时创造未登记的 schema_id 或 storage.profile。同一语义允许选择其登记的不同无损存储 profile。
141
+
142
+ ## 3. observation 观测数据
143
+
144
+ ### 3.1 rgb.mkv 与 rgb_valid.pt
145
+
146
+ RGB、深度和栅格 mask 在 shared 中统一使用 MKV 视频容器,不展开为逐帧图片或图像 tar。MANO、关键点、位姿等数值标注仍用数组;分割的重叠多边形仍用 JSONL,不为了视频化而有损栅格化。单图可为一帧视频,独立图批量封装规则见 2.2。
147
+
148
+ **无损指共享层不增加信息损失。** 源 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 位冒充无损。
149
+
150
+ #### 3.1.1 允许的 RGB 存储 profile
151
+
152
+ | storage.profile | 编码方式 | 适用规则 |
153
+ |---|---|---|
154
+ | mkv/mjpeg_copy/v1 | 源 JPEG 压缩帧直接封装成 MJPEG/MKV | 不解码重编码;保持每张 JPEG 码流字节;普通 8 位 JPEG 且 MKV/解码器支持时使用 |
155
+ | mkv/source_copy/v1 | 已有视频的 RGB 对应码流直接封装为 MKV | 仅源编码能被 MKV 和选定解码器支持时使用,不伪造帧;需维持正确的呈现顺序与依赖帧 |
156
+ | mkv/h264_rgb_lossless/v1 | libx264rgb 的真正无损模式 | 必须 RGB 路径、CRF=0,并通过全帧 RGB 字节比较;不能替换成默认 libx264 YUV420 路径 |
157
+ | mkv/ffv1_rgb/v1 | FFV1 的 RGB 可逆编码路径 | 作为通用候选;解码回 RGB 后必须逐字节相同,不做色度降采样 |
158
+
159
+ 优先尝试源码流直接封装;不能封装或需要选择稀疏帧时,比较 FFV1 与无损 RGB H.264。对完整待发布片段,只在通过无损验收的候选中选择文件较小者,不假设某个编码器总最小;编码时间和随机读取代价记入构建记录。中间候选不作为 shared 多份常驻。H.264 跨帧压缩允许较长 GOP,必须记录 GOP/关键帧间隔,随机取帧需从前一关键帧正确解码,不能把 seek 返回的近似帧当目标帧。
160
+
161
+ 普通源视频可以保留它已有的有损码流,但不允许新增有损重编码。源是 VRS 等记录容器时,先查明图像流实际编码:已有兼容 JPEG/视频包可直接提取封装,否则解码后使用真正无损编码;不把整个 VRS 改后缀当 MKV。PNG 不要求直接塞进 MKV,可选上表两种无损重编码方式。
162
+
163
+ #### 3.1.2 视频配置与校验
164
+
165
+ 每个视频组件在 metainfo 中登记 `storage`,至少包含:
166
+
167
+ | 字段 | 内容 |
168
+ |---|---|
169
+ | profile | 上述登记的存储 profile;语义仍由组件 schema_id 指定 |
170
+ | codec | 文件中实际 codec,例如 mjpeg、h264、ffv1;source_copy 必须写实际 codec |
171
+ | pixel_format | 实际编码像素格式;不得仅凭编码器参数猜测 |
172
+ | encoded_size | 视频物理像素尺寸 `[width,height]`;深度可能不同于逻辑尺寸,见 3.2 |
173
+ | decoder | 解码器名称、版本,以及颜色矩阵/范围/旋转处理等实际像素解释配置;未知的源色彩声明 unknown,不擅自称为 sRGB |
174
+ | encoder_parameters | 重编码时的编码器、版本、无损模式和 GOP 等参数;直接封装时记录 stream_copy |
175
+ | source_lossy | 源是否已有损:true / false / unknown;不是共享层再有损编码的许可 |
176
+
177
+ 无损重新编码的 RGB 必须使用同一固定解码配置,比较**全部帧**的统一 RGB 字节、数量及顺序。MJPEG-copy 不重新编码,生产校验采用 `jpeg-packets-all-rgb-sample16/v1`:从 MKV 逐包取回,对全部源 JPEG 的 SHA256、数量、顺序和图像尺寸进行精确核对;每视图另用同一固定解码配置比较最多 16 帧的源与目标 RGB 字节(含首尾与四分位位置,其余由固定种子抽取)。记录策略、实际索引、种子与结果;不足 16 帧时全查。试点与最终完整序列随机抽查,对选中视图的全部帧复核解码 RGB。历史已做全帧像素检查的证明继续保留。
178
+
179
+ 逐包一致与像素抽查的范围必须分别声明,不能将抽查写成全量像素检查。不能用 PSNR 高、视觉相似、编码器参数称为 lossless 等替代精确检查。同时保留源编码的色彩标记和必要元数据;原图有 EXIF/色彩/方向等元数据时保留 raw 和必要来源信息;不能静默自动旋转图像而不更新像素对应与标定。以上加速策略仅适用于原 JPEG 码流直接封装,不适用于深度、标签或重新编码的 RGB。
180
+
181
+ 所有共享视频的呈现帧顺序与统一 frame_index 一一对应,每个栅格组件恰好 T 帧。MKV 的 `storage_fps` 只服务封装,声明 `timebase_role=index_only`;source_copy 可以保留源 PTS 以避免改坏码流,但真实时间与标注对齐仍以 frames 为准。未知真实时间保留 null。缺失某帧组件时保留索引位置并使用该组件的无效占位/valid 标识,不删帧;不能以重复相邻图像冒充已知观测。
182
+
183
+ ### 3.2 depth.mkv 与 depth_valid.mkv
184
+
185
+ 深度语义仍是 `depth/z_float32/v1`:统一读取结果 `[T,H,W] float32`,米制相机 Z 分量,`depth_type=z`。有效深度有限且大于 0,无效位置为 NaN。`depth_origin=measured/rendered/unknown` 必填,来源不明时 unknown。默认与 RGB 共用像素网格及相机参考系,不处理未注册 RGB-D。射线距离必须依据源定义转换成 z,不能只改声明。
186
+
187
+ #### 3.2.1 float32 的可逆视频编码
188
+
189
+ 采用 `mkv/depth_float32_bits/v1`:**不是把深度量化成 uint16**��而是将规范化后每个 IEEE-754 float32 的完整 32 位拆成两个 uint16,使用 FFV1 gray16le 保存。视频物理尺寸为 `[2W,H]`:每行前 W 列存原 float32 位串的低 16 位,后 W 列存高 16 位。读取时先合并为 uint32 位串,再按 float32 重新解释,不能数值 cast 成 float32。
190
+
191
+ ```text
192
+ u = reinterpret_uint32(depth_float32)
193
+ encoded[:, :, :W] = uint16(u & 65535)
194
+ encoded[:, :, W:] = uint16(u >> 16)
195
+ u_restored = uint32(low) | (uint32(high) << 16)
196
+ depth_float32 = reinterpret_float32(u_restored)
197
+ ```
198
+
199
+ 统一采用 little-endian 原始字节接口。`camera.image_size` 始终是逻辑 RGB 尺寸 `[W,H]`,不能改成编码视频的 2W;`storage.encoded_size=[2W,H]`。包括 NaN 在内的 float32 位串必须全帧完全恢复,不允许改成 float16、整数毫米、归一化灰度或 RGB 伪彩色。这里的无损验收基准是完成既定米制/坐标转换后的标准 float32 数组,不声称消除 float64→float32 等原约定转换本身的舍入。
200
+
201
+ #### 3.2.2 逐像素有效性
202
+
203
+ `depth_valid.mkv` 使用 `mkv/bool_ffv1/v1`,FFV1 gray8(FFmpeg pixel_format=`gray`),物理尺寸 `[W,H]`。像素只能为 0 或 1,统一解码为 `[T,H,W] bool`,逐像素含义不变。这样不再把庞大的 bool 数组保存为未压缩 `.pt`;标注的帧级/手级 valid 仍保留原有小数组。
204
+
205
+ 登记示例(W、H 以下取 640、480;decoder/encoder_parameters 的实际版本由转换器填写):
206
+
207
+ ```json
208
+ {
209
+ "available": true,
210
+ "schema_id": "depth/z_float32/v1",
211
+ "data_ref": "observation/depth.mkv",
212
+ "axes": ["T", "height", "width"],
213
+ "valid_ref": "observation/depth_valid.mkv",
214
+ "valid_axes": ["T", "height", "width"],
215
+ "unit": "m",
216
+ "depth_type": "z",
217
+ "depth_origin": "measured",
218
+ "invalid_value": "NaN",
219
+ "storage": {
220
+ "profile": "mkv/depth_float32_bits/v1",
221
+ "codec": "ffv1",
222
+ "pixel_format": "gray16le",
223
+ "encoded_size": [1280, 480],
224
+ "source_lossy": false,
225
+ "decoder": {"name": "ffmpeg", "version": "填写实际版本"},
226
+ "encoder_parameters": {"name": "ffv1", "level": 3, "version": "填写实际版本"}
227
+ },
228
+ "valid_storage": {
229
+ "profile": "mkv/bool_ffv1/v1",
230
+ "codec": "ffv1",
231
+ "pixel_format": "gray",
232
+ "encoded_size": [640, 480],
233
+ "source_lossy": false,
234
+ "decoder": {"name": "ffmpeg", "version": "填写实际版本"},
235
+ "encoder_parameters": {"name": "ffv1", "version": "填写实际版本"}
236
+ },
237
+ "provenance": {"kind": "format_conversion", "method": "源深度转米制 z float32;逐位打包为 FFV1"},
238
+ "source_locator": {"file": "raw/data/depth.zip", "member": "depth/0001.png"}
239
+ }
240
+ ```
241
+
242
+ 深度和有效性视频都必须逐帧解码验收:float32 位串相同、bool 相同、T 相同,并检查 valid=true 的正有限值和 valid=false 的 NaN。读取器必须按 profile 还原,不能把 depth.mkv 的编码像素直接当深度值。
243
+
244
+ ## 4. camera 相机、帧索引与标定
245
+
246
+ ### 4.1 frames.jsonl:索引、时间与对应关系
247
+
248
+ `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` 或明确的源帧/时间映射表达,不能仅凭相同数组索引认定同步。
249
+
250
+ 每个视图必须提供此文件。源时间使用整数纳秒及 `clock_domain`,未知写 JSON `null`;不同时间域不能直接比较。逐帧 split 可以覆盖 metainfo 的视图默认划分,并保留来源,见 2.4。
251
+
252
+ ### 4.2 坐标系与标定通则
253
+
254
+ | 项目 | 统一约定 |
255
+ |---|---|
256
+ | 相机坐标 | 右手系,X 向右、Y 向下、Z 向前,长度单位米 |
257
+ | 齐次变换 | 列向量,`p_target = T_target_from_source @ p_source` |
258
+ | 图像坐标 | `(u,v)`;左上像素中心为 `(0,0)`,u 向右、v 向下,单位 pixel |
259
+ | 固定标定 | 本版展开为 T 份,同一 schema 不混用静态与动态形状 |
260
+ | 分辨率或模型变化 | 分开存储为视图/片段,不在同一组件中混装 |
261
+ | 未知标定 | 相机内外参允许缺省,不填单位阵冒充已知标定 |
262
+
263
+ ### 4.3 intrinsic.pt 与畸变参数
264
+
265
+ | model / schema_id | intrinsic.pt 的固定结构 |
266
+ |---|---|
267
+ | pinhole / camera/pinhole/v1 | `[T,3,3]`,标准 K,最后一行为 `[0,0,1]`;限无畸变或已校正图像 |
268
+ | fisheye624 / camera/fisheye624/v1 | `[T,15]`,`[f,cx,cy,k0,k1,k2,k3,k4,k5,p0,p1,s0,s1,s2,s3]`,采用 Project Aria Fisheye624 投影定义 |
269
+ | opencv_fisheye4 / camera/opencv_fisheye4/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件 `distortion_ref` 指向 `[T,4]`,顺序 `[k1,k2,k3,k4]`,使用 OpenCV fisheye 等距角度多项式;已由 ReInterHand 实际原始相机参数验证 |
270
+ | rational8 / camera/rational8/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件必需 `distortion_ref` 指向 `[T,8]`,顺序 `[k1,k2,p1,p2,k3,k4,k5,k6]` |
271
+ | unknown / null | 不提供可用 intrinsic,不声称可以投影 |
272
+
273
+ 有畸变的其他模型必须注册新 schema,固定参数名、顺序和投影公式;不能塞进针孔 K 后遗失畸变项。`metainfo.camera.schema_id` 必须与 intrinsic 组件一致。同一模型的别名不可隐式改变参数布局。
274
+
275
+ `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。
276
+
277
+ 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 保存。
278
+
279
+ 内参有效性为 `intrinsic_valid.pt [T] bool`;有畸变时使用对应 `distortion_ref`。同一模型的参数名和顺序固定。
280
+
281
+ ### 4.4 extrinsic.pt 与 extrinsic_valid.pt
282
+
283
+ `extrinsic.pt` 为 `[T,4,4]`,schema `transform/se3/v1`,方向固定 `T_camera_from_world`,有效性 `[T]`。世界坐标含义及源坐标转换记录在 provenance 中;只有相机坐标标注不要求虚构世界坐标。旋转块须正交且 determinant≈1。
284
+
285
+ ## 5. annotation 标注数据
286
+
287
+ ### 5.1 标注通则:手槽、valid 与 visibility
288
+
289
+ 手槽固定为 0=left、1=right,指解剖学左右,不按画面位置或可见性重排。本阶段只处理左右手两槽,不处理更多手。实体引用使用 `hand_left`、`hand_right`;手槽不证明跨采集片段的个人身份。
290
+
291
+ #### 5.1.1 valid:标注是否可用于监督
292
+
293
+ 标注的 `valid=true` 表示:有对应实际标注、通过本 schema 数值检查,且通过来源明确提供并适用于该组件的有效性/QA 条件。`valid=false` 可由缺标注、无法建立帧对应、源无效占位或官方 QA 不通过导致;不等于画面没有手或手不可见。各组件独立判断,MANO 按 `[T,2]` 标记左右手,关键点按 `[T,2,K]` 标记。
294
+
295
+ **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 有效监督。
296
+
297
+ 本地筛选须依据明确的规则,并在 `valid_policy.local_excluded_frame_indices`、排除原因和正式报告中记录。单个可疑投影作为问题记录,不直接硬编码排除该帧。已确认的曝光异常须明确作用范围,不能把一个序列的“前两帧有问题”套到所有序列。RGB 编码完好与几何监督可用是两件事,允许保留原图及帧索引而屏蔽对应标注;未发现问题不等于完成全部人工审核,试点待确认时不能作为已验收发布使用。
298
+
299
+ 源字段必须按官方语义映射,不能直接按名字复制:
300
+
301
+ | 来源 | 官方含义 | 映射原则 |
302
+ |---|---|---|
303
+ | [H2O](https://github.com/taeinkwon/h2odataset) 的手标注首位 | 0 未标注、1 已标注 | 可作为对应手标注存在性的依据,不推断未标注原因 |
304
+ | [HOT3D](https://github.com/facebookresearch/hot3d#using-mask-files) 的 pose_available、visible、mask_qa_pass | 分别表达姿态存在、可见性、对画面中可见手物位姿的人工 QA | 逐手/物体记录决定存在性,再 AND 当前相机当前帧 QA;QA 是整帧聚合判定,保守排除该帧全部手物几何监督,不声称每个实体均有错误;源可见性基于位姿推导时,其自身 valid 同样受 QA 约束 |
305
+ | [Dex-YCB](https://github.com/NVlabs/dex-ycb-toolkit#loading-dataset-and-visualizing-samples) 的全零 pose_m、全 -1 joints | 不可见的手或缺标注共用占位表示 | 对应组件 valid=false;不能从该值判定 visibility=false,也不能声称原因是动捕缺失 |
306
+ | [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 输入 |
307
+
308
+ 源 valid=false 若代表评估筛选或其他条件,应检查实际标注和源约定后映射;不能一律清空坐标。反之,占位零或 -1 只有在源官方明确规定时才判为缺失,不泛化成所有数据的判断规则。
309
+
310
+ `valid=true` 的标注应通过其 schema 的数值与形状检查;检查失败必须报告或修复,不能静默隐藏。QA 不通过应报告排除数量与原因,并保留可追溯信息;不能把这类无效称为缺标注。RGB、深度等观测有效性仍按各自 schema;手物 QA 不自动否定 RGB、静态相机内参或物体资产。相机外参是否过滤须依据其自身来源规则;HOT3D 本次保留源外参用于溯源和诊断,不能用其存在性证明 QA 失败帧的几何监督正确。
311
+
312
+ #### 5.1.2 visibility:可见性属性
313
+
314
+ 附加质量属性只保留 `visibility`,存放在对应模态或标注集内,不设 quality 目录。同一份可见性仅存一次;uv 与 xyz 共用时引用同一个文件。
315
+
316
+ 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,不与逐关键点可见性混用。
317
+
318
+ `valid` 回答“这项标注能否用于监督”,`visibility` 回答“在当前图像中是否可见(或可见多少)”。不可见的手或关键点仍可有有效标注;不能因 visibility=0 就清空坐标。源没有 visibility 时缺省或标为未知,不由 valid 推断。
319
+
320
+ | 情况 | 手标注 valid | visibility |
321
+ |---|---|---|
322
+ | RGB 已开始录制,动捕尚未开始,没有其他对应手标注 | false | 以独立源可见性标注为准;没有则未知 |
323
+ | 手被遮挡,但源有标注且通过适用有效性检查 | true | 若源声明不可见,则 false 或源可见比例 |
324
+ | 手可见且有对应标注,通过适用 QA | true | 若源有此信息,则 true 或源可见比例 |
325
+ | 手可见,但该帧漏标或动捕中断 | false | 可以为 true,但必须有独立来源依据 |
326
+ | 有手部参数,但官方 QA 明确不通过 | false | 不据此断言不可见;源可见比例若基于不可靠位姿,其属性 valid 也为 false |
327
+
328
+ visibility 自己的 valid_ref 表示该可见性标注是否可用,不复用 MANO 或关键点坐标的 valid_ref;明确记录源存在性及适用的 QA 条件。上述例子不要求凭图像自动生成可见性。
329
+
330
+ 不设 quality 组件或目录,不另存拟合误差、曝光、截断比例等通用质量数组。适用的官方 QA 合并进对应 valid,在 `valid_policy` 记录来源与规则;正式校验报告保留原始 QA 时间区间及排除统计。原始 QA 文件仍在 raw,官方 split 保留。
331
+
332
+ ### 5.2 mano:参数与整手可见性
333
+
334
+ 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。
335
+
336
+ `model_profile` 必须固定 MANO 版本、`flat_hand_mean=true`、左手 shapedirs 修正状态。平移表示模型输出顶点所加的全局平移,不是某个腕关节的坐标;源语义不同须转换。shape 无量纲。模型权重不作为共享数据附带上传。
337
+
338
+ `mano/visibility.pt [T,2]` 保存源整手可见比例时使用 float32 [0,1],`visibility_type=ratio`;只有实际采用 0–100 的百分比才除以100,不能只凭表头判断。HOT3D 的 `visibility_ratio[%]` 实值已经是0–1,官方读取器原样读取,必须保留原值。通过 MANO 组件 attributes 登记,使用独立有效性,不复用 motion_valid。
339
+
340
+ 手部共享表示仅保留 MANO 参数与选定关键点,不发布独立手表面几何。需要渲染或接触计算时由 MANO 参数生成,几何引用使用固定 MANO 模型配置与顶点顺序;不影响 object 下的物体模型和材质资产。
341
+
342
+ ### 5.3 keypoints:二维点、三维点与逐点可见性
343
+
344
+ 关键点独立于 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` 固定,不能在同一数组中逐帧变化;同体系统一顺序。数值使用像素坐标或米制相机系。
345
+
346
+ | keypoint_schema | K 与固定索引 |
347
+ |---|---|
348
+ | mano21/v1 | 21;wrist 后依次 thumb/index/middle/ring/little,每指由近端至指尖 |
349
+ | rhd21/v1 | 21;保持 wrist,然后五指由近端至指尖;原始每指 tip→palm 反序。只统一顺序,不宣称解剖学位置等价于 MANO |
350
+
351
+ 具体名称与源索引映射见 `schema.json`。当前只登记 MANO21 与 RHD21;不登记 MediaPipe、ReInterHand capture21 或 fit24 中间关键点。
352
+
353
+ 每个发布中的每个视图只提供一套标准手关键点,直接放在 keypoints 下,不设 annotation_set_id 字段或目录。uv 与 xyz 是这套关键点的二维与三维表示,不是两套标注。provenance 分别记录二者来自原始标注还是计算结果;不要求已有 2D 必须由当前 xyz 重新投影覆盖。
354
+
355
+ ReInterHand 的 Original keypoints、Original fits keypoints 及带前臂关键点不纳入 shared;如需手关键点,从选定 MANO 参数生成 MANO21 并记录模型/指尖回归约定。其他数据集默认使用选定的官方关键点,不额外生成平行的 MANO 派生集合。后续主动更换生成方法或结果时发布新的 dataset_version,不在同一版本内增设方法分支。
356
+
357
+ manual/projection/fitting 只记录在 provenance,不作为目录或类型分支。不得通过坐标为零、是否出画或 visibility 判断标注是否存在。派生标注仅在实际生成并通过数值检查后声明 valid=true;没有生成的项为 false,不伪造坐标。
358
+
359
+ `keypoints/visibility.pt [T,2,K]` 保存源逐点可见性,布尔表示使用 `visibility_type=boolean`。uv 与 xyz 共用时引用同一份文件。整手比例属性没有 MANO 可挂载时使用 `whole_hand_visibility.pt [T,2]`,`meaning=whole_hand`;它与逐点可见性分开,通用登记规则见 5.1。
360
+
361
+ 不使用 annotation_set_id;ReInterHand 中间关键点集合不进入 shared,raw 保留来源文件。
362
+
363
+ ### 5.4 object:身份、资产、位姿与几何
364
+
365
+ #### 5.4.1 metainfo.json:物体身份与跟踪作用域
366
+
367
+ 手用 `hand_left`、`hand_right` 及槽位 0、1 表示,不再另存 entities.json。物体身份登记在 `annotation/object/<object_id>/metainfo.json`,必填 `object_id`、`identity_scope`、`scope_id`、`source_locator`;可含 `category_id`、`source_object_id`、`mesh_ref`、`has_model`、部件引用。即使只有分割、没有 pose/mesh,也可只有这份物体元信息。
368
+
369
+ `identity_scope` 为 frame/subsequence/sequence,`scope_id` 指定具体作用域;跨相机共享身份只在已有源对应证据时使用。VISOR 按官方 subsequence 与实体名关联时记录 `association_basis=official_subsequence_entity_name`,不能声称这是全视频物理实例跟踪。无需与 object_id 一一对应的标准 track_id;官方独立轨迹标识存在时保留为 source_track_id,并声明作用域。手槽不证明跨采集片段的个人身份。
370
+
371
+ #### 5.4.2 assets:网格、材质与纹理
372
+
373
+ 资产属于物体,统一存放在 `annotation/object/<object_id>/` 内,可用 `assets/` 子目录组织网格、材质、纹理和部件资产。序列层不设共享 assets。所有引用采用视图根目录为基准;其中物体资产组件的 `data_ref` 与部件的 `mesh_ref` 采用相对于当前视图目录的 POSIX 路径,例如 `annotation/object/cup_01/assets/cup.obj`,且必须指向所属物体目录内的资产。OBJ 内部的材质、纹理引用遵循文件格式自身的相对路径规则,依赖文件一并保留。不同相机视图允许各自保存物体资产,不要求跨视图去重;下载物体时包含其资产依赖。
374
+
375
+ 网格 schema 为 `mesh/obj/v1`,顶点米制,静态有效性可直接声明标量 `valid`,或通过 `valid_ref` 指向标量 bool Tensor;不按 T 重复静态资产。由物体/部件通过引用关联,不仅凭文件名猜测。
376
+
377
+ #### 5.4.3 pose.pt、pose_valid.pt 与 visibility.pt
378
+
379
+ 刚体 schema 为 `object/rigid/v1`,`pose.pt [T,4,4]` 固定为 `T_camera_from_object`,平移米制,有效性 `[T]`。物体坐标原点、轴向必须与 mesh 一致;旋转块为正交矩阵且 determinant≈1。
380
+
381
+ `object/<id>/visibility.pt [T]` 保存源物体可见比例,float32 [0,1],`visibility_type=ratio`。通过所属物体组件 attributes 登记,独立表达其有效性。
382
+
383
+ #### 5.4.4 articulation.json、部件位姿与 joint_state.pt
384
+
385
+ 关节物体: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]`,不与父局部变换混装。
386
+
387
+ 若提供 `joint_state.pt [T,J]`,必须登记固定 joint_order、轴在父部件系的表达、零位变换与正方向,valid 为 `[T,J]`;缺少这些运动学定义时只发布部件位姿与已有来源信��,不伪造可驱动的关节模型。关节值与部件位姿同时存在时需验证一致性。
388
+
389
+ 部件层级应声明语义:纯语义包含树允许 `joints=[]`,不将包含关系推断为机械关节。关节状态 schema 为 `object/joint_state/v1`;转动用弧度、移动用米,混合类型按 joint_order 对应的关节定义解释。
390
+
391
+ #### 5.4.5 dimensions、几何关键点与顶点部件标签
392
+
393
+ `dimensions.pt [T,3]` 采用 `object/dimensions/v1`,有效性为 `[T]`。
394
+
395
+ 物体/部件 `dimensions` 为 `[length,width,height]` 米,轴顺序与该 mesh 的局部坐标关联,登记 `dimensions_semantics` 和来源。HOI4D dimensions 与 mesh 的具体尺度关系未验证前标为 source_unspecified,保留源值并暂停依赖该关系的几何验收,不能默认为待施加缩放。需要施加缩放时明确 scale_applied_to_mesh,禁止重复应用。
396
+
397
+ 源物体关键点放 `object/<id>/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。每个发布选择一套源几何点并记录选择,不另建方法分支。
398
+
399
+ `vertex_part_ids.pt [V] int64` 绑定 `mesh_ref` 与 topology_id,登记整数到 part_id 的映射;未知用 -1。ARCTIC 不同拓扑的资产分别绑定,不能共用未经转换的顶点标签。部件层级中 is_instance/has_model 等源属性保留,几何文件仍全部归 object。
400
+
401
+ ### 5.5 segment:分割类别、编码与覆盖范围
402
+
403
+ 每个发布选择一套任务使用的分割表示,不建立方法/标注集分支。没有分割就不创建 segment 目录,不为其他模态创建空的实体表。
404
+
405
+ | schema_id | 文件与数值语义 |
406
+ |---|---|
407
+ | segment/uint16_labels/v1 | mask.mkv;整数区域编号,通过 instances.jsonl 解释 |
408
+ | segment/instance_polygons/v1 | polygons.jsonl;实例多边形,可重叠;当前不支持孔洞拓扑 |
409
+ | segment/foreground_intensity/v1 | mask.mkv;0–255 前景强度,不是区域编号或经过校准的概率 |
410
+
411
+ #### 5.5.1 uint16 标签图与 instances.jsonl
412
+
413
+ 组件声明 `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。
414
+
415
+ `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 中每个非保留编码必须有且仅有一个映射。
416
+
417
+ FreiHAND 的试点按本任务需要,统一到手/背景类别,保留每个原生区域编码;不要求给原生细分区域猜测手指名称。需要细部件监督时,尚未核实的部件名称必须保持未知,不能因粗粒度手类别已核实便声称部件语义也已统一。
418
+
419
+ #### 5.5.2 重叠实例多边形
420
+
421
+ 每发布选择一套任务使用的分割表示,不建立方法/标注集分支。VISOR 的实际试点存在重叠实例多边形,单层标签图不能无损表达。对此补充 `segment/instance_polygons/v1`:`segment/polygons.jsonl` 每帧包含 `frame_index` 和 `instances`,每实例包含 `mask_value` 与 `polygons`(列表,每个多边形为源图像像素坐标顶点序列,保留原始精度)。身份和类别仍由同一 `instances.jsonl` 映射,有效性仍为 `[T]`,通过 schema 区分物理编码。允许多实例重叠,不采用后画覆盖前画。消费者按需栅格化为独立实例二值 mask;不能声称合并的单层 mask 无损。
422
+
423
+ #### 5.5.3 灰度前景强度
424
+
425
+ 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 的数值含义不同,不能将该文件按整数类别图解码。
426
+
427
+ FreiHAND 训练集的 JPEG mask 使用 `segment/foreground_intensity/v1`,逐像素保留 JPEG 解码后的灰度,`entity_id=hand_right`。该 schema 不限定双手合并:单手或合并范围由 `entity_id` 与 `coverage` 明确声明。评估集整数区域图仍用 `segment/uint16_labels/v1`,两者不能仅凭文件名使用同一种解码语义。
428
+
429
+ #### 5.5.4 coverage 与有效性
430
+
431
+ `coverage.kind=full/selected_entities/partial/unknown`。full 指声明的标注范围完整;selected_entities 还应列出目标范围。无论哪种,0 本身不自动成为背景;背景要有明确类别映射,未标注区域不能用于构造负样本。保留源逐类/逐实例 exhaustive 信息,未知不可改写为完整。
432
+
433
+ 三种表示的帧级有效性均为 `[T]`,表示该帧是否提供此分割标注;对应 valid_ref 在组件中登记,仍用小型 bool `.pt` 数组。栅格 mask 必须登记 storage,格式见 3.1.2,所有帧的整数编码或强度逐值完全相同。编码语义由 schema_id 决定,读取器不能仅依据 mask.mkv 文件名选择解码方式。
434
+
435
+ ### 5.6 contact:接触、抓取、区域与距离
436
+
437
+ #### 5.6.1 relations.jsonl 与 relations_valid.pt
438
+
439
+ `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。
440
+
441
+ 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 保存;不得当作逐顶点接触。
442
+
443
+ relations 组件的 valid_ref 指向 `relations_valid.pt [T] bool`,表示该帧是否有可用源关系标注。有效帧中可以存在 status=unknown 的明确不确定标注;无源标注的帧为 valid=false、relations=[]。组件仍声明 available/provenance/source_locator。
444
+
445
+ #### 5.6.2 实体对的顶点区域与距离
446
+
447
+ 已发布的接触区域/距离按参与关系的 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 后才可转换,不能随意栅格化宣称等价。
448
+
449
+ 顶点区域/距离已有存储定义,但尚未完成真实输入试点;接入时必须提供源语义与几何验收证据,不因已经登记 schema 就视为通过。
450
+
451
+ ## 附录:任务范围
452
+
453
+ 不强制收录 2D bbox、完整高频动捕、动作程序、身体 SMPL-X、点云或网络特征。范围内的接触、visibility、选定手关键点、物体几何不能因不便处理而静默丢弃。分割采用的物理编码由第 5.5 节决定,存在重叠时不能以单层标签图声称无损。
454
+
455
+ 不设置 entities_ref/segment/entities.json,不要求与 object_id 重复的 track_id。MediaPipe 不在当前关键点定义中;旧版本迁移必须保留可追溯关系,不能直接删表。手部共享表示不含独立 hand_mesh。
456
+
457
+ schema.json 是普通注册表,不是 JSON Schema 文档或可执行验收器;定义存在不代表真实数据已验证。验收须保留实测范围与未决项。
458
+
459
+ 本存储约定只更新标准,不代表既有 FFV1/depth.pt 试点已迁移。新发布必须显式写 storage 配置;旧产物按其旧定义读取,不能只改文件后缀或版本标识伪装为合规。
dex-ycb/shared-v1.0/doc/validation/KEYPOINT_PROJECTION_QC.json ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "scope": "Saved source 3D joints projected with saved color intrinsics vs saved source 2D joints; independent of hand mesh rendering.",
3
+ "views": [
4
+ {
5
+ "view": "data/20200709-subject-01_20200709_141754/836212060125",
6
+ "points": 1323,
7
+ "median_px": 0.0,
8
+ "p95_px": 3.4119690099032596e-05
9
+ },
10
+ {
11
+ "view": "data/20200813-subject-02_20200813_145341/836212060125",
12
+ "points": 1512,
13
+ "median_px": 7.62939453125e-06,
14
+ "p95_px": 3.1456798751605675e-05
15
+ },
16
+ {
17
+ "view": "data/20200820-subject-03_20200820_135250/836212060125",
18
+ "points": 1512,
19
+ "median_px": 0.0,
20
+ "p95_px": 3.4119690099032596e-05
21
+ },
22
+ {
23
+ "view": "data/20200903-subject-04_20200903_103554/836212060125",
24
+ "points": 1281,
25
+ "median_px": 0.0,
26
+ "p95_px": 3.4119690099032596e-05
27
+ },
28
+ {
29
+ "view": "data/20200908-subject-05_20200908_143301/836212060125",
30
+ "points": 1323,
31
+ "median_px": 0.0,
32
+ "p95_px": 4.31583721365314e-05
33
+ },
34
+ {
35
+ "view": "data/20200918-subject-06_20200918_112947/836212060125",
36
+ "points": 861,
37
+ "median_px": 0.0,
38
+ "p95_px": 3.4119690099032596e-05
39
+ },
40
+ {
41
+ "view": "data/20200928-subject-07_20200928_143249/836212060125",
42
+ "points": 1407,
43
+ "median_px": 1.52587890625e-05,
44
+ "p95_px": 4.31583721365314e-05
45
+ },
46
+ {
47
+ "view": "data/20201002-subject-08_20201002_104620/836212060125",
48
+ "points": 1323,
49
+ "median_px": 7.62939453125e-06,
50
+ "p95_px": 4.31583721365314e-05
51
+ },
52
+ {
53
+ "view": "data/20201015-subject-09_20201015_142601/836212060125",
54
+ "points": 1554,
55
+ "median_px": 0.0,
56
+ "p95_px": 3.4119690099032596e-05
57
+ },
58
+ {
59
+ "view": "data/20201015-subject-09_20201015_142601/932122062010",
60
+ "points": 1554,
61
+ "median_px": 0.0,
62
+ "p95_px": 3.4119690099032596e-05
63
+ },
64
+ {
65
+ "view": "data/20201022-subject-10_20201022_110806/836212060125",
66
+ "points": 1512,
67
+ "median_px": 0.0,
68
+ "p95_px": 3.1456798751605675e-05
69
+ },
70
+ {
71
+ "view": "data/20201015-subject-09_20201015_150838/836212060125",
72
+ "points": 1554,
73
+ "median_px": 0.0,
74
+ "p95_px": 4.31583721365314e-05
75
+ }
76
+ ]
77
+ }
dex-ycb/shared-v1.0/doc/validation/SOURCE_FRAME_COVERAGE.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "views": 8000,
3
+ "frames": 581968,
4
+ "missing_frames": {
5
+ "color": 0,
6
+ "aligned_depth_to_color": 0,
7
+ "labels": 0
8
+ },
9
+ "affected_views": {
10
+ "color": 0,
11
+ "aligned_depth_to_color": 0,
12
+ "labels": 0
13
+ },
14
+ "first_20_affected_views": [],
15
+ "scope": "Count source locator presence and frame index in saved frames.jsonl, not direct reread of source tar or decoded-media QC."
16
+ }
dex-ycb/shared-v1.0/doc/validation/SOURCE_FRAME_COVERAGE.log ADDED
@@ -0,0 +1 @@
 
 
1
+ {"views": 8000, "frames": 581968, "missing_frames": {"color": 0, "aligned_depth_to_color": 0, "labels": 0}, "affected_views": {"color": 0, "aligned_depth_to_color": 0, "labels": 0}, "first_20_affected_views": [], "scope": "Count source locator presence and frame index in saved frames.jsonl, not direct reread of source tar or decoded-media QC."}
dex-ycb/shared-v1.0/doc/validation/SOURCE_FRAME_COVERAGE.status ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ START=2026-09-29T10:12:56+08:00
2
+ EXIT=0 END=2026-09-29T10:17:01+08:00
dex-ycb/shared-v1.0/doc/validation/STRUCTURAL_AUDIT.json ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sequences": 1000,
3
+ "views": 8000,
4
+ "subjects": {
5
+ "20200709-subject-01": 100,
6
+ "20200813-subject-02": 100,
7
+ "20200820-subject-03": 100,
8
+ "20200903-subject-04": 100,
9
+ "20200908-subject-05": 100,
10
+ "20200918-subject-06": 100,
11
+ "20200928-subject-07": 100,
12
+ "20201002-subject-08": 100,
13
+ "20201015-subject-09": 100,
14
+ "20201022-subject-10": 100
15
+ },
16
+ "splits": {
17
+ "train": 5600,
18
+ "val": 800,
19
+ "test": 1600
20
+ },
21
+ "available_views": {
22
+ "rgb": 8000,
23
+ "intrinsic": 8000,
24
+ "extrinsic": 8000,
25
+ "mano": 8000,
26
+ "keypoints_uv": 8000,
27
+ "keypoints_xyz": 8000,
28
+ "pose_ycb_01": 1736,
29
+ "mesh_ycb_01": 1736,
30
+ "pose_ycb_05": 1424,
31
+ "mesh_ycb_05": 1424,
32
+ "pose_ycb_06": 1640,
33
+ "mesh_ycb_06": 1640,
34
+ "pose_ycb_15": 1552,
35
+ "mesh_ycb_15": 1552,
36
+ "segment": 8000,
37
+ "depth": 8000,
38
+ "relations": 8000,
39
+ "pose_ycb_11": 1448,
40
+ "mesh_ycb_11": 1448,
41
+ "pose_ycb_12": 1584,
42
+ "mesh_ycb_12": 1584,
43
+ "pose_ycb_20": 1784,
44
+ "mesh_ycb_20": 1784,
45
+ "pose_ycb_02": 1672,
46
+ "mesh_ycb_02": 1672,
47
+ "pose_ycb_14": 1560,
48
+ "mesh_ycb_14": 1560,
49
+ "pose_ycb_21": 1464,
50
+ "mesh_ycb_21": 1464,
51
+ "pose_ycb_16": 1464,
52
+ "mesh_ycb_16": 1464,
53
+ "pose_ycb_04": 1720,
54
+ "mesh_ycb_04": 1720,
55
+ "pose_ycb_08": 1616,
56
+ "mesh_ycb_08": 1616,
57
+ "pose_ycb_09": 1568,
58
+ "mesh_ycb_09": 1568,
59
+ "pose_ycb_18": 1776,
60
+ "mesh_ycb_18": 1776,
61
+ "pose_ycb_03": 1408,
62
+ "mesh_ycb_03": 1408,
63
+ "pose_ycb_17": 1576,
64
+ "mesh_ycb_17": 1576,
65
+ "pose_ycb_07": 1504,
66
+ "mesh_ycb_07": 1504,
67
+ "pose_ycb_13": 1672,
68
+ "mesh_ycb_13": 1672,
69
+ "pose_ycb_10": 1688,
70
+ "mesh_ycb_10": 1688
71
+ },
72
+ "config": {
73
+ "root": "/data0/xuzhefeng/Datasets/dex-ycb",
74
+ "out": "/data0/xuzhefeng/Datasets/uni-hoi-dataset",
75
+ "release_id": "shared-v1.0",
76
+ "limit": null,
77
+ "max_frames": null,
78
+ "mano_dir": "/data0/xuzhefeng/Datasets/mano",
79
+ "views": null,
80
+ "jpeg_full_check": false,
81
+ "subjects": null
82
+ },
83
+ "published_script_sha256": {
84
+ "render_dexycb_validation.py": "a0a74847a42e98202462a46edfc278c9422b4e05539414d52bc32bfd1690bf2a",
85
+ "warehouse_v1_0.py": "6bdc15c3f88a9eb9c460a2569bca65f8767b42ed44eba78518fdbdb5b021d553",
86
+ "convert_visor_v1.0.py": "e011c184261359364ad507484373bfc1a1a58387c4c2140ee97b523cab3a6879",
87
+ "render_hoi4d_validation.py": "c02d04cea14a22fec176be45753b9920f493e96ae7b43cd85e3d393a2d7b0971",
88
+ "convert_h2o_v1.0.py": "c434436efd6fdb7cd383322224f5cc5bb8cc59294f97c5668e0f787d734de75e",
89
+ "check_dexycb_projection.py": "0d16e58789ae1a0cb54c7d4c7729079b98173857a83ba25a0adc78310120611e",
90
+ "convert_hoi4d_v1.0.py": "a751aa6a074c97578e11bc9b42052fe8dbb7075f122e8c2c7c04100445ad0bc5",
91
+ "convert_dexycb_v1.0.py": "a766b9b482e0bdf1025e3ce36987df45ef1b0558bcd1ece1b79c122aed5a4e8f"
92
+ },
93
+ "sampled_views": [
94
+ "data/20200709-subject-01_20200709_141754/836212060125",
95
+ "data/20200813-subject-02_20200813_145341/836212060125",
96
+ "data/20200820-subject-03_20200820_135250/836212060125",
97
+ "data/20200903-subject-04_20200903_103554/836212060125",
98
+ "data/20200908-subject-05_20200908_143301/836212060125",
99
+ "data/20200918-subject-06_20200918_112947/836212060125",
100
+ "data/20200928-subject-07_20200928_143249/836212060125",
101
+ "data/20201002-subject-08_20201002_104620/836212060125",
102
+ "data/20201015-subject-09_20201015_142601/836212060125",
103
+ "data/20201015-subject-09_20201015_142601/932122062010",
104
+ "data/20201015-subject-09_20201015_150838/836212060125",
105
+ "data/20201022-subject-10_20201022_110806/836212060125"
106
+ ],
107
+ "scope": "Structure and file refs checked for all views; persisted QC and HTML only for sampled views. No manual visual approval yet."
108
+ }
dex-ycb/shared-v1.0/doc/validation/colorfix-run.log ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20200709-subject-01_20200709_141754_836212060125.html selected_frames [0, 9, 18, 36, 54, 71]
2
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20200813-subject-02_20200813_145341_836212060125.html selected_frames [0, 18, 36, 54, 71]
3
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20200820-subject-03_20200820_135250_836212060125.html selected_frames [0, 18, 36, 54, 71]
4
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20200903-subject-04_20200903_103554_836212060125.html selected_frames [0, 13, 18, 37, 55, 73]
5
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20200908-subject-05_20200908_143301_836212060125.html selected_frames [0, 9, 18, 36, 54, 71]
6
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20200918-subject-06_20200918_112947_836212060125.html selected_frames [0, 18, 31, 36, 54, 71]
7
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20200928-subject-07_20200928_143249_836212060125.html selected_frames [0, 7, 18, 37, 55, 73]
8
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20201002-subject-08_20201002_104620_836212060125.html selected_frames [0, 11, 18, 37, 55, 73]
9
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20201015-subject-09_20201015_142601_836212060125.html selected_frames [0, 18, 37, 55, 73]
10
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20201015-subject-09_20201015_142601_932122062010.html selected_frames [0, 18, 37, 55, 73]
11
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20201015-subject-09_20201015_150838_836212060125.html selected_frames [0, 18, 37, 55, 73]
12
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20201022-subject-10_20201022_110806_836212060125.html selected_frames [0, 18, 36, 54, 71]
13
+ {"sequences": 1000, "views": 8000, "subjects": {"20200709-subject-01": 100, "20200813-subject-02": 100, "20200820-subject-03": 100, "20200903-subject-04": 100, "20200908-subject-05": 100, "20200918-subject-06": 100, "20200928-subject-07": 100, "20201002-subject-08": 100, "20201015-subject-09": 100, "20201022-subject-10": 100}, "splits": {"train": 5600, "val": 800, "test": 1600}, "available_views": {"rgb": 8000, "intrinsic": 8000, "extrinsic": 8000, "mano": 8000, "keypoints_uv": 8000, "keypoints_xyz": 8000, "pose_ycb_01": 1736, "mesh_ycb_01": 1736, "pose_ycb_05": 1424, "mesh_ycb_05": 1424, "pose_ycb_06": 1640, "mesh_ycb_06": 1640, "pose_ycb_15": 1552, "mesh_ycb_15": 1552, "segment": 8000, "depth": 8000, "relations": 8000, "pose_ycb_11": 1448, "mesh_ycb_11": 1448, "pose_ycb_12": 1584, "mesh_ycb_12": 1584, "pose_ycb_20": 1784, "mesh_ycb_20": 1784, "pose_ycb_02": 1672, "mesh_ycb_02": 1672, "pose_ycb_14": 1560, "mesh_ycb_14": 1560, "pose_ycb_21": 1464, "mesh_ycb_21": 1464, "pose_ycb_16": 1464, "mesh_ycb_16": 1464, "pose_ycb_04": 1720, "mesh_ycb_04": 1720, "pose_ycb_08": 1616, "mesh_ycb_08": 1616, "pose_ycb_09": 1568, "mesh_ycb_09": 1568, "pose_ycb_18": 1776, "mesh_ycb_18": 1776, "pose_ycb_03": 1408, "mesh_ycb_03": 1408, "pose_ycb_17": 1576, "mesh_ycb_17": 1576, "pose_ycb_07": 1504, "mesh_ycb_07": 1504, "pose_ycb_13": 1672, "mesh_ycb_13": 1672, "pose_ycb_10": 1688, "mesh_ycb_10": 1688}, "config": {"root": "/data0/xuzhefeng/Datasets/dex-ycb", "out": "/data0/xuzhefeng/Datasets/uni-hoi-dataset", "release_id": "shared-v1.0", "limit": null, "max_frames": null, "mano_dir": "/data0/xuzhefeng/Datasets/mano", "views": null, "jpeg_full_check": false, "subjects": null}, "published_script_sha256": {"render_dexycb_validation.py": "a0a74847a42e98202462a46edfc278c9422b4e05539414d52bc32bfd1690bf2a", "warehouse_v1_0.py": "6bdc15c3f88a9eb9c460a2569bca65f8767b42ed44eba78518fdbdb5b021d553", "convert_visor_v1.0.py": "e011c184261359364ad507484373bfc1a1a58387c4c2140ee97b523cab3a6879", "render_hoi4d_validation.py": "c02d04cea14a22fec176be45753b9920f493e96ae7b43cd85e3d393a2d7b0971", "convert_h2o_v1.0.py": "c434436efd6fdb7cd383322224f5cc5bb8cc59294f97c5668e0f787d734de75e", "check_dexycb_projection.py": "0d16e58789ae1a0cb54c7d4c7729079b98173857a83ba25a0adc78310120611e", "convert_hoi4d_v1.0.py": "a751aa6a074c97578e11bc9b42052fe8dbb7075f122e8c2c7c04100445ad0bc5", "convert_dexycb_v1.0.py": "a766b9b482e0bdf1025e3ce36987df45ef1b0558bcd1ece1b79c122aed5a4e8f"}, "sampled_views": ["data/20200709-subject-01_20200709_141754/836212060125", "data/20200813-subject-02_20200813_145341/836212060125", "data/20200820-subject-03_20200820_135250/836212060125", "data/20200903-subject-04_20200903_103554/836212060125", "data/20200908-subject-05_20200908_143301/836212060125", "data/20200918-subject-06_20200918_112947/836212060125", "data/20200928-subject-07_20200928_143249/836212060125", "data/20201002-subject-08_20201002_104620/836212060125", "data/20201015-subject-09_20201015_142601/836212060125", "data/20201015-subject-09_20201015_142601/932122062010", "data/20201015-subject-09_20201015_150838/836212060125", "data/20201022-subject-10_20201022_110806/836212060125"], "scope": "Structure and file refs checked for all views; persisted QC and HTML only for sampled views. No manual visual approval yet."}
dex-ycb/shared-v1.0/doc/validation/colorfix-run.status ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ START=2026-09-28T21:32:25+08:00
2
+ EXIT=0 END=2026-09-28T21:45:14+08:00
dex-ycb/shared-v1.0/doc/validation/index.html ADDED
@@ -0,0 +1 @@
 
 
1
+ <!doctype html><html lang="zh"><meta charset="utf-8"><title>dex-ycb review</title><h1>dex-ycb 抽样人工审核</h1><p>选择视图;所有预览均来自已保存的 shared 数据。</p><ul><li><a href="20200709-subject-01_20200709_141754_836212060125.html">20200709-subject-01_20200709_141754_836212060125.html</a></li><li><a href="20200813-subject-02_20200813_145341_836212060125.html">20200813-subject-02_20200813_145341_836212060125.html</a></li><li><a href="20200820-subject-03_20200820_135250_836212060125.html">20200820-subject-03_20200820_135250_836212060125.html</a></li><li><a href="20200903-subject-04_20200903_103554_836212060125.html">20200903-subject-04_20200903_103554_836212060125.html</a></li><li><a href="20200908-subject-05_20200908_143301_836212060125.html">20200908-subject-05_20200908_143301_836212060125.html</a></li><li><a href="20200918-subject-06_20200918_112947_836212060125.html">20200918-subject-06_20200918_112947_836212060125.html</a></li><li><a href="20200928-subject-07_20200928_143249_836212060125.html">20200928-subject-07_20200928_143249_836212060125.html</a></li><li><a href="20201002-subject-08_20201002_104620_836212060125.html">20201002-subject-08_20201002_104620_836212060125.html</a></li><li><a href="20201015-subject-09_20201015_142601_836212060125.html">20201015-subject-09_20201015_142601_836212060125.html</a></li><li><a href="20201015-subject-09_20201015_142601_932122062010.html">20201015-subject-09_20201015_142601_932122062010.html</a></li><li><a href="20201015-subject-09_20201015_150838_836212060125.html">20201015-subject-09_20201015_150838_836212060125.html</a></li><li><a href="20201022-subject-10_20201022_110806_836212060125.html">20201022-subject-10_20201022_110806_836212060125.html</a></li></ul></html>
dex-ycb/shared-v1.0/doc/validation/render_dexycb_validation.before-color-fix.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Audit a finished Dex-YCB release and render persisted modalities for manual review."""
3
+ from collections import Counter
4
+ import hashlib
5
+ import json
6
+ from pathlib import Path
7
+ import sys
8
+
9
+ from render_hoi4d_validation import render
10
+
11
+
12
+ def inspect(root):
13
+ data, doc, scripts = root / 'data', root / 'doc', root / 'script'
14
+ sequences = sorted(p for p in data.iterdir() if p.is_dir())
15
+ assert len(sequences) == 1000, f'expected 1000 sequences, got {len(sequences)}'
16
+ assert len(list(doc.glob('*.build.json'))) == 1000
17
+ assert not list(data.glob('*.tmp-*')), 'unfinished temporary sequences'
18
+ config = json.loads((scripts / 'config.json').read_text())
19
+ assert all(config.get(k) is None for k in ('limit', 'max_frames', 'subjects', 'views'))
20
+ hashes = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in scripts.glob('*.py')}
21
+ subjects, splits, availability = Counter(), Counter(), Counter()
22
+ selected = []
23
+ for seq in sequences:
24
+ views = sorted(p for p in seq.iterdir() if p.is_dir())
25
+ assert len(views) == 8, (seq, len(views))
26
+ build = json.loads((doc / (seq.name + '.build.json')).read_text())
27
+ assert set(build['views']) == {p.name for p in views}, seq
28
+ assert all(hashes.get(k) == v for k, v in build['scripts'].items()), seq
29
+ subject = seq.name.split('_')[0]
30
+ subjects[subject] += 1
31
+ if subjects[subject] == 1:
32
+ selected.append(views[0])
33
+ if subject.endswith('subject-09'):
34
+ selected.append(views[-1]) # one more camera, including left-hand subject
35
+ for view in views:
36
+ meta = json.loads((view / 'metainfo.json').read_text())
37
+ assert meta['sequence_id'] == seq.name and meta['camera_id'] == view.name, view
38
+ assert meta['dataset_id'] == 'dex-ycb' and meta['release_id'] == 'shared-v1.0', view
39
+ assert meta['num_frames'] > 0 and meta.get('view_type') == 'exo', view
40
+ assert (view / 'camera/frames.jsonl').is_file(), view
41
+ assert meta['components']['rgb']['available'], view
42
+ splits[meta['split']] += 1
43
+ for key, part in meta['components'].items():
44
+ if part.get('available'):
45
+ availability[key] += 1
46
+ for ref in ('data_ref', 'valid_ref'):
47
+ if part.get(ref):
48
+ assert (view / part[ref]).is_file(), (view, key, ref)
49
+ assert len(subjects) == 10 and set(subjects.values()) == {100}, subjects
50
+ assert availability['depth'] == availability['rgb'] == 8000, availability
51
+ report = dict(sequences=len(sequences), views=sum(splits.values()), subjects=dict(subjects),
52
+ splits=dict(splits), available_views=dict(availability), config=config,
53
+ published_script_sha256=hashes, sampled_views=[str(v.relative_to(root)) for v in selected],
54
+ scope='Structure and file refs checked for all views; persisted QC and HTML only for sampled views. No manual visual approval yet.')
55
+ destination = doc / 'validation'
56
+ destination.mkdir(exist_ok=True)
57
+ (destination / 'STRUCTURAL_AUDIT.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
58
+ for view in selected:
59
+ render(view, destination)
60
+ return report
61
+
62
+
63
+ if __name__ == '__main__':
64
+ print(json.dumps(inspect(Path(sys.argv[1]).expanduser().resolve()), ensure_ascii=False), flush=True)
dex-ycb/shared-v1.0/doc/validation/render_hoi4d_validation.before-color-fix.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Standalone, offline HTML review of every persisted component in selected views."""
3
+ import argparse
4
+ import base64
5
+ import html
6
+ import io
7
+ import json
8
+ import random
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ from PIL import Image, ImageDraw
13
+ import torch
14
+
15
+ from warehouse_v1_0 import video_frames, unpack_depth, validate_view
16
+
17
+
18
+ def snapshot(video, fmt, shape, dtype, indices):
19
+ return {i: frame.copy() for i, frame in enumerate(video_frames(video, fmt, shape, dtype)) if i in indices}
20
+
21
+
22
+ def picture(image):
23
+ image.thumbnail((800, 450)) # Previews only; released tensors and videos are not resized.
24
+ output = io.BytesIO()
25
+ image.save(output, format='PNG')
26
+ return '<img loading="lazy" src="data:image/png;base64,' + base64.b64encode(output.getvalue()).decode() + '">'
27
+
28
+
29
+ def mesh_preview(path):
30
+ """Project the whole source asset; bound drawing cost without favoring early faces."""
31
+ vertices, faces, referenced = [], [], set()
32
+ rng = random.Random(0)
33
+ face_count = 0
34
+ with path.open(errors='replace') as stream:
35
+ for line in stream:
36
+ if line.startswith('v '):
37
+ vertices.append([float(v) for v in line.split()[1:4]])
38
+ elif line.startswith('f '):
39
+ face = []
40
+ for token in line.split()[1:]:
41
+ index = int(token.split('/')[0])
42
+ face.append(index - 1 if index > 0 else len(vertices) + index)
43
+ if len(face) < 3:
44
+ continue
45
+ referenced.update(face)
46
+ face_count += 1
47
+ # ponytail: bounded static preview; use a full OBJ viewer if 5000 faces miss fine detail.
48
+ if len(faces) < 5000:
49
+ faces.append(face)
50
+ else:
51
+ pick = rng.randrange(face_count)
52
+ if pick < len(faces):
53
+ faces[pick] = face
54
+ if not vertices or not faces:
55
+ return 'OBJ 未提供可绘制的顶点/面'
56
+ if min(referenced) < 0 or max(referenced) >= len(vertices):
57
+ raise ValueError(f'invalid OBJ face index: {path}')
58
+ xyz = np.asarray(vertices, dtype=np.float64)
59
+ if not np.isfinite(xyz).all():
60
+ raise ValueError(f'nonfinite OBJ vertex: {path}')
61
+ # Fixed orthonormal isometric basis: geometry only, not an inferred camera pose.
62
+ projected = np.column_stack(((xyz[:, 0] - xyz[:, 2]) / np.sqrt(2),
63
+ (xyz[:, 0] + xyz[:, 2] - 2 * xyz[:, 1]) / np.sqrt(6)))
64
+ used = projected[np.fromiter(referenced, dtype=np.int64)]
65
+ lo, hi = used.min(axis=0), used.max(axis=0)
66
+ extent = (hi - lo).max()
67
+ if extent <= 0:
68
+ return 'OBJ 所有面投影到同一点'
69
+ projected = (projected - (lo + hi) / 2) * (380 / extent) + 215
70
+ image = Image.new('RGB', (430, 430), 'white')
71
+ draw = ImageDraw.Draw(image)
72
+ for face in faces:
73
+ polygon = [tuple(projected[i]) for i in face]
74
+ draw.line(polygon + [polygon[0]], fill='#205caa', width=1)
75
+ return picture(image)
76
+
77
+
78
+ def render(view, destination):
79
+ meta = json.loads((view / 'metainfo.json').read_text())
80
+ n = meta['num_frames']
81
+ width, height = meta['camera']['image_size']
82
+ components = meta['components']
83
+ frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()]
84
+ assert len(frames) == n
85
+ selected = {0, n // 4, n // 2, 3 * n // 4, n - 1}
86
+ for item in components.values():
87
+ ref = item.get('valid_ref', '')
88
+ if ref.endswith('.pt'):
89
+ valid = torch.load(view / ref, map_location='cpu', weights_only=True).numpy()
90
+ if valid.shape[0] == n:
91
+ matching = np.flatnonzero(valid.reshape(n, -1).any(axis=1))
92
+ if len(matching):
93
+ selected.add(int(matching[0]))
94
+ selected = set(sorted(selected)[:12]) | {n - 1}
95
+ rgb = snapshot(view / components['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected)
96
+ depth = (snapshot(view / components['depth']['data_ref'], 'gray16le', (height, 2 * width), '<u2', selected)
97
+ if components.get('depth', {}).get('available') else {})
98
+ masks = (snapshot(view / components['segment']['data_ref'], 'gray16le', (height, width), '<u2', selected)
99
+ if components.get('segment', {}).get('available') else {})
100
+ labels = {}
101
+ mapping = view / 'annotation/segment/instances.jsonl'
102
+ if mapping.exists():
103
+ labels = {row['frame_index']: row['labels'] for row in map(json.loads, mapping.read_text().splitlines()) if row['frame_index'] in selected}
104
+ uv = components.get('keypoints_uv', {})
105
+ uv_points = torch.load(view / uv['data_ref'], map_location='cpu', weights_only=True).numpy() if uv.get('available') else None
106
+ uv_valid = torch.load(view / uv['valid_ref'], map_location='cpu', weights_only=True).numpy() if uv.get('available') else None
107
+ sections = []
108
+ for i in sorted(selected):
109
+ image = Image.fromarray(rgb[i])
110
+ if uv_points is not None:
111
+ draw = ImageDraw.Draw(image)
112
+ for slot, color in enumerate(('#00ffff', '#ff9922')):
113
+ for (x, y), valid in zip(uv_points[i, slot], uv_valid[i, slot], strict=True):
114
+ if valid and np.isfinite([x, y]).all():
115
+ draw.ellipse((x - 3, y - 3, x + 3, y + 3), fill=color)
116
+ panels = ['<figure>' + picture(image) + '<figcaption>RGB + 原生 2D 手关键点(若有)</figcaption></figure>']
117
+ if i in depth:
118
+ z = unpack_depth(depth[i])
119
+ luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8)
120
+ panels.append('<figure>' + picture(Image.fromarray(luminance)) + '<figcaption>深度 Z(黑=无效,白≥3 m;仅预览)</figcaption></figure>')
121
+ if i in masks:
122
+ mask = masks[i]
123
+ colors = np.zeros((*mask.shape, 3), dtype=np.uint8)
124
+ for value in np.unique(mask):
125
+ if value not in (0, 65535):
126
+ colors[mask == value] = ((int(value) * 89) % 240 + 15, (int(value) * 61) % 240 + 15, (int(value) * 131) % 240 + 15)
127
+ panels.append('<figure>' + picture(Image.fromarray(colors)) + '<figcaption>原生分割整数编码的伪彩色预览</figcaption></figure>')
128
+ active = (mask != 0) & (mask != 65535)
129
+ overlay = rgb[i].copy()
130
+ overlay[active] = ((overlay[active].astype(np.uint16) + colors[active]) // 2).astype(np.uint8)
131
+ panels.append('<figure>' + picture(Image.fromarray(overlay)) + '<figcaption>原生分割叠加 RGB(仅预览)</figcaption></figure>')
132
+ details = {'frame': frames[i], 'segment_labels': labels.get(i, [])}
133
+ for name, component in components.items():
134
+ ref = component.get('data_ref', '')
135
+ if component.get('available') and ref.endswith('.pt'):
136
+ values = torch.load(view / ref, map_location='cpu', weights_only=True)
137
+ if values.ndim and values.shape[0] == n:
138
+ details[name] = {'value': values[i].tolist()}
139
+ if component.get('valid_ref', '').endswith('.pt'):
140
+ valid = torch.load(view / component['valid_ref'], map_location='cpu', weights_only=True)
141
+ details[name]['valid'] = valid[i].tolist()
142
+ sections.append('<section><h2>帧 ' + str(i) + ' / ' + str(n) + '</h2><div class="panels">' + ''.join(panels)
143
+ + '</div><details><summary>帧号、来源、全部数值组件与有效性</summary><pre>'
144
+ + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '</pre></details></section>')
145
+ assets = []
146
+ for name, component in components.items():
147
+ if component.get('available') and component['data_ref'].lower().endswith('.obj'):
148
+ ref = component['data_ref']
149
+ assets.append('<figure><h3>' + html.escape(name) + '</h3>' + mesh_preview(view / ref)
150
+ + '<figcaption>仅展示网格原生形状;未验证尺度/位姿对应。</figcaption></figure>')
151
+ result = validate_view(view)
152
+ destination.mkdir(parents=True, exist_ok=True)
153
+ title = view.parent.name + '_' + view.name
154
+ 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}'
155
+ page = '<!doctype html><html lang="zh"><meta charset="utf-8"><title>' + html.escape(title) + '</title><style>' + css + '</style><h1>' + html.escape(title) + '</h1><p>预览图仅供人工审核,不是训练输入;未提供的模态在 metainfo 中保留原因。</p>' + ''.join(sections) + '<h2>原始物体模型(独立预览)</h2><div class="panels">' + ''.join(assets) + '</div><details><summary>全部组件元信息及原始来源</summary><pre>' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '</pre></details><details><summary>持久化 QC 结果</summary><pre>' + html.escape(json.dumps(result, ensure_ascii=False, indent=2)) + '</pre></details></html>'
156
+ (destination / (title + '.html')).write_text(page)
157
+ (destination / (title + '.report.json')).write_text(json.dumps(result, ensure_ascii=False, indent=2))
158
+ links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html')
159
+ (destination / 'index.html').write_text('<!doctype html><html lang="zh"><meta charset="utf-8"><title>' + html.escape(meta['dataset_id']) + ' review</title><h1>' + html.escape(meta['dataset_id']) + ' 抽样人工审核</h1><p>选择视图;所有预览均来自已保存的 shared 数据。</p><ul>' + ''.join('<li><a href="' + html.escape(x, quote=True) + '">' + html.escape(x) + '</a></li>' for x in links) + '</ul></html>')
160
+ print(destination / (title + '.html'), 'selected_frames', sorted(selected), flush=True)
161
+
162
+
163
+ def main():
164
+ p = argparse.ArgumentParser(description=__doc__)
165
+ p.add_argument('views', nargs='+', type=Path)
166
+ p.add_argument('--out', type=Path)
167
+ args = p.parse_args()
168
+ for view in args.views:
169
+ render(view, args.out or view.parents[2] / 'doc/validation')
170
+
171
+
172
+ if __name__ == '__main__':
173
+ main()
dex-ycb/shared-v1.0/doc/validation/validation-run.log ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20200709-subject-01_20200709_141754_836212060125.html selected_frames [0, 9, 18, 36, 54, 71]
2
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20200813-subject-02_20200813_145341_836212060125.html selected_frames [0, 18, 36, 54, 71]
3
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20200820-subject-03_20200820_135250_836212060125.html selected_frames [0, 18, 36, 54, 71]
4
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20200903-subject-04_20200903_103554_836212060125.html selected_frames [0, 13, 18, 37, 55, 73]
5
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20200908-subject-05_20200908_143301_836212060125.html selected_frames [0, 9, 18, 36, 54, 71]
6
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20200918-subject-06_20200918_112947_836212060125.html selected_frames [0, 18, 31, 36, 54, 71]
7
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20200928-subject-07_20200928_143249_836212060125.html selected_frames [0, 7, 18, 37, 55, 73]
8
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20201002-subject-08_20201002_104620_836212060125.html selected_frames [0, 11, 18, 37, 55, 73]
9
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20201015-subject-09_20201015_142601_836212060125.html selected_frames [0, 18, 37, 55, 73]
10
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20201015-subject-09_20201015_142601_932122062010.html selected_frames [0, 18, 37, 55, 73]
11
+ /data0/xuzhefeng/Datasets/uni-hoi-dataset/dex-ycb/shared-v1.0/doc/validation/20201022-subject-10_20201022_110806_836212060125.html selected_frames [0, 18, 36, 54, 71]
12
+ {"sequences": 1000, "views": 8000, "subjects": {"20200709-subject-01": 100, "20200813-subject-02": 100, "20200820-subject-03": 100, "20200903-subject-04": 100, "20200908-subject-05": 100, "20200918-subject-06": 100, "20200928-subject-07": 100, "20201002-subject-08": 100, "20201015-subject-09": 100, "20201022-subject-10": 100}, "splits": {"train": 5600, "val": 800, "test": 1600}, "available_views": {"rgb": 8000, "intrinsic": 8000, "extrinsic": 8000, "mano": 8000, "keypoints_uv": 8000, "keypoints_xyz": 8000, "pose_ycb_01": 1736, "mesh_ycb_01": 1736, "pose_ycb_05": 1424, "mesh_ycb_05": 1424, "pose_ycb_06": 1640, "mesh_ycb_06": 1640, "pose_ycb_15": 1552, "mesh_ycb_15": 1552, "segment": 8000, "depth": 8000, "relations": 8000, "pose_ycb_11": 1448, "mesh_ycb_11": 1448, "pose_ycb_12": 1584, "mesh_ycb_12": 1584, "pose_ycb_20": 1784, "mesh_ycb_20": 1784, "pose_ycb_02": 1672, "mesh_ycb_02": 1672, "pose_ycb_14": 1560, "mesh_ycb_14": 1560, "pose_ycb_21": 1464, "mesh_ycb_21": 1464, "pose_ycb_16": 1464, "mesh_ycb_16": 1464, "pose_ycb_04": 1720, "mesh_ycb_04": 1720, "pose_ycb_08": 1616, "mesh_ycb_08": 1616, "pose_ycb_09": 1568, "mesh_ycb_09": 1568, "pose_ycb_18": 1776, "mesh_ycb_18": 1776, "pose_ycb_03": 1408, "mesh_ycb_03": 1408, "pose_ycb_17": 1576, "mesh_ycb_17": 1576, "pose_ycb_07": 1504, "mesh_ycb_07": 1504, "pose_ycb_13": 1672, "mesh_ycb_13": 1672, "pose_ycb_10": 1688, "mesh_ycb_10": 1688}, "config": {"root": "/data0/xuzhefeng/Datasets/dex-ycb", "out": "/data0/xuzhefeng/Datasets/uni-hoi-dataset", "release_id": "shared-v1.0", "limit": null, "max_frames": null, "mano_dir": "/data0/xuzhefeng/Datasets/mano", "views": null, "jpeg_full_check": false, "subjects": null}, "published_script_sha256": {"render_dexycb_validation.py": "5336c7d7e84536223328f013894a105e4aa4cd0a32fa3befc9e41ec13fd1c76b", "warehouse_v1_0.py": "6bdc15c3f88a9eb9c460a2569bca65f8767b42ed44eba78518fdbdb5b021d553", "convert_visor_v1.0.py": "e011c184261359364ad507484373bfc1a1a58387c4c2140ee97b523cab3a6879", "render_hoi4d_validation.py": "35c96fce9984987601d11e68e05ca849f8a8a5b01b80458d3216acf3805ff6cf", "convert_h2o_v1.0.py": "c434436efd6fdb7cd383322224f5cc5bb8cc59294f97c5668e0f787d734de75e", "convert_hoi4d_v1.0.py": "a751aa6a074c97578e11bc9b42052fe8dbb7075f122e8c2c7c04100445ad0bc5", "convert_dexycb_v1.0.py": "a766b9b482e0bdf1025e3ce36987df45ef1b0558bcd1ece1b79c122aed5a4e8f"}, "sampled_views": ["data/20200709-subject-01_20200709_141754/836212060125", "data/20200813-subject-02_20200813_145341/836212060125", "data/20200820-subject-03_20200820_135250/836212060125", "data/20200903-subject-04_20200903_103554/836212060125", "data/20200908-subject-05_20200908_143301/836212060125", "data/20200918-subject-06_20200918_112947/836212060125", "data/20200928-subject-07_20200928_143249/836212060125", "data/20201002-subject-08_20201002_104620/836212060125", "data/20201015-subject-09_20201015_142601/836212060125", "data/20201015-subject-09_20201015_142601/932122062010", "data/20201022-subject-10_20201022_110806/836212060125"], "scope": "Structure and file refs checked for all views; persisted QC and HTML only for sampled views. No manual visual approval yet."}
dex-ycb/shared-v1.0/doc/validation/validation-run.status ADDED
@@ -0,0 +1 @@
 
 
1
+ EXIT=0 END=2026-09-28T18:37:38+08:00
dex-ycb/shared-v1.0/script/__pycache__/render_dexycb_validation.py.cpython-38.pyc ADDED
Binary file (3.95 kB). View file
 
dex-ycb/shared-v1.0/script/__pycache__/render_hoi4d_validation.cpython-312.pyc ADDED
Binary file (18.9 kB). View file
 
dex-ycb/shared-v1.0/script/__pycache__/render_hoi4d_validation.py.cpython-38.pyc ADDED
Binary file (9.83 kB). View file
 
dex-ycb/shared-v1.0/script/__pycache__/warehouse_v1_0.cpython-312.pyc ADDED
Binary file (76.1 kB). View file
 
dex-ycb/shared-v1.0/script/check_dexycb_coverage.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Count per-frame source RGB/depth/label presence in a finished Dex-YCB release."""
3
+ from collections import Counter
4
+ import json
5
+ from pathlib import Path
6
+ import sys
7
+
8
+ KINDS = ('color', 'aligned_depth_to_color', 'labels')
9
+
10
+
11
+ def check_view(view):
12
+ meta = json.loads((view / 'metainfo.json').read_text())
13
+ missing = Counter()
14
+ count = 0
15
+ with (view / 'camera/frames.jsonl').open() as stream:
16
+ for count, line in enumerate(stream, 1):
17
+ row = json.loads(line)
18
+ assert row['frame_index'] == row['source_frame_id'] == count - 1, (view, count)
19
+ sources = row['component_sources']
20
+ for kind in KINDS:
21
+ if kind not in sources:
22
+ missing[kind] += 1
23
+ else:
24
+ assert sources[kind].get('file') and sources[kind].get('member'), (view, count, kind)
25
+ assert count == meta['num_frames'], (view, count, meta['num_frames'])
26
+ return count, missing
27
+
28
+
29
+ def audit(root):
30
+ totals, affected = Counter(), Counter()
31
+ examples = []
32
+ views = 0
33
+ for seq in sorted((root / 'data').iterdir()):
34
+ if not seq.is_dir():
35
+ continue
36
+ for view in sorted(p for p in seq.iterdir() if p.is_dir()):
37
+ frames, missing = check_view(view)
38
+ views += 1
39
+ totals['frames'] += frames
40
+ for kind in KINDS:
41
+ totals['missing_' + kind] += missing[kind]
42
+ affected[kind] += bool(missing[kind])
43
+ if missing and len(examples) < 20:
44
+ examples.append({'view': str(view.relative_to(root)), 'missing': dict(missing)})
45
+ assert views == 8000, views
46
+ result = {'views': views, 'frames': totals['frames'], 'missing_frames': {k: totals['missing_' + k] for k in KINDS},
47
+ 'affected_views': dict(affected), 'first_20_affected_views': examples,
48
+ 'scope': 'Count source locator presence and frame index in saved frames.jsonl, not direct reread of source tar or decoded-media QC.'}
49
+ path = root / 'doc/validation/SOURCE_FRAME_COVERAGE.json'
50
+ path.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n')
51
+ return result
52
+
53
+
54
+ if __name__ == '__main__':
55
+ print(json.dumps(audit(Path(sys.argv[1]).expanduser().resolve()), ensure_ascii=False), flush=True)
dex-ycb/shared-v1.0/script/check_dexycb_projection.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Check saved Dex-YCB source 3D joints against saved source 2D joints in sampled views."""
3
+ import json
4
+ from pathlib import Path
5
+ import sys
6
+
7
+ import numpy as np
8
+ import torch
9
+
10
+ root = Path(sys.argv[1])
11
+ report = json.loads((root / 'doc/validation/STRUCTURAL_AUDIT.json').read_text())
12
+ checks = []
13
+ for name in report['sampled_views']:
14
+ view = root / name
15
+ load = lambda path: torch.load(view / path, weights_only=True, map_location='cpu').numpy()
16
+ k = load('camera/intrinsic.pt')
17
+ xyz = load('annotation/keypoints/xyz.pt')
18
+ uv = load('annotation/keypoints/uv.pt')
19
+ valid = load('annotation/keypoints/xyz_valid.pt') & load('annotation/keypoints/uv_valid.pt')
20
+ z = xyz[..., 2]
21
+ valid &= np.isfinite(xyz).all(axis=-1) & np.isfinite(uv).all(axis=-1) & (z > 0)
22
+ z = np.where(valid, z, 1)
23
+ pred = np.stack((k[:, 0, 0, None, None] * xyz[..., 0] / z + k[:, 0, 2, None, None],
24
+ k[:, 1, 1, None, None] * xyz[..., 1] / z + k[:, 1, 2, None, None]), axis=-1)
25
+ errors = np.linalg.norm(pred[valid] - uv[valid], axis=-1)
26
+ checks.append(dict(view=name, points=int(errors.size), median_px=float(np.median(errors)) if errors.size else None,
27
+ p95_px=float(np.percentile(errors, 95)) if errors.size else None))
28
+ (root / 'doc/validation/KEYPOINT_PROJECTION_QC.json').write_text(json.dumps({
29
+ 'scope': 'Saved source 3D joints projected with saved color intrinsics vs saved source 2D joints; independent of hand mesh rendering.',
30
+ 'views': checks}, ensure_ascii=False, indent=2) + '\n')
31
+ print(json.dumps(checks, ensure_ascii=False), flush=True)
dex-ycb/shared-v1.0/script/config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "root": "/data0/xuzhefeng/Datasets/dex-ycb",
3
+ "out": "/data0/xuzhefeng/Datasets/uni-hoi-dataset",
4
+ "release_id": "shared-v1.0",
5
+ "limit": null,
6
+ "max_frames": null,
7
+ "mano_dir": "/data0/xuzhefeng/Datasets/mano",
8
+ "views": null,
9
+ "jpeg_full_check": false,
10
+ "subjects": null
11
+ }
dex-ycb/shared-v1.0/script/convert_dexycb_v1.0.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Dex-YCB source annotations → CONTRACT.md v1.0. No derived annotations."""
3
+ import io
4
+ import re
5
+ import shutil
6
+ import tarfile
7
+ import tempfile
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ from PIL import Image
12
+ import yaml
13
+
14
+ from warehouse_v1_0 import (View, build_record, find_file, locator, mano_models, mesh_asset,
15
+ model_profile, parser, pca_to_axis_angle, release, roots, safe_member, sequence_dir)
16
+
17
+ IMG_W, IMG_H = 640, 480
18
+
19
+ class _Loader(yaml.SafeLoader):
20
+ pass
21
+
22
+
23
+ _Loader.add_constructor("tag:yaml.org,2002:python/tuple",
24
+ lambda l, n: tuple(l.construct_sequence(n)))
25
+
26
+
27
+ def yaml_load_bytes(data: bytes):
28
+ return yaml.load(io.BytesIO(data), Loader=_Loader)
29
+
30
+
31
+ class Calibration:
32
+ def __init__(self, dexycb_root: Path):
33
+ self.intrinsics = {} # serial -> {fx,fy,cx,cy,w,h}
34
+ self.extrinsics = {} # group -> {serial: [12] 行优先 3×4 cam→world}
35
+ self.betas = {} # mano_calib_name -> [10]
36
+ calib_dir = dexycb_root / "calibration"
37
+ if calib_dir.is_dir():
38
+ self._load((p.as_posix(), p.read_bytes())
39
+ for p in sorted(calib_dir.rglob("*")) if p.is_file())
40
+ else:
41
+ tar_path = dexycb_root / "calibration.tar.gz"
42
+ if not tar_path.exists():
43
+ raise FileNotFoundError(f"no calibration/ nor calibration.tar.gz in {dexycb_root}")
44
+ with tarfile.open(tar_path, "r:gz") as tf:
45
+ self._load((m.name, tf.extractfile(m).read()) for m in tf if m.isfile())
46
+
47
+ _RE_INTR = re.compile(r"(?:^|/)intrinsics/(\d+)_\d+x\d+\.yml$")
48
+ _RE_EXTRA = re.compile(r"(?:^|/)extrinsics_(\d{8}_\d{6})/extrinsics\.yml$")
49
+ _RE_MANO = re.compile(r"(?:^|/)mano_(\d{8}_\d{6}_subject-\d{2}_right)/mano\.yml$")
50
+
51
+ def _load(self, files):
52
+ for rel, data in files:
53
+ m = self._RE_INTR.search(rel)
54
+ if m:
55
+ c = yaml_load_bytes(data)["color"]
56
+ self.intrinsics[m.group(1)] = {"fx": float(c["fx"]), "fy": float(c["fy"]),
57
+ "cx": float(c["ppx"]), "cy": float(c["ppy"]),
58
+ "w": IMG_W, "h": IMG_H}
59
+ continue
60
+ m = self._RE_EXTRA.search(rel)
61
+ if m:
62
+ raw = yaml_load_bytes(data)["extrinsics"]
63
+ self.extrinsics[m.group(1)] = {
64
+ str(s): [float(x) for x in np.asarray(v).ravel()] for s, v in raw.items()}
65
+ continue
66
+ m = self._RE_MANO.search(rel)
67
+ if m:
68
+ self.betas[m.group(1)] = [float(b) for b in yaml_load_bytes(data)["betas"]]
69
+
70
+
71
+
72
+ def calibration_locator(path, member, **extra):
73
+ if path.is_dir():
74
+ return locator(path / member.removeprefix('calibration/'), **extra)
75
+ return locator(path, member, **extra)
76
+
77
+
78
+ def prepare_models(root, destination):
79
+ archive = find_file(root, 'models.tar.gz')
80
+ if archive is None:
81
+ return {}, None
82
+ pattern = re.compile(r'^models/(\d{3}_[a-z0-9_]+)/(textured_simple\.obj(?:\.mtl)?|texture_map\.png)$')
83
+ names = set()
84
+ with tarfile.open(archive, 'r|gz') as tf:
85
+ for member in tf:
86
+ match = pattern.fullmatch(member.name)
87
+ if member.isfile() and match:
88
+ names.add(match[1])
89
+ path = safe_member(destination, '/'.join(match.groups()))
90
+ path.parent.mkdir(parents=True, exist_ok=True)
91
+ path.write_bytes(tf.extractfile(member).read())
92
+ if len(names) != 21:
93
+ raise ValueError('expected all 21 source YCB model directories')
94
+ return {i: destination / name for i, name in enumerate(sorted(names), 1)}, archive
95
+
96
+
97
+ def convert_view(path, args, seq, serial, frames, meta, meta_loc, calib, calib_path, models, assets, asset_archive):
98
+ total = int(meta.get('num_frames', max(frames) + 1))
99
+ ids = list(range(min(total, args.max_frames) if args.max_frames else total))
100
+ for f in ids:
101
+ frames.setdefault(f, {})
102
+ if not ids:
103
+ raise ValueError('no RGB frames')
104
+ source_rows = []
105
+ for f in ids:
106
+ row = frames[f]
107
+ source_rows.append(dict(source_frame_id=f, sync_id=f'{seq}:{f}',
108
+ source_locator=row['color'][1] if 'color' in row else (meta_loc | {'source_frame_id': f, 'missing_rgb': True}), annotation_matches={
109
+ 'labels': {'source_frame_id': f, 'source_timestamp_ns': None, 'clock_domain': None,
110
+ 'match_method': 'index_map', 'delta_ns': None, 'source_locator': row['labels'][1]}
111
+ for _ in [0] if 'labels' in row},
112
+ component_sources={k: v[1] for k, v in row.items()}))
113
+ view = View(path, 'dex-ycb', args.release_id, seq, serial, source_rows,
114
+ sampling='dense' if ids == list(range(ids[0], ids[-1] + 1)) else 'sparse')
115
+ view.valid_rules = {
116
+ 'mano': 'Source pose_m present and not all zero; side model/calibration available',
117
+ 'keypoints': 'Corresponding joint_2d/joint_3d present; whole-hand all -1 is missing, broadcast to its 21 points',
118
+ 'pose': 'Source pose_y for this ycb_ids slot present and not an all-zero matrix',
119
+ 'segment': 'Source seg array provided for this frame; region codes and entity references validated',
120
+ 'relations': 'Source sequence ycb_grasp_ind resolves through ycb_ids; broadcast sequence grasp to selected frames',
121
+ }
122
+ view.full_jpeg = getattr(args, 'jpeg_full_check', False)
123
+ view.meta['view_type'] = 'exo'
124
+ view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views}
125
+ subject = re.search(r'subject-(\d+)', seq)
126
+ if subject and 1 <= int(subject[1]) <= 10:
127
+ index = int(subject[1])
128
+ view.meta.update(split='val' if index == 7 else 'test' if index in (8, 9) else 'train',
129
+ split_scheme='Dex-YCB/s1', split_source_locator={
130
+ 'url': 'https://github.com/NVlabs/dex-ycb-toolkit/blob/master/dex_ycb_toolkit/dex_ycb.py',
131
+ 'rule': 's1 unseen-subject: 01-06/10 train, 07 val, 08-09 test'})
132
+ view.meta.pop('split_reason', None)
133
+ view.rgb([frames[f]['color'][0] if 'color' in frames[f] else None for f in ids], {'frames_ref': 'camera/frames.jsonl'})
134
+ n = len(ids)
135
+ intr = calib.intrinsics.get(serial)
136
+ K = None if intr is None else np.array([[intr['fx'], 0, intr['cx']], [0, intr['fy'], intr['cy']], [0, 0, 1]])
137
+ ext = calib.extrinsics.get(str(meta['extrinsics']), {}).get(serial)
138
+ E = None
139
+ if ext is not None:
140
+ E = np.eye(4)
141
+ E[:3] = np.asarray(ext).reshape(3, 4)
142
+ E = np.linalg.inv(E)
143
+ view.camera(K, calibration_locator(calib_path, f'calibration/intrinsics/{serial}_640x480.yml'), E,
144
+ calibration_locator(calib_path, f'calibration/extrinsics_{meta["extrinsics"]}/extrinsics.yml',
145
+ conversion='inverse of source T_world_from_camera'))
146
+ sides = meta.get('mano_sides')
147
+ if sides not in (['left'], ['right']):
148
+ raise ValueError(f'expected exactly one anatomical source hand: {sides}')
149
+ side = sides[0]
150
+ slot = ['left', 'right'].index(side)
151
+ cal_name = meta['mano_calib'][0] if isinstance(meta['mano_calib'], list) else meta['mano_calib']
152
+ labels = [dict(np.load(frames[f]['labels'][0])) if 'labels' in frames[f] else {} for f in ids]
153
+ label_loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources.labels'}
154
+ motion = np.full((n, 2, 61), np.nan, np.float32)
155
+ mv = np.zeros((n, 2), bool)
156
+ if side in models and any('pose_m' in lab for lab in labels):
157
+ for i, lab in enumerate(labels):
158
+ if 'pose_m' not in lab:
159
+ continue
160
+ pose = np.asarray(lab['pose_m']).reshape(51)
161
+ if not np.any(pose): # Official Dex-YCB missing-pose sentinel, independent of joints/seg.
162
+ continue
163
+ motion[i, slot] = np.r_[pose[:3], pca_to_axis_angle(pose[3:48], models[side]),
164
+ calib.betas[cal_name], pose[48:51]]
165
+ mv[i, slot] = True
166
+ view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv,
167
+ ['T', 'hand', 'parameter'], label_loc, model_profile=model_profile(models),
168
+ calibration_source=calibration_locator(calib_path, f'calibration/mano_{cal_name}/mano.yml'),
169
+ provenance={'kind': 'format_conversion', 'method': 'source PCA @ hands_components + hands_mean; explicit axis-angle consumed with flat_hand_mean=true'})
170
+ elif any('pose_m' in lab for lab in labels):
171
+ view.absent('mano', 'Source PCA exists; provide --mano-dir to expand it', 'dependency_missing')
172
+ else:
173
+ view.absent('mano', 'No source pose_m field')
174
+ for source_key, key, dim, unit in [('joint_2d', 'uv', 2, 'pixel'), ('joint_3d', 'xyz', 3, 'm')]:
175
+ if not any(source_key in x for x in labels):
176
+ view.absent('keypoints_' + key, 'No source ' + source_key)
177
+ continue
178
+ points = np.full((n, 2, 21, dim), np.nan, np.float32)
179
+ valid = np.zeros((n, 2, 21), bool)
180
+ for i, lab in enumerate(labels):
181
+ if source_key not in lab:
182
+ continue
183
+ p = np.asarray(lab[source_key]).reshape(21, dim)
184
+ points[i, slot] = p
185
+ valid[i, slot] = not np.all(p == -1) # Official sentinel covers the whole source hand.
186
+ # An individual off-image point (-1, -1) is not evidence of missing annotation.
187
+ view.tensor('keypoints_' + key, f'keypoints/{key}/v1', f'annotation/keypoints/{key}.pt',
188
+ points, valid, ['T', 'hand', 'keypoint', 'coordinate'], label_loc,
189
+ keypoint_schema='mano21/v1', unit=unit)
190
+ ycb_ids = [int(x) for x in meta['ycb_ids']]
191
+ for j, oid in enumerate(ycb_ids):
192
+ entity = f'ycb_{oid:02d}'
193
+ view.object(entity, meta_loc, source_object_id=oid, category_id=oid)
194
+ poses = np.full((n, 4, 4), np.nan, np.float32)
195
+ valid = np.zeros(n, bool)
196
+ for i, lab in enumerate(labels):
197
+ if 'pose_y' in lab:
198
+ pose = np.asarray(lab['pose_y'])
199
+ if pose.shape != (len(ycb_ids), 3, 4):
200
+ raise ValueError('pose_y shape differs from ycb_ids')
201
+ if np.any(pose[j]): # Official all-zero missing object pose sentinel.
202
+ poses[i] = np.eye(4)
203
+ poses[i, :3] = pose[j]
204
+ valid[i] = True
205
+ if any('pose_y' in lab for lab in labels):
206
+ view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt',
207
+ poses, valid, ['T', 'row', 'column'], label_loc,
208
+ convention='T_camera_from_object', unit='m')
209
+ else:
210
+ view.absent('pose_' + entity, 'No source pose_y field')
211
+ if oid in assets:
212
+ mesh_asset(view, entity, assets[oid], assets[oid] / 'textured_simple.obj',
213
+ locator(asset_archive, f'models/{assets[oid].name}/textured_simple.obj'))
214
+ else:
215
+ view.absent('mesh_' + entity, 'models.tar.gz unavailable', 'not_downloaded')
216
+ if any('seg' in lab for lab in labels):
217
+ mask_rows = []
218
+ width, height = view.meta['camera']['image_size']
219
+ for i, lab in enumerate(labels):
220
+ values = np.unique(lab.get('seg', np.zeros((height, width), np.uint8)))
221
+ mappings = []
222
+ for value in values:
223
+ value = int(value)
224
+ if value == 0:
225
+ continue
226
+ if value != 255 and value not in ycb_ids:
227
+ raise ValueError(f'unknown Dex-YCB region value {value}')
228
+ mappings.append(dict(mask_value=value, category_id='hand' if value == 255 else value,
229
+ entity_id='hand_' + side if value == 255 else f'ycb_{value:02d}', part_id=None,
230
+ source_instance_id=value))
231
+ mask_rows.append(dict(frame_index=i, labels=mappings))
232
+ view.raster('segment', (lab.get('seg', np.zeros((height, width), np.uint16)) for lab in labels),
233
+ ['seg' in lab for lab in labels], label_loc, mask_rows)
234
+ view.meta['components']['segment'].update(coverage={'kind': 'selected_entities',
235
+ 'entities': ['hand_' + side] + [f'ycb_{o:02d}' for o in ycb_ids]}, source_zero_meaning='background')
236
+ else:
237
+ view.absent('segment', 'No source seg field')
238
+ if any('aligned_depth_to_color' in frames[f] for f in ids):
239
+ def depths():
240
+ width, height = view.meta['camera']['image_size']
241
+ for f in ids:
242
+ item = frames[f].get('aligned_depth_to_color')
243
+ if item is None:
244
+ yield np.full((height, width), np.nan, np.float32)
245
+ else:
246
+ with Image.open(item[0]) as im:
247
+ yield np.asarray(im).astype(np.float32) / 1000.0
248
+ view.raster('depth', depths(), None, {'frames_ref': 'camera/frames.jsonl',
249
+ 'source_field': 'component_sources.aligned_depth_to_color', 'conversion': 'millimetres to metres'})
250
+ else:
251
+ view.absent('depth', 'No source aligned_depth_to_color frames')
252
+ grasp = meta.get('ycb_grasp_ind')
253
+ if grasp is not None:
254
+ if not 0 <= int(grasp) < len(ycb_ids):
255
+ raise ValueError('invalid ycb_grasp_ind')
256
+ relation = dict(relation_type='grasp', subject_id='hand_' + side,
257
+ object_id=f'ycb_{ycb_ids[int(grasp)]:02d}', status='positive', source_locator=meta_loc,
258
+ provenance={'kind': 'source', 'method': 'sequence ycb_grasp_ind resolved through ycb_ids; not per-frame contact'})
259
+ view.relations([{'frame_index': i, 'relations': [relation]} for i in range(n)], np.ones(n, bool), meta_loc)
260
+ else:
261
+ view.absent('relations', 'No source grasp/contact relation')
262
+ return view.finish()
263
+
264
+
265
+ MEMBER = re.compile(r'^([^/]+)/(\d{8}_\d{6})/(meta\.yml|(\d{12})/(color|labels|aligned_depth_to_color)_(\d+)\.(jpg|npz|png))$')
266
+
267
+
268
+ def convert_archive(archive, args, out, calib, calib_path, models, assets, asset_archive):
269
+ selected_views = set(args.views.split(',')) if args.views else None
270
+ done = 0
271
+ current, meta, meta_loc, rows = None, None, None, {}
272
+ with tempfile.TemporaryDirectory(prefix='dex-source-') as wd:
273
+ work = Path(wd)
274
+ def flush():
275
+ nonlocal done
276
+ if not rows:
277
+ return
278
+ seq = archive.name.split('.tar')[0] + '_' + current
279
+ reports = {}
280
+ with sequence_dir(out, seq) as target:
281
+ for serial, frames in sorted(rows.items()):
282
+ reports[serial] = convert_view(target / serial, args, seq, serial, frames, meta,
283
+ meta_loc, calib, calib_path, models, assets, asset_archive)
284
+ build_record(out, seq, reports)
285
+ for staged in list(work.iterdir()):
286
+ if staged.is_dir():
287
+ shutil.rmtree(staged)
288
+ else:
289
+ staged.unlink()
290
+ done += 1
291
+ print(f'Converted {seq}', flush=True)
292
+ with tarfile.open(archive, 'r|gz') as tf:
293
+ for member in tf:
294
+ match = MEMBER.fullmatch(member.name)
295
+ if not member.isfile() or not match:
296
+ continue
297
+ seq = match[2]
298
+ if seq != current:
299
+ flush()
300
+ if args.limit and done >= args.limit:
301
+ break
302
+ current, meta, meta_loc, rows = seq, None, None, {}
303
+ data_kind = match[3]
304
+ if data_kind == 'meta.yml':
305
+ data = tf.extractfile(member).read()
306
+ meta = yaml_load_bytes(data)
307
+ meta_loc = locator(archive, member.name, data)
308
+ continue
309
+ serial, kind, f = match[4], match[5], int(match[6])
310
+ if selected_views and serial not in selected_views or args.max_frames and f >= args.max_frames:
311
+ continue
312
+ data = tf.extractfile(member).read()
313
+ dest = safe_member(work, member.name)
314
+ dest.parent.mkdir(parents=True, exist_ok=True)
315
+ dest.write_bytes(data)
316
+ row = rows.setdefault(serial, {}).setdefault(f, {})
317
+ if kind in row:
318
+ raise ValueError('duplicate archive frame')
319
+ row[kind] = (dest, locator(archive, member.name, data))
320
+ else:
321
+ flush()
322
+ return done
323
+
324
+
325
+ def main(argv=None):
326
+ p = parser('dex-ycb', __doc__)
327
+ p.add_argument('--subjects')
328
+ args = p.parse_args(argv)
329
+ archives = sorted({a for r in roots(args.root) for a in r.glob('*-subject-*.tar.gz')})
330
+ if args.subjects:
331
+ subjects = {s.strip().zfill(2) for s in args.subjects.split(',')}
332
+ archives = [a for a in archives if re.search(r'subject-(\d+)', a.name)[1] in subjects]
333
+ if not archives:
334
+ p.error('no Dex-YCB subject archives found')
335
+ cp = find_file(args.root, 'calibration.tar.gz') or find_file(args.root, 'calibration')
336
+ if cp is None:
337
+ p.error('calibration source missing')
338
+ calib = Calibration(cp.parent)
339
+ models = mano_models(args.mano_dir)
340
+ out = release(args, 'dex-ycb')
341
+ with tempfile.TemporaryDirectory(prefix='dex-models-') as wd:
342
+ assets, asset_archive = prepare_models(args.root, Path(wd))
343
+ for archive in archives:
344
+ convert_archive(archive, args, out, calib, cp, models, assets, asset_archive)
345
+ return 0
346
+
347
+
348
+ if __name__ == '__main__':
349
+ raise SystemExit(main())
dex-ycb/shared-v1.0/script/convert_h2o_v1.0.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """H2O native RGB-D, MANO, joints and objects → CONTRACT.md v1.0 (no rendered masks)."""
3
+ import json
4
+ import re
5
+ import shutil
6
+ import tarfile
7
+ import tempfile
8
+ from pathlib import Path
9
+ import zipfile
10
+
11
+ import numpy as np
12
+ from PIL import Image
13
+
14
+ from warehouse_v1_0 import (View, build_record, find_file, locator, mano_models, mesh_asset,
15
+ model_profile, parser, release, roots, safe_member, sequence_dir)
16
+
17
+ OBJECTS = {1: 'book', 2: 'espresso', 3: 'lotion', 4: 'spray',
18
+ 5: 'milk', 6: 'cocoa', 7: 'chips', 8: 'cappuccino'}
19
+ MEMBER = re.compile(r'^(?:h2o_CASA/)?(subject\d+)/([^/]+)/(\d+)/(cam\d)/(.+)$')
20
+ FRAME = re.compile(r'(rgb|depth|cam_pose|hand_pose|hand_pose_mano|obj_pose|obj_pose_rt)/(\d+)\.(png|jpg|txt)$')
21
+
22
+
23
+ def load_splits(root):
24
+ archive = find_file(root, 'label_split.zip')
25
+ result = {}
26
+ if archive is not None:
27
+ with zipfile.ZipFile(archive) as z:
28
+ for split in ('train', 'val', 'test'):
29
+ member = f'label_split/action_{split}.txt'
30
+ for line_no, line in enumerate(z.read(member).decode().splitlines(), 1):
31
+ fields = line.split()
32
+ if len(fields) < 2 or fields[1] == 'path':
33
+ continue
34
+ key = fields[1]
35
+ if key in result and result[key][0] != split:
36
+ raise ValueError('conflicting official splits')
37
+ result[key] = (split, locator(archive, member, record=line_no))
38
+ return result
39
+
40
+
41
+ def load_assets(root, work):
42
+ archive = find_file(root, 'object.zip')
43
+ if archive is None:
44
+ return {}, None
45
+ with zipfile.ZipFile(archive) as z:
46
+ for member in z.infolist():
47
+ if member.is_dir():
48
+ continue
49
+ path = safe_member(work, member.filename)
50
+ path.parent.mkdir(parents=True, exist_ok=True)
51
+ path.write_bytes(z.read(member))
52
+ result = {}
53
+ for oid, name in OBJECTS.items():
54
+ directory = work / 'object' / name
55
+ candidates = list(directory.glob('*.obj'))
56
+ if len(candidates) != 1:
57
+ raise ValueError(f'expected one source OBJ for {name}')
58
+ result[oid] = (directory, candidates[0])
59
+ return result, archive
60
+
61
+
62
+ def convert_view(path, args, seq, cam, rows, intr, splits, models, assets, asset_archive):
63
+ ids = list(range(min(rows), max(rows) + 1))
64
+ for f in ids:
65
+ rows.setdefault(f, {})
66
+ n = len(ids)
67
+ if not n:
68
+ raise ValueError('no RGB frames')
69
+ split, split_loc = splits.get(seq, ('unknown', None))
70
+ 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},
71
+ component_sources={k: item[1] for k, item in rows[f].items()},
72
+ annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None,
73
+ clock_domain=None, match_method='index_map', delta_ns=None)
74
+ for k in rows[f] if k != 'rgb'}) for f in ids]
75
+ view = View(path, 'H2O', args.release_id, seq.replace('/', '_'), cam, frame_rows, split=split)
76
+ view.valid_rules = {
77
+ 'mano': 'Per-hand hand_pose_mano flag equals 1; corresponding side model available',
78
+ 'keypoints': "Per-hand hand_pose flag equals 1, broadcast to that hand's 21 source points independently of MANO",
79
+ 'pose': 'Source obj_pose_rt class equals this nonzero object class',
80
+ 'points': 'Source obj_pose class equals this nonzero object class, broadcast to its 21 points',
81
+ }
82
+ view.full_jpeg = getattr(args, 'jpeg_full_check', False)
83
+ view.meta['view_type'] = 'ego' if cam == 'cam4' else 'exo' if cam in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown'
84
+ view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views}
85
+ if split_loc:
86
+ view.meta.update(split_scheme='official_action_split', split_source_locator=split_loc)
87
+ view.rgb([rows[f]['rgb'][0] if 'rgb' in rows[f] else None for f in ids], {'frames_ref': 'camera/frames.jsonl'})
88
+ loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'}
89
+ if intr is not None:
90
+ fx, fy, cx, cy, width, height = np.loadtxt(intr[0]).ravel()
91
+ if [int(width), int(height)] != view.meta['camera']['image_size']:
92
+ raise ValueError('source intrinsics resolution mismatch')
93
+ K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]])
94
+ view.camera(K, intr[1])
95
+ camps = np.full((n, 4, 4), np.nan, np.float32)
96
+ cv = np.zeros(n, bool)
97
+ data = []
98
+ for i, f in enumerate(ids):
99
+ lab = {k: np.loadtxt(item[0]).ravel() for k, item in rows[f].items() if k not in ('rgb', 'depth')}
100
+ data.append(lab)
101
+ if 'cam_pose' in lab:
102
+ camps[i] = np.linalg.inv(lab['cam_pose'].reshape(4, 4))
103
+ cv[i] = True
104
+ if cv.any():
105
+ view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', camps, cv,
106
+ ['T', 'row', 'column'], loc, convention='T_camera_from_world',
107
+ source_convention='T_world_from_camera')
108
+ motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool)
109
+ points, pv = np.full((n, 2, 21, 3), np.nan, np.float32), np.zeros((n, 2, 21), bool)
110
+ object_ids = set()
111
+ for i, lab in enumerate(data):
112
+ if 'hand_pose_mano' in lab:
113
+ hands = lab['hand_pose_mano'].reshape(2, 62)
114
+ for side, row in enumerate(hands):
115
+ if row[0] not in (0, 1):
116
+ raise ValueError('unexpected H2O MANO presence flag')
117
+ if row[0] == 1:
118
+ motion[i, side] = np.r_[row[4:52], row[52:62], row[1:4]]
119
+ mv[i, side] = True
120
+ if 'hand_pose' in lab:
121
+ hands = lab['hand_pose'].reshape(2, 64)
122
+ for side, row in enumerate(hands):
123
+ if row[0] not in (0, 1):
124
+ raise ValueError('unexpected H2O keypoint presence flag')
125
+ if row[0] == 1:
126
+ points[i, side] = row[1:].reshape(21, 3)
127
+ pv[i, side] = True
128
+ for key in ('obj_pose', 'obj_pose_rt'):
129
+ if key in lab and lab[key][0] != 0:
130
+ object_ids.add(int(lab[key][0]))
131
+ if any('hand_pose_mano' in lab for lab in data):
132
+ if len(models) == 2:
133
+ view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv,
134
+ ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models))
135
+ else:
136
+ view.absent('mano', 'Source parameters exist; --mano-dir must identify both model profiles', 'dependency_missing')
137
+ if any('hand_pose' in lab for lab in data):
138
+ view.tensor('keypoints_xyz', 'keypoints/xyz/v1', 'annotation/keypoints/xyz.pt', points, pv,
139
+ ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='m')
140
+ for oid in sorted(object_ids):
141
+ if oid not in OBJECTS:
142
+ raise ValueError(f'unknown H2O object class {oid}')
143
+ entity = OBJECTS[oid]
144
+ view.object(entity, loc, category_id=oid, source_object_id=oid)
145
+ poses, ov = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool)
146
+ pts, kv = np.full((n, 21, 3), np.nan, np.float32), np.zeros((n, 21), bool)
147
+ for i, lab in enumerate(data):
148
+ if 'obj_pose_rt' in lab and lab['obj_pose_rt'][0] == oid:
149
+ poses[i] = lab['obj_pose_rt'][1:].reshape(4, 4)
150
+ ov[i] = True
151
+ if 'obj_pose' in lab and lab['obj_pose'][0] == oid:
152
+ pts[i] = lab['obj_pose'][1:].reshape(21, 3)
153
+ kv[i] = True
154
+ if ov.any():
155
+ view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt',
156
+ poses, ov, ['T', 'row', 'column'], loc, convention='T_camera_from_object', unit='m')
157
+ if kv.any():
158
+ view.tensor('points_' + entity, 'object_keypoints/camera/v1',
159
+ f'annotation/object/{entity}/keypoints/xyz.pt', pts, kv,
160
+ ['T', 'keypoint', 'coordinate'], loc, keypoint_schema='H2O_official_object21',
161
+ keypoint_names=['center'] + [f'corner_{i}' for i in range(8)] + [f'edge_midpoint_{i}' for i in range(12)],
162
+ source_order='official obj_point_order.jpg: center, 8 corners, 12 edge midpoints', unit='m')
163
+ if oid in assets:
164
+ directory, obj = assets[oid]
165
+ mesh_asset(view, entity, directory, obj, locator(asset_archive, f'object/{entity}/{obj.name}'))
166
+ else:
167
+ view.absent('mesh_' + entity, 'Source object.zip unavailable', 'not_downloaded')
168
+ if any('depth' in rows[f] for f in ids):
169
+ width, height = view.meta['camera']['image_size']
170
+ def depths():
171
+ for f in ids:
172
+ item = rows[f].get('depth')
173
+ if item:
174
+ with Image.open(item[0]) as im:
175
+ yield np.asarray(im).astype(np.float32) / 1000.0
176
+ else:
177
+ yield np.full((height, width), np.nan, np.float32)
178
+ view.raster('depth', depths(), None, loc | {'source_field': 'component_sources.depth',
179
+ 'definition': 'https://github.com/taeinkwon/h2oplayer/blob/main/utils.py',
180
+ 'conversion': 'registered millimetre camera-Z to metres; no viewer range clipping'})
181
+ else:
182
+ view.absent('depth', 'No source depth frames')
183
+ view.absent('segment', 'H2O provides no native segmentation; rendering deferred to v2.0')
184
+ view.absent('relations', 'No source contact/grasp annotation')
185
+ return view.finish()
186
+
187
+
188
+ def convert_archive(archive, args, out, splits, models, assets, asset_archive):
189
+ selected_views = set(args.views.split(',')) if args.views else None
190
+ subjects = {'subject' + s.strip() for s in args.subjects.split(',')} if args.subjects else None
191
+ current, rows, intrinsics, done = None, {}, {}, 0
192
+ with tempfile.TemporaryDirectory(prefix='h2o-source-') as wd:
193
+ work = Path(wd)
194
+ def flush():
195
+ nonlocal done
196
+ if not rows:
197
+ return
198
+ seq = '/'.join(current)
199
+ reports, pending = {}, {}
200
+ for cam, frames in sorted(rows.items()):
201
+ existing = out / 'data' / seq.replace('/', '_') / cam
202
+ if (existing / 'metainfo.json').is_file():
203
+ old_frames = [json.loads(line) for line in (existing / 'camera/frames.jsonl').read_text().splitlines()]
204
+ if [f['source_frame_id'] for f in old_frames] != list(range(min(frames), max(frames) + 1)):
205
+ raise ValueError('existing view has different sampling; choose a new release-id')
206
+ for frame in old_frames:
207
+ incoming = frames.get(frame['source_frame_id'], {})
208
+ previous = frame.get('component_sources', {})
209
+ if set(previous) != set(incoming) or any(previous[k].get('sha256') != v[1].get('sha256') for k, v in incoming.items()):
210
+ raise ValueError('duplicate H2O view differs from the published source; choose a new release-id')
211
+ else:
212
+ pending[cam] = frames
213
+ if pending:
214
+ with sequence_dir(out, seq.replace('/', '_')) as target:
215
+ for cam, frames in pending.items():
216
+ reports[cam] = convert_view(target / cam, args, seq, cam, frames,
217
+ intrinsics.get(cam), splits, models, assets, asset_archive)
218
+ build_record(out, seq.replace('/', '_'), reports)
219
+ for staged in list(work.iterdir()):
220
+ if staged.is_dir():
221
+ shutil.rmtree(staged)
222
+ else:
223
+ staged.unlink()
224
+ done += 1
225
+ print(f'{"Converted" if pending else "Verified existing"} {seq}', flush=True)
226
+ # Uncompressed CASA supports seeking over large frames; gzip is single-pass.
227
+ mode = 'r:' if archive.suffix == '.tar' else 'r|gz'
228
+ with tarfile.open(archive, mode) as tf:
229
+ for member in tf:
230
+ match = MEMBER.fullmatch(member.name)
231
+ if not member.isfile() or not match:
232
+ continue
233
+ subj, scene, seq, cam, tail = match.groups()
234
+ if subjects and subj not in subjects:
235
+ continue
236
+ key = (subj, scene, seq)
237
+ if key != current:
238
+ flush()
239
+ if args.limit and done >= args.limit:
240
+ break
241
+ current, rows, intrinsics = key, {}, {}
242
+ if selected_views and cam not in selected_views:
243
+ continue
244
+ frame = FRAME.fullmatch(tail)
245
+ if tail != 'cam_intrinsics.txt' and not frame:
246
+ continue
247
+ if frame and args.max_frames and int(frame[2]) >= args.max_frames:
248
+ continue
249
+ data = tf.extractfile(member).read()
250
+ dest = safe_member(work, member.name)
251
+ dest.parent.mkdir(parents=True, exist_ok=True)
252
+ dest.write_bytes(data)
253
+ item = (dest, locator(archive, member.name, data))
254
+ if tail == 'cam_intrinsics.txt':
255
+ intrinsics[cam] = item
256
+ else:
257
+ kind, f = frame[1], int(frame[2])
258
+ row = rows.setdefault(cam, {}).setdefault(f, {})
259
+ if kind in row:
260
+ raise ValueError('duplicate H2O frame')
261
+ row[kind] = item
262
+ else:
263
+ flush()
264
+ return done
265
+
266
+
267
+ def main(argv=None):
268
+ p = parser('H2O', __doc__)
269
+ p.add_argument('--subjects')
270
+ p.add_argument('--include-casa', action='store_true')
271
+ p.add_argument('--archive', type=Path, help='Convert one explicit source archive')
272
+ args = p.parse_args(argv)
273
+ archives = [args.archive.expanduser()] if args.archive else sorted(
274
+ {a for root in roots(args.root) for a in root.glob('subject*_v1_1.tar.gz')})
275
+ if args.include_casa:
276
+ casa = find_file(args.root, 'h2o_CASA.tar')
277
+ if casa:
278
+ archives.append(casa)
279
+ if not archives:
280
+ p.error('no H2O archives found')
281
+ out = release(args, 'H2O')
282
+ models, splits = mano_models(args.mano_dir), load_splits(args.root)
283
+ with tempfile.TemporaryDirectory(prefix='h2o-assets-') as wd:
284
+ assets, asset_archive = load_assets(args.root, Path(wd))
285
+ for archive in archives:
286
+ convert_archive(archive, args, out, splits, models, assets, asset_archive)
287
+ return 0
288
+
289
+
290
+ if __name__ == '__main__':
291
+ raise SystemExit(main())
292
+
293
+ # TODO(v2.0): 以下旧 MANO 网格和渲染分割代码仅保留备查;v1.0 不生成标注。
294
+ # def load_mano_model(path: Path):
295
+ # """MPI MANO pkl → numpy 字典。shapedirs 在 pkl 内为 chumpy Select(对 (778,3,20) 基
296
+ # 底 flat 选取前 10 个 shape 分量;idxs 已核实等价于 base[:,:,:10])。"""
297
+ # with open(path, "rb") as f:
298
+ # d = _ManoUnpickler(f, encoding="latin1").load()
299
+ # sd = d["shapedirs"]
300
+ # base = np.asarray(sd.a.x, np.float64) # (778, 3, 20)
301
+ # shapedirs = base.reshape(-1)[np.asarray(sd.idxs)].reshape(base.shape[0], 3, -1)
302
+ # jreg = d["J_regressor"]
303
+ # jreg = np.asarray(jreg.todense()) if hasattr(jreg, "todense") else np.asarray(jreg)
304
+ # return {"v_template": np.asarray(d["v_template"], np.float64),
305
+ # "shapedirs": shapedirs,
306
+ # "posedirs": np.asarray(d["posedirs"], np.float64),
307
+ # "weights": np.asarray(d["weights"], np.float64),
308
+ # "J_regressor": np.asarray(jreg, np.float64),
309
+ # "kintree": np.asarray(d["kintree_table"], np.int64),
310
+ # "faces": np.asarray(d["f"], np.int64)}
311
+ #
312
+ #
313
+ # def rodrigues(r):
314
+ # """axis-angle (N,3) → 旋转矩阵 (N,3,3)。公式 I + sinθ·K + (1−cosθ)·K²(已对 scipy 核验)。"""
315
+ # r = np.asarray(r, np.float64).reshape(-1, 3)
316
+ # th = np.linalg.norm(r, axis=1)
317
+ # R = np.zeros((len(r), 3, 3))
318
+ # nz = th > 1e-12
319
+ # R[~nz] = np.eye(3)
320
+ # k = r[nz] / th[nz, None]
321
+ # K = np.zeros((len(k), 3, 3))
322
+ # K[:, 0, 1], K[:, 0, 2], K[:, 1, 2] = -k[:, 2], k[:, 1], -k[:, 0]
323
+ # K[:, 1, 0], K[:, 2, 0], K[:, 2, 1] = k[:, 2], -k[:, 1], k[:, 0]
324
+ # s, c = np.sin(th[nz])[:, None, None], np.cos(th[nz])[:, None, None]
325
+ # R[nz] = np.eye(3) + s * K + (1 - c) * (K @ K)
326
+ # return R
327
+ #
328
+ #
329
+ # def _mano_chain(model, betas, pose):
330
+ # """返回 (v_shaped, J, Rs, G):G 为 16 个关节的全局变换(平移列 = 关节位置)。"""
331
+ # v = model["v_template"] + np.einsum("nkc,c->nk", model["shapedirs"], betas)
332
+ # J = model["J_regressor"] @ v
333
+ # Rs = rodrigues(np.asarray(pose, np.float64).reshape(16, 3))
334
+ # kt = model["kintree"]
335
+ # G = np.zeros((16, 4, 4))
336
+ # for j in range(16):
337
+ # p = kt[0, j] if j else -1
338
+ # loc = np.eye(4)
339
+ # loc[:3, :3] = Rs[j]
340
+ # loc[:3, 3] = J[j] - (J[p] if j else 0.0)
341
+ # G[j] = loc if not j else G[p] @ loc
342
+ # return v, J, Rs, G
343
+ #
344
+ #
345
+ # def mano_forward(model, betas, pose, transl):
346
+ # """MANO LBS 前向(经典蒙皮 M_j = G_j·G0_j⁻¹;对 hand_pose 21 关节实证 0.0 mm)。
347
+ # pose: 48 axis-angle([0:3] 全局);返回相机系米顶点 (778,3)。"""
348
+ # v, J, Rs, G = _mano_chain(model, betas, pose)
349
+ # lrot = (Rs[1:] - np.eye(3)).ravel()
350
+ # v_posed = v + np.einsum("nkc,c->nk", model["posedirs"], lrot)
351
+ # kt = model["kintree"]
352
+ # G0 = np.zeros((16, 4, 4))
353
+ # for j in range(16):
354
+ # p = kt[0, j] if j else -1
355
+ # loc = np.eye(4)
356
+ # loc[:3, 3] = J[j] - (J[p] if j else 0.0)
357
+ # G0[j] = loc if not j else G0[p] @ loc
358
+ # M = np.einsum("nj,jab->nab", model["weights"], G @ np.linalg.inv(G0))
359
+ # out = np.einsum("nab,nb->na", M[:, :3, :3], v_posed) + M[:, :3, 3]
360
+ # return out + np.asarray(transl, np.float64)
361
+ #
362
+ #
363
+ # def mano_chain_joints(model, betas, pose, transl):
364
+ # """16 个关节位置(相机系米)= 链平移列;自检用。"""
365
+ # _, _, _, G = _mano_chain(model, betas, pose)
366
+ # return G[:, :3, 3] + np.asarray(transl, np.float64)
367
+ #
368
+ #
369
+ # def rasterize(verts_cam, faces, labels, W, H, fx, fy, cx, cy):
370
+ # z = verts_cam[:, 2]
371
+ # P = faces
372
+ # ok = (z[P] > 0.02).all(1) # 任一顶点在相机后 → 丢弃该三角形
373
+ # P, labels = P[ok], labels[ok]
374
+ # if len(P) == 0:
375
+ # return np.zeros((H, W), np.uint16), np.zeros(0, np.int64)
376
+ # x = verts_cam[:, 0] / z * fx + cx
377
+ # y = verts_cam[:, 1] / z * fy + cy
378
+ # xa = np.maximum(0, np.minimum(np.floor(x[P[:, 0]]), np.minimum(
379
+ # np.floor(x[P[:, 1]]), np.floor(x[P[:, 2]]))).astype(np.int64))
380
+ # xb = np.minimum(W - 1, np.maximum(np.ceil(x[P[:, 0]]), np.maximum(
381
+ # np.ceil(x[P[:, 1]]), np.ceil(x[P[:, 2]]))).astype(np.int64))
382
+ # ya = np.maximum(0, np.minimum(np.floor(y[P[:, 0]]), np.minimum(
383
+ # np.floor(y[P[:, 1]]), np.floor(y[P[:, 2]]))).astype(np.int64))
384
+ # yb = np.minimum(H - 1, np.maximum(np.ceil(y[P[:, 0]]), np.maximum(
385
+ # np.ceil(y[P[:, 1]]), np.ceil(y[P[:, 2]]))).astype(np.int64))
386
+ # xa, ya = np.minimum(xa, xb), np.minimum(ya, yb) # 完全出画的三角形 → 空 bbox
387
+ # wdt, hgt = xb - xa + 1, yb - ya + 1
388
+ # cnt = wdt * hgt
389
+ # tot = int(cnt.sum())
390
+ # tri = np.repeat(np.arange(len(P)), cnt)
391
+ # k = np.arange(tot) - (np.cumsum(cnt) - cnt)[tri]
392
+ # px = xa[tri] + k % wdt[tri] + 0.5
393
+ # py = ya[tri] + k // wdt[tri] + 0.5
394
+ # ax, ay = x[P[tri, 0]], y[P[tri, 0]]
395
+ # bx, by = x[P[tri, 1]], y[P[tri, 1]]
396
+ # cx_, cy_ = x[P[tri, 2]], y[P[tri, 2]]
397
+ # area = ((x[P[:, 1]] - x[P[:, 0]]) * (y[P[:, 2]] - y[P[:, 0]])
398
+ # - (y[P[:, 1]] - y[P[:, 0]]) * (x[P[:, 2]] - x[P[:, 0]]))
399
+ # areat = area[tri]
400
+ # e0 = (bx - ax) * (py - ay) - (by - ay) * (px - ax)
401
+ # e1 = (cx_ - bx) * (py - by) - (cy_ - by) * (px - bx)
402
+ # e2 = (ax - cx_) * (py - cy_) - (ay - cy_) * (px - cx_)
403
+ # s = np.sign(areat)
404
+ # inside = (np.abs(areat) > 1e-9) & ((e0 * s >= 0) & (e1 * s >= 0) & (e2 * s >= 0))
405
+ # px, py, tri = px[inside], py[inside], tri[inside]
406
+ # at = areat[inside]
407
+ # w0, w1, w2 = e1[inside] / at, e2[inside] / at, e0[inside] / at
408
+ # zz = w0 * z[P[tri, 0]] + w1 * z[P[tri, 1]] + w2 * z[P[tri, 2]]
409
+ # pix = py.astype(np.int64) * W + px.astype(np.int64)
410
+ # order = np.lexsort((zz, pix)) # 同像素按深度升序 → 首条即最近
411
+ # pix, tri = pix[order], tri[order]
412
+ # first = np.unique(pix, return_index=True)[1]
413
+ # mask = np.zeros(H * W, np.uint16)
414
+ # win = tri[first]
415
+ # mask[pix[first]] = labels[win] + 1 # 临时标签 +1(0=背景)
416
+ # return mask.reshape(H, W), np.bincount(labels[win] + 1)
417
+ #
418
+ #
419
+ # # ============================================================================
420
+ # # ffmpeg 写出与核验(与 convert_dexycb.py 同构)
421
+ # # ============================================================================
422
+ # verts, faces_all, labels = [], [], []
423
+ # for ti, (tid, kind) in enumerate(tracks):
424
+ # if kind == "hand_left" and b["mano"][0] > 0.5:
425
+ # verts.append(mano_forward(mano_models["left"], b["mano"][52:62],
426
+ # b["mano"][4:52], b["mano"][1:4]))
427
+ # faces_all.append(mano_models["left"]["faces"])
428
+ # elif kind == "hand_right" and b["mano"][62] > 0.5:
429
+ # verts.append(mano_forward(mano_models["right"], b["mano"][114:124],
430
+ # b["mano"][66:114], b["mano"][63:66]))
431
+ # faces_all.append(mano_models["right"]["faces"])
432
+ # elif isinstance(kind, tuple) and int(b["objp"][0]) == kind[1]:
433
+ # M = np.asarray(b["objrt"][1:17], np.float64).reshape(4, 4)
434
+ # V0, F0 = meshes[kind[1]]
435
+ # verts.append(V0 @ M[:3, :3].T + M[:3, 3])
436
+ # faces_all.append(F0)
437
+ # else:
438
+ # continue
439
+ # labels.append(np.full(len(faces_all[-1]), ti))
440
+ # if verts:
441
+ # V = np.concatenate(verts)
442
+ # offs = np.cumsum([0] + [len(v) for v in verts[:-1]])
443
+ # F = np.concatenate([fa + o for fa, o in zip(faces_all, offs)])
444
+ # mask, counts = rasterize(V, F, np.concatenate(labels),
445
+ # IMG_W, IMG_H, fx, fy, cx, cy)
446
+ # else:
447
+ # mask, counts = np.zeros((IMG_H, IMG_W), np.uint16), np.zeros(0, np.int64)
448
+ # lut = np.zeros(n_tracks + 1, np.uint16)
449
+ # for ti in range(n_tracks):
450
+ # present = ti + 1 < len(counts) and counts[ti + 1] > 0
451
+ # if present:
452
+ # presence[tracks[ti][0]][f] = True
453
+ # if active_id[ti] is None:
454
+ # pid = next(i for i in range(1, 65535) if i not in used)
455
+ # used.add(pid)
456
+ # active_id[ti], seg_start[ti] = pid, f
457
+ # frame_maps[ti].append({"id": pid})
458
+ # lut[ti + 1] = active_id[ti]
459
+ # elif active_id[ti] is not None:
460
+ # frame_maps[ti][-1]["frames"] = [seg_start[ti], f - 1]
461
+ # segments[ti].append([seg_start[ti], f - 1])
462
+ # used.discard(active_id[ti])
463
+ # active_id[ti] = None
464
+ # mw.write(lut[mask])
465
+
466
+
467
+ # TODO(v2.0): 旧物体尺寸派生代码;v1.0 仅保留源物体关键点。
468
+ # pts = np.asarray(b["objp"][1:64], np.float64).reshape(21, 3)
469
+ # half = np.abs((pts[1:9] - pts[0]) @ M[:3, :3]).max(0)
470
+ # obj_recs.append({
471
+ # "track_id": f"o{classes.index(c)}", "frame": f,
472
+ # "mesh_ref": f"h2o/{OBJ_CLASSES[c]}.obj",
473
+ # "pose": {"quat": rotmat_to_quat_wxyz(M[:3, :3])[0].tolist(),
474
+ # "trans": M[:3, 3].tolist()},
475
+ # "bbox_center3d": pts[0].tolist(),
476
+ # "bbox_size": (2 * half).tolist()})
dex-ycb/shared-v1.0/script/convert_hoi4d_v1.0.py ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """HOI4D native observations and annotations → CONTRACT.md v1.0."""
3
+ from collections import Counter
4
+ from contextlib import ExitStack
5
+ from functools import lru_cache
6
+ import gzip
7
+ import io
8
+ import json
9
+ from pathlib import Path
10
+ import pickle
11
+ import re
12
+ import shutil
13
+ import shlex
14
+ import posixpath
15
+ import subprocess
16
+ import tempfile
17
+ import tarfile
18
+ import zipfile
19
+
20
+ import numpy as np
21
+ from PIL import Image
22
+ from scipy.spatial.transform import Rotation
23
+
24
+ from warehouse_v1_0 import (View, build_record, check_mesh, decode_args, find_file, json_write, locator,
25
+ mano_models, model_profile, parser, probe, release, run, safe_member, sequence_dir)
26
+
27
+ CATEGORIES = {
28
+ 1: dict(cad="rigid/ToyCar", groups=[("main", [1], "Toy Car", 1)],
29
+ hands={2: "right"}, objmap={"Toycar": "main"}),
30
+ 2: dict(cad="rigid/Mug", groups=[("a", [1], "Mug", 2), ("b", [3], "Mug", 2)],
31
+ hands={2: "right"}, objmap={"Watercup": "a"}),
32
+ 3: dict(cad="articulated/Laptop", groups=[("main", [1, 3], "Laptop", 3)],
33
+ hands={2: "right"},
34
+ objmap={"Laptopdisplay": "main", "Laptopkeyboard": "main"}),
35
+ 4: dict(cad="articulated/StorageFurniture",
36
+ groups=[("main", [1, 3, 4], "Storage Furniture", 4),
37
+ ("bottle", [5], "Bottle", 5)],
38
+ hands={2: "right"},
39
+ objmap={"Lockerbody": "main", "Lockersldingdoor": "main",
40
+ "Lockerdrawer": "main", "Safebox": "main"}),
41
+ 5: dict(cad="rigid/Bottle", groups=[("main", [1], "Bottle", 5),
42
+ ("mug", [3], "Mug", 2)],
43
+ hands={2: "right"}, objmap={"bottleddrinks": "main"}),
44
+ 6: dict(cad="articulated/Safe", groups=[("main", [1, 3], "Safe", 6),
45
+ ("bottle", [4], "Bottle", 5)],
46
+ hands={2: "right"}, objmap={"Safebox": "main", "Safedoor": "main"}),
47
+ 7: dict(cad="rigid/Bowl", groups=[("main", [1], "Bowl", 7),
48
+ ("ball", [3], "Ball", None)],
49
+ hands={2: "right"}, objmap={"bowl": "main"}),
50
+ 8: dict(cad="articulated/Bucket",
51
+ groups=[("a", [1, 3], "Bucket", 8), ("b", [4, 5], "Bucket", 8)],
52
+ hands={2: "right", 6: "left"},
53
+ objmap={"bucket": "a", "Buckethandle": "a"}),
54
+ 9: dict(cad="articulated/Scissors", groups=[("main", [1, 3], "Scissors", 9)],
55
+ hands={2: "right"},
56
+ objmap={"scissors": "main", "scissors2": None}), # scissors2:场景道具,无掩码
57
+ 11: dict(cad="articulated/Pliers", groups=[("main", [1, 3], "Pliers", 11)],
58
+ hands={2: "right"}, objmap={"Pliersleft": "main", "Pliersright": "main"}),
59
+ 12: dict(cad="rigid/Kettle", groups=[("main", [1], "Kettle", 12),
60
+ ("mug", [3], "Mug", 2)],
61
+ hands={2: "right"}, objmap={"kettle": "main"}),
62
+ 13: dict(cad="rigid/Knife", groups=[("main", [1], "Knife", 13),
63
+ ("apple", [3], "Apple", None)],
64
+ hands={2: "right"}, objmap={"knife": "main"}),
65
+ 14: dict(cad="articulated/TrashCan",
66
+ groups=[("main", [1, 3], "Trash Can", 14), ("bottle", [4], "Bottle", 5)],
67
+ hands={2: "right"}, objmap={"Dustbinbase": "main", "Dustbincover": "main"}),
68
+ 17: dict(cad="articulated/Lamp", groups=[("main", [1, 3, 4, 5], "Lamp", 17)],
69
+ hands={2: "right", 6: "left"},
70
+ objmap={"Lampbase": "main", "Tablelampfirstjoint": "main",
71
+ "Tablelampsecondjoint": "main", "Thirdjointoftablelamp": "main"}),
72
+ 18: dict(cad="articulated/Stapler",
73
+ groups=[("main", [1, 3, 4], "Stapler", 18), ("paper", [5], "Paper", None)],
74
+ hands={2: "right", 6: "left"}, # 6=左手:官方 label.csv 缺列,实测修正
75
+ objmap={"Staplerbase": "main", "Staplercover": "main"}),
76
+ 20: dict(cad="rigid/Chair", groups=[("main", [1], "Chair", 20)],
77
+ hands={2: "right", 3: "left"}, objmap={"chair": "main"}),
78
+ }
79
+
80
+
81
+ # Official HOI4D definitions/motion segmentation/label.csv; no spatial side inference.
82
+ 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'}}
83
+
84
+
85
+ class SplitFiles(io.RawIOBase):
86
+ """Read concatenated source gzip parts without concatenating 119 GB on disk."""
87
+ def __init__(self, paths):
88
+ self.paths = iter(paths)
89
+ self.current = None
90
+
91
+ def readable(self):
92
+ return True
93
+
94
+ def readinto(self, buffer):
95
+ while True:
96
+ if self.current is None:
97
+ path = next(self.paths, None)
98
+ if path is None:
99
+ return 0
100
+ self.current = path.open('rb')
101
+ n = self.current.readinto(buffer)
102
+ if n:
103
+ return n
104
+ self.current.close()
105
+ self.current = None
106
+
107
+ def close(self):
108
+ if self.current is not None:
109
+ self.current.close()
110
+ super().close()
111
+
112
+
113
+ def extract_depths(root, sequences, work):
114
+ directory = find_file(root, 'DEPTH')
115
+ if directory is None:
116
+ return {}, []
117
+ parts = sorted(directory.glob('HOI4D_depth_video.tar.gz*'), key=lambda p: int(p.name.split('.gz')[1] or 0))
118
+ if not parts:
119
+ return {}, []
120
+ wanted = {f'HOI4D_depth_video/{seq}/align_depth/depth_video.avi': seq for seq in sequences}
121
+ found = {}
122
+ with SplitFiles(parts) as joined, io.BufferedReader(joined) as inp, gzip.GzipFile(fileobj=inp) as gz:
123
+ with tarfile.open(fileobj=gz, mode='r|') as tf:
124
+ for member in tf:
125
+ if member.isfile() and member.name in wanted:
126
+ seq = wanted[member.name]
127
+ dest = work / (seq.replace('/', '_') + '.avi')
128
+ with tf.extractfile(member) as src, dest.open('wb') as dst:
129
+ shutil.copyfileobj(src, dst)
130
+ found[seq] = (dest, {'files': [str(p.resolve()) for p in parts], 'member': member.name})
131
+ if len(found) == len(wanted):
132
+ break
133
+ return found, parts
134
+
135
+
136
+ def palette_mask(data):
137
+ with Image.open(io.BytesIO(data)) as im:
138
+ arr = np.asarray(im)
139
+ if arr.ndim == 2:
140
+ return arr.astype(np.uint16)
141
+ if arr.shape[-1] != 3:
142
+ raise ValueError('unsupported HOI4D mask representation')
143
+ colors = []
144
+ for i in range(256):
145
+ rgb, value = [0, 0, 0], i
146
+ for bit in range(8):
147
+ for channel in range(3):
148
+ rgb[channel] |= ((value >> channel) & 1) << (7 - bit)
149
+ value >>= 3
150
+ colors.append(rgb)
151
+ colors = np.asarray(colors, dtype=np.uint32)
152
+ codes = colors[:, 0] | colors[:, 1] << 8 | colors[:, 2] << 16
153
+ pixels = arr[..., 0].astype(np.uint32) | arr[..., 1].astype(np.uint32) << 8 | arr[..., 2].astype(np.uint32) << 16
154
+ unique, inv = np.unique(pixels, return_inverse=True)
155
+ lookup = {int(color): i for i, color in enumerate(codes)}
156
+ if any(int(c) not in lookup for c in unique):
157
+ raise ValueError('source mask has colors outside official VOC palette')
158
+ return np.array([lookup[int(c)] for c in unique], np.uint16)[inv].reshape(arr.shape[:2])
159
+
160
+
161
+ @lru_cache(maxsize=2)
162
+ def index_frames(z):
163
+ index = {}
164
+ for name in z.namelist():
165
+ parent, _, filename = name.rpartition('/')
166
+ stem, dot, suffix = filename.rpartition('.')
167
+ if not dot or not stem.isdigit() or suffix not in ('png', 'json', 'pickle'):
168
+ continue
169
+ entries = index.setdefault((parent + '/', '.' + suffix), {})
170
+ f = int(stem)
171
+ if f in entries:
172
+ raise ValueError(f'duplicate frame number under {parent}')
173
+ entries[f] = name
174
+ return index
175
+
176
+
177
+ def frame_members(z, prefix, suffix):
178
+ return index_frames(z).get((prefix, suffix), {})
179
+
180
+
181
+ def convert_sequence(seq, args, target, rgbz, annz, hpz, calz, cadz, paths, models, depth):
182
+ category = int(re.search(r'/C(\d+)/', seq)[1])
183
+ definition = CATEGORIES.get(category)
184
+ if definition is None:
185
+ raise ValueError(f'category mapping unavailable: {category}')
186
+ prefix = f'HOI4D_annotations/{seq}'
187
+ mask_members = frame_members(annz, prefix + '/2Dseg/mask/', '.png')
188
+ if not mask_members:
189
+ mask_members = frame_members(annz, prefix + '/2Dseg/shift_mask/', '.png')
190
+ pose_members = frame_members(annz, prefix + '/objpose/', '.json')
191
+ hand_members = {side: frame_members(hpz, f'Hand_pose/handpose_{side}_hand/{seq}/', '.pickle')
192
+ for side in ('left', 'right')} if hpz else {'left': {}, 'right': {}}
193
+ with tempfile.TemporaryDirectory(prefix='hoi4d-source-') as wd:
194
+ work = Path(wd)
195
+ member = f'HOI4D_release/{seq}/align_rgb/image.mp4'
196
+ video = work / 'rgb.mp4'
197
+ with rgbz.open(member) as src, video.open('wb') as dst:
198
+ shutil.copyfileobj(src, dst)
199
+ info = probe(video)
200
+ if 'nb_frames' not in info:
201
+ info['nb_frames'] = json.loads(run(['ffprobe', '-v', 'error', '-count_frames', '-select_streams', 'v:0',
202
+ '-show_entries', 'stream=nb_read_frames', '-of', 'json', str(video)], stdout=subprocess.PIPE).stdout)['streams'][0]['nb_read_frames']
203
+ n = int(info['nb_frames'])
204
+ if args.max_frames:
205
+ n = min(n, args.max_frames)
206
+ frames = []
207
+ for f in range(n):
208
+ sources = {}
209
+ if f in mask_members:
210
+ sources['segment'] = locator(paths['annotations'], mask_members[f], annz.read(mask_members[f]))
211
+ if f in pose_members:
212
+ sources['object'] = locator(paths['annotations'], pose_members[f], annz.read(pose_members[f]))
213
+ for side in ('left', 'right'):
214
+ if f in hand_members[side]:
215
+ sources['hand_' + side] = locator(paths['hand'], hand_members[side][f], hpz.read(hand_members[side][f]))
216
+ frames.append(dict(source_frame_id=f, source_locator=locator(paths['release'], member, frame=f),
217
+ component_sources=sources, annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None,
218
+ clock_domain=None, match_method='index_map', delta_ns=None) for k in sources}))
219
+ view = View(target, 'HOI4D', args.release_id, seq.replace('/', '_'), 'ego', frames)
220
+ view.valid_rules = {
221
+ 'mano': 'Matched side pickle contains poseCoeff, beta, trans and corresponding model available; zero angles are not missing',
222
+ 'keypoints': 'Matched side pickle contains kps2D; independently provided source points, no visibility gate',
223
+ 'pose': 'Matched source object record contains rotation and center; record identity retained',
224
+ 'dimensions': 'Matched source object record contains dimensions; size/mesh relation remains source_unspecified',
225
+ 'segment': 'Source mask or shift_mask present with verified palette codes and entity/part mapping',
226
+ }
227
+ view.full_jpeg = getattr(args, 'jpeg_full_check', False)
228
+ view.meta['view_type'] = 'ego'
229
+ view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'source_sequence': seq}
230
+ view.rgb([], locator(paths['release'], member), video=video, count=n)
231
+ intr_name = f'camera_params/{seq.split("/")[0]}/intrin.npy'
232
+ if calz and intr_name in calz.namelist():
233
+ view.camera(np.load(io.BytesIO(calz.read(intr_name))), locator(paths['camera'], intr_name))
234
+ extr_name = prefix + '/3Dseg/output.log'
235
+ if extr_name in annz.NameToInfo:
236
+ lines = [line for line in annz.read(extr_name).decode().splitlines() if line.strip()]
237
+ if len(lines) % 5:
238
+ raise ValueError('invalid Open3D camera trajectory')
239
+ extr, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool)
240
+ for i in range(0, len(lines), 5):
241
+ idx = int(lines[i].split()[0])
242
+ if idx < n:
243
+ if valid[idx]:
244
+ raise ValueError('duplicate trajectory index')
245
+ extr[idx] = np.linalg.inv(np.loadtxt(io.StringIO('\n'.join(lines[i + 1:i + 5]))))
246
+ valid[idx] = True
247
+ view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', extr, valid,
248
+ ['T', 'row', 'column'], locator(paths['annotations'], extr_name),
249
+ convention='T_camera_from_world', source_convention='Open3D LOG camera-to-world; inverted')
250
+ loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'}
251
+ motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool)
252
+ points, pv = np.full((n, 2, 21, 2), np.nan, np.float32), np.zeros((n, 2, 21), bool)
253
+ for slot, side in enumerate(('left', 'right')):
254
+ for f, name in hand_members[side].items():
255
+ if f >= n:
256
+ continue
257
+ data = pickle.loads(hpz.read(name), encoding='latin1')
258
+ if all(k in data for k in ('poseCoeff', 'beta', 'trans')):
259
+ motion[f, slot] = np.r_[np.asarray(data['poseCoeff']).reshape(48),
260
+ np.asarray(data['beta']).reshape(10), np.asarray(data['trans']).reshape(3)]
261
+ mv[f, slot] = True # Zero angles are a valid pose, not a missing sentinel.
262
+ if 'kps2D' in data:
263
+ points[f, slot] = np.asarray(data['kps2D']).reshape(21, 2)
264
+ pv[f, slot] = True
265
+ if mv.any():
266
+ if all(side in models for slot, side in enumerate(('left', 'right')) if mv[:, slot].any()):
267
+ view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv,
268
+ ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models))
269
+ else:
270
+ view.absent('mano', 'Source MANO exists; provide --mano-dir to fix model identity', 'dependency_missing')
271
+ if pv.any():
272
+ view.tensor('keypoints_uv', 'keypoints/uv/v1', 'annotation/keypoints/uv.pt', points, pv,
273
+ ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='pixel',
274
+ source_method='Upstream fitted MANO projection already present in kps2D')
275
+ objects = {}
276
+ groups = {key: (vals, name, cls) for key, vals, name, cls in definition['groups']}
277
+ def ensure_object(key, source_loc, category_id=None, frame=None, source_id=None):
278
+ if key not in objects:
279
+ view.object(key, source_loc, scope='frame' if frame is not None else 'sequence',
280
+ scope_id=f'{seq}:{frame}' if frame is not None else None,
281
+ category_id=category_id, source_object_id=source_id)
282
+ objects[key] = {}
283
+ mappings = []
284
+ mask_valid = []
285
+ for f in range(n):
286
+ labels = []
287
+ if f in mask_members:
288
+ values = np.unique(palette_mask(annz.read(mask_members[f])))
289
+ for value in values:
290
+ value = int(value)
291
+ if value in (0, 255):
292
+ if value == 255:
293
+ raise ValueError('HOI4D 255 region semantics unverified')
294
+ continue
295
+ if REGION_NAMES[category].get(value) in ('Left Hand', 'Right Hand'):
296
+ entity, part, cls = 'hand_' + REGION_NAMES[category][value].split()[0].lower(), None, 'hand'
297
+ else:
298
+ group = next((k for k, (vals, _, _) in groups.items() if value in vals), None)
299
+ entity = group or f'unknown_region_{value}'
300
+ cls = groups[group][2] if group else None
301
+ part = f'region_{value}' if group and len(groups[group][0]) > 1 else None
302
+ ensure_object(entity, locator(paths['annotations'], mask_members[f], annz.read(mask_members[f])), cls)
303
+ if part:
304
+ objects[entity].setdefault('parts', {})[part] = {'part_id': part, 'parent_id': None,
305
+ 'has_model': False, 'mesh_ref': None, 'source_region_code': value, 'name': REGION_NAMES[category].get(value)}
306
+ labels.append(dict(mask_value=value, category_id=cls, entity_id=entity,
307
+ part_id=part, source_instance_id=value,
308
+ source_attributes={'region_name': REGION_NAMES[category].get(value)}))
309
+ mappings.append(dict(frame_index=f, labels=labels))
310
+ mask_valid.append(f in mask_members)
311
+ if any(mask_valid):
312
+ width, height = view.meta['camera']['image_size']
313
+ view.raster('segment', (palette_mask(annz.read(mask_members[f])) if f in mask_members else
314
+ np.zeros((height, width), np.uint16) for f in range(n)), mask_valid, loc, mappings)
315
+ view.meta['components']['segment']['coverage'] = {'kind': 'unknown'}
316
+ if any(label['part_id'] for row in mappings for label in row['labels']):
317
+ view.meta['components']['segment']['segmentation_type'] = 'part'
318
+ else:
319
+ view.absent('segment', 'No native segmentation for this source sequence')
320
+ records = {}
321
+ for f, name in pose_members.items():
322
+ if f >= n:
323
+ continue
324
+ data = json.loads(annz.read(name))
325
+ # isEffective is not used to erase existing numerical annotations.
326
+ source_records = data.get('dataList', data.get('objects'))
327
+ if source_records is None:
328
+ raise ValueError('unrecognized source object annotation structure')
329
+ label_counts = Counter(record['label'] for record in source_records)
330
+ per_frame = set()
331
+ for record_index, record in enumerate(source_records):
332
+ label = record['label']
333
+ group = definition['objmap'].get(label)
334
+ ambiguous = group is not None and sum(g[2] == groups[group][2] for g in groups.values()) > 1
335
+ ambiguous = ambiguous or label_counts[label] > 1 or group is None
336
+ entity = f'pose_frame_{f}_{record_index}' if ambiguous else group
337
+ ensure_object(entity, locator(paths['annotations'], name, record=record_index),
338
+ groups[group][2] if group else None, frame=f if ambiguous else None, source_id=record.get('id'))
339
+ if ambiguous:
340
+ view.build['unresolved'].append({'component': entity, 'status': 'source_semantics_unverified',
341
+ 'reason': 'Source pose retained with frame identity; no guessed association to same-class mask instances'})
342
+ label_key = (entity, label)
343
+ if label_key in per_frame:
344
+ raise ValueError(f'ambiguous repeated object label {label}; source identity must be resolved')
345
+ per_frame.add(label_key)
346
+ records.setdefault(label_key, {})[f] = (record, locator(paths['annotations'], name, record=record.get('id')))
347
+ for (entity, label), by_frame in records.items():
348
+ part_labels = [k[1] for k in records if k[0] == entity]
349
+ articulated = definition['cad'].startswith('articulated/') and entity == definition['groups'][0][0]
350
+ part = 'pose_' + re.sub(r'[^a-zA-Z0-9_]', '_', label) if articulated or len(part_labels) > 1 else None
351
+ base = f'annotation/object/{entity}'
352
+ if part:
353
+ base += '/parts/' + part
354
+ objects[entity].setdefault('parts', {})[part] = dict(part_id=part, parent_id=None,
355
+ has_model=False, mesh_ref=None, source_label=label)
356
+ poses, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool)
357
+ dimensions = np.full((n, 3), np.nan, np.float32)
358
+ dv = np.zeros(n, bool)
359
+ for f, (record, _) in by_frame.items():
360
+ if all(k in record for k in ('rotation', 'center')):
361
+ poses[f] = np.eye(4)
362
+ poses[f, :3, :3] = Rotation.from_euler('XYZ', [record['rotation'][k] for k in ('x', 'y', 'z')]).as_matrix()
363
+ poses[f, :3, 3] = [record['center'][k] for k in ('x', 'y', 'z')]
364
+ valid[f] = True
365
+ if 'dimensions' in record:
366
+ dimensions[f] = [record['dimensions'][k] for k in ('length', 'width', 'height')]
367
+ dv[f] = True
368
+ key = entity + ('_' + part if part else '')
369
+ view.tensor('pose_' + key, 'transform/se3/v1' if part else 'object/rigid/v1', base + '/pose.pt', poses, valid,
370
+ ['T', 'row', 'column'], loc, convention='T_camera_from_part' if part else 'T_camera_from_object',
371
+ unit='m', source_label=label, source_euler_order='XYZ',
372
+ definition='https://github.com/hoi4d/ObjTracking/blob/main/process_data.py')
373
+ if dv.any():
374
+ view.tensor('dimensions_' + key, 'object/dimensions/v1', base + '/dimensions.pt', dimensions, dv,
375
+ ['T', 'dimension'], loc, dimensions_semantics='source_unspecified', unit='m', scale_applied_to_mesh=False)
376
+ if cadz:
377
+ primary = definition['groups'][0][0]
378
+ if sum(g[2] == category for g in groups.values()) > 1:
379
+ primary = 'source_cad_instance'
380
+ instance = int(re.search(r'/N(\d+)/', seq)[1])
381
+ mesh_prefix = f'HOI4D_CAD_Model_for_release/{definition["cad"]}/{instance:03d}'
382
+ candidates = [name for name in cadz.namelist() if not name.endswith('/') and
383
+ (name == mesh_prefix + '.obj' or name.startswith(mesh_prefix + '/'))]
384
+ if candidates:
385
+ # Retain OBJ material/texture dependencies beside their original names.
386
+ queue = list(candidates)
387
+ for name in queue:
388
+ if Path(name).suffix.lower() not in ('.obj', '.mtl'):
389
+ continue
390
+ for line in cadz.read(name).decode().splitlines():
391
+ fields = shlex.split(line, comments=True)
392
+ if not fields:
393
+ continue
394
+ refs = fields[1:] if fields[0] == 'mtllib' else ([fields[-1]] if
395
+ fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal') else [])
396
+ for ref in refs:
397
+ dependency = posixpath.normpath(posixpath.join(posixpath.dirname(name), ref))
398
+ if dependency not in cadz.NameToInfo:
399
+ raise ValueError(f'missing CAD dependency: {dependency}')
400
+ if dependency not in candidates:
401
+ candidates.append(dependency)
402
+ queue.append(dependency)
403
+ ensure_object(primary, locator(paths['cad'], mesh_prefix), category)
404
+ asset_dir = view.path / f'annotation/object/{primary}/assets'
405
+ asset_refs = []
406
+ for name in candidates:
407
+ relative = posixpath.relpath(name, mesh_prefix if definition['cad'].startswith('articulated/') else posixpath.dirname(mesh_prefix))
408
+ dest = safe_member(asset_dir, relative)
409
+ dest.parent.mkdir(parents=True, exist_ok=True)
410
+ dest.write_bytes(cadz.read(name))
411
+ ref = dest.relative_to(view.path).as_posix()
412
+ if dest.suffix.lower() == '.obj':
413
+ asset_key = re.sub(r'[^a-zA-Z0-9_]', '_', relative)
414
+ view.component('mesh_' + primary + '_' + asset_key, 'mesh/obj/v1', ref, ['vertex'],
415
+ locator(paths['cad'], name), unit='m', valid=True,
416
+ scale_applied_to_mesh=False, dimensions_semantics='source_unspecified')
417
+ asset_refs.append(ref)
418
+ if definition['cad'].startswith('articulated/'):
419
+ part_id = 'asset_' + asset_key
420
+ objects[primary].setdefault('parts', {})[part_id] = dict(part_id=part_id,
421
+ parent_id=None, has_model=True, mesh_ref=ref, source_asset=relative,
422
+ note='Source asset; correspondence to motion part labels remains unverified')
423
+ for asset_ref in asset_refs:
424
+ mesh_check = check_mesh(view.path / asset_ref, asset_dir)
425
+ view.build['validation'].append({'component': asset_ref, **mesh_check,
426
+ 'unit_basis': 'official ObjTracking loads source canonical CAD without scaling in metre camera coordinates',
427
+ 'geometric_acceptance': 'physical dimensions-to-mesh relation remains source_unspecified'})
428
+ metadata_path = view.path / f'annotation/object/{primary}/metainfo.json'
429
+ metadata = json.loads(metadata_path.read_text())
430
+ metadata.update(has_model=bool(asset_refs), asset_refs=asset_refs)
431
+ if definition['cad'].startswith('rigid/') and len(asset_refs) == 1:
432
+ metadata['mesh_ref'] = asset_refs[0]
433
+ json_write(metadata_path, metadata)
434
+ if definition['cad'].startswith('articulated/'):
435
+ view.build['unresolved'].append({'component': 'object_part_asset_association',
436
+ 'status': 'source_semantics_unverified',
437
+ 'reason': 'All source assets and motion labels retained, but no guessed correspondence or joint_state'})
438
+ for entity, info in objects.items():
439
+ if 'parts' in info:
440
+ ref = f'annotation/object/{entity}/articulation.json'
441
+ json_write(view.path / ref, {'parts': list(info['parts'].values()), 'joints': [],
442
+ 'hierarchy_semantics': 'semantic_containment',
443
+ 'note': 'Unassociated source region, motion and asset nodes; original CAD trees retained in assets'})
444
+ view.component('articulation_' + entity, 'object/articulated/v1', ref, [], loc)
445
+ meta_path = view.path / f'annotation/object/{entity}/metainfo.json'
446
+ metadata = json.loads(meta_path.read_text())
447
+ metadata['articulation_ref'] = ref
448
+ json_write(meta_path, metadata)
449
+ if depth is not None:
450
+ dpath, dloc = depth
451
+ dmeta = probe(dpath)
452
+ if [dmeta['width'], dmeta['height']] != view.meta['camera']['image_size']:
453
+ raise ValueError('HOI4D depth grid differs from RGB')
454
+ if dmeta['pix_fmt'] != 'gray16le':
455
+ raise ValueError('unexpected HOI4D depth pixel format')
456
+ width, height = view.meta['camera']['image_size']
457
+ raw = work / 'depth.raw'
458
+ limits = ['-frames:v', str(n)] if args.max_frames else []
459
+ run(decode_args(dpath, 'gray16le') + limits + ['-y', str(raw)])
460
+ if raw.stat().st_size != n * width * height * 2:
461
+ raise ValueError('depth/RGB frame count or grid mismatch')
462
+ def depths():
463
+ with raw.open('rb') as inp:
464
+ for _ in range(n):
465
+ yield np.frombuffer(inp.read(width * height * 2), '<u2').reshape(height, width).astype(np.float32) / 1000
466
+ view.raster('depth', depths(), None, dloc | {'conversion': 'registered millimetre camera-Z to metres'})
467
+ else:
468
+ view.absent('depth', 'No matching source depth video was found',
469
+ 'source_missing' if find_file(args.root, 'DEPTH') else 'not_downloaded')
470
+ return view.finish()
471
+
472
+
473
+ def main(argv=None):
474
+ p = parser('HOI4D', __doc__)
475
+ p.add_argument('--tasks', help='Comma-separated substrings of source sequence paths')
476
+ p.add_argument('--sessions', help='Comma-separated sessions')
477
+ p.add_argument('--categories', help='Comma-separated category numbers')
478
+ args = p.parse_args(argv)
479
+ if args.views and args.views != 'ego':
480
+ p.error('HOI4D source camera ID is ego')
481
+ paths = {key: find_file(args.root, name) for key, name in {
482
+ 'release': 'HOI4D_release.zip', 'annotations': 'HOI4D_annotations.zip', 'hand': 'HOI4D_Hand_pose.zip',
483
+ 'camera': 'camera_params.zip', 'cad': 'HOI4D_CAD_Model_for_release.zip'}.items()}
484
+ if not paths['release'] or not paths['annotations']:
485
+ p.error('HOI4D release and annotation ZIPs are required')
486
+ out = release(args, 'HOI4D')
487
+ models = mano_models(args.mano_dir)
488
+ with ExitStack() as stack, tempfile.TemporaryDirectory(prefix='hoi4d-depth-') as wd:
489
+ archives = {key: stack.enter_context(zipfile.ZipFile(path)) if path else None for key, path in paths.items()}
490
+ sequences = sorted(name.removeprefix('HOI4D_release/').removesuffix('/align_rgb/image.mp4')
491
+ for name in archives['release'].namelist() if name.endswith('/align_rgb/image.mp4'))
492
+ if args.tasks:
493
+ sequences = [s for s in sequences if any(token in s for token in args.tasks.split(','))]
494
+ if args.sessions:
495
+ sequences = [s for s in sequences if s.split('/')[0] in args.sessions.split(',')]
496
+ if args.categories:
497
+ sequences = [s for s in sequences if re.search(r'/C(\d+)/', s)[1] in args.categories.split(',')]
498
+ if args.limit:
499
+ sequences = sequences[:args.limit]
500
+ if not sequences:
501
+ p.error('no matching source sequences')
502
+ depths, _ = extract_depths(args.root, sequences, Path(wd))
503
+ for seq in sequences:
504
+ name = seq.replace('/', '_')
505
+ with sequence_dir(out, name) as target:
506
+ report = convert_sequence(seq, args, target / 'ego', archives['release'], archives['annotations'],
507
+ archives['hand'], archives['camera'], archives['cad'], paths, models, depths.get(seq))
508
+ build_record(out, name, {'ego': report})
509
+ print(f'Converted {seq}', flush=True)
510
+ return 0
511
+
512
+
513
+ if __name__ == '__main__':
514
+ raise SystemExit(main())
515
+
516
+ # TODO(v2.0): 旧 bbox IoU 实例重分配属于推断,注释保留,不在 v1.0 执行。
517
+ # # 同类多实例(C8 双桶 / C2 双杯):2dBox 可用时按 IoU 复核归属
518
+ # cls = next(x[3] for x in cat["groups"] if x[0] == gk)
519
+ # sibs = [g for g in cat["groups"]
520
+ # if g[0] != gk and cls is not None and g[3] == cls]
521
+ # box = (d.get("2dBox") or {}).get("camera1")
522
+ # box = (box[0][0], box[0][1], box[1][0], box[1][1]) \
523
+ # if box and len(box) == 2 else None
524
+ # if box is not None and sibs:
525
+ # gvals = next(x[1] for x in cat["groups"] if x[0] == gk)
526
+ # best, best_iou = gk, box_iou(box, bbox_of(mask, gvals))
527
+ # for s in sibs:
528
+ # if ("obj", s[0]) not in tid_of_group:
529
+ # continue
530
+ # i = box_iou(box, bbox_of(mask, s[1]))
531
+ # if i > best_iou + 0.1 and i > 0.15:
532
+ # best, best_iou = s[0], i
533
+ # if best != gk:
534
+ # gk, iou_fixups = best, iou_fixups + 1
dex-ycb/shared-v1.0/script/convert_visor_v1.0.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """VISOR source polygons and contact → CONTRACT.md v1.0, without rasterization or side inference."""
3
+ from collections import Counter
4
+ import hashlib
5
+ import json
6
+ import re
7
+ import shutil
8
+ import tempfile
9
+ from pathlib import Path
10
+ import zipfile
11
+
12
+ import numpy as np
13
+ import torch
14
+
15
+ from warehouse_v1_0 import (View, build_record, find_file, jsonl_write, locator, parser,
16
+ release, roots, sequence_dir, source)
17
+
18
+ FRAME = re.compile(r'frame_(\d+)')
19
+ HAND = {300: 'left', 301: 'right'}
20
+ GLOVE = {303: 'left', 304: 'right'}
21
+ STATES = {'hand-not-in-contact': 'negative', 'glove-not-in-contact': 'negative',
22
+ 'none-of-the-above': 'target_unannotated', 'inconclusive': 'unknown'}
23
+
24
+
25
+ def hand_side(ann):
26
+ if ann['class_id'] in HAND:
27
+ return HAND[ann['class_id']]
28
+ if ann['class_id'] not in (60, 303, 304):
29
+ return None
30
+ raw = ann.get('on_which_hand')
31
+ raw = raw if isinstance(raw, list) else [raw]
32
+ sides = set()
33
+ for item in raw:
34
+ if item == 'left hand':
35
+ sides.add('left')
36
+ if item in ('right hand', 'rigth hand'):
37
+ sides.add('right')
38
+ if len(sides) == 1:
39
+ return next(iter(sides))
40
+ if not sides and ann['class_id'] in GLOVE:
41
+ return GLOVE[ann['class_id']]
42
+ return None
43
+
44
+
45
+ def convert_video(video, split, annotation, ann_loc, rgb_zip, rgb_loc, mapping, args, target):
46
+ indexed = sorted(enumerate(annotation['video_annotations']), key=lambda row: int(FRAME.search(row[1]['image']['name'])[1]))
47
+ if args.max_frames:
48
+ indexed = indexed[:args.max_frames]
49
+ if len({row['image']['name'] for _, row in indexed}) != len(indexed):
50
+ raise ValueError('duplicate VISOR frame')
51
+ keys = lambda row, ann: (row['image']['subsequence'], ann['class_id'], ann['name'])
52
+ collisions = set()
53
+ for _, row in indexed:
54
+ collisions.update(key for key, number in Counter(keys(row, a) for a in row['annotations']).items() if number > 1)
55
+ frames, paths = [], []
56
+ with tempfile.TemporaryDirectory(prefix='visor-rgb-') as wd, zipfile.ZipFile(rgb_zip) as z:
57
+ work = Path(wd)
58
+ for original_index, row in indexed:
59
+ name = row['image']['name']
60
+ data = z.read(name)
61
+ path = work / Path(name).name
62
+ path.write_bytes(data)
63
+ paths.append(path)
64
+ loc = rgb_loc | {'nested_member': name, 'sha256': hashlib.sha256(data).hexdigest()}
65
+ frames.append(dict(source_frame_id=int(FRAME.search(name)[1]), source_locator=loc,
66
+ source_image=row['image'], original_frame_name=mapping.get(name),
67
+ annotation_matches={'segment': dict(source_frame_id=name, source_timestamp_ns=None,
68
+ clock_domain=None, match_method='index_map', delta_ns=None,
69
+ source_locator=ann_loc | {'record': f'video_annotations[{original_index}]'})}))
70
+ view = View(target, 'EPIC-KITCHENS-VISOR', args.release_id, video, 'ego', frames, sampling='sparse', split=split)
71
+ view.valid_rules = {
72
+ 'segment': 'Selected sparse annotation frame present; all source polygons finite with at least three vertices and entity mapping valid',
73
+ 'relations': 'At least one source in_contact_object value present; positive targets resolve in the same frame; unknown is an explicit usable status',
74
+ }
75
+ view.full_jpeg = getattr(args, 'jpeg_full_check', False)
76
+ view.meta.update(view_type='ego', split_scheme='VISOR_GroundTruth_SparseAnnotations', split_source_locator=ann_loc)
77
+ view.meta['sampling']['selection'] = {'representation': 'official sparse annotations', 'max_frames': args.max_frames}
78
+ view.rgb(paths, rgb_loc)
79
+ entities = {}
80
+ polygons, mappings, relations, relation_valid = [], [], [], []
81
+ for f, (original_index, row) in enumerate(indexed):
82
+ frame_loc = ann_loc | {'record': f'video_annotations[{original_index}]'}
83
+ id_map, labels, polys = {}, [], []
84
+ for code, ann in enumerate(row['annotations'], 1):
85
+ if code >= 65535:
86
+ raise ValueError('too many source instances')
87
+ sid = ann['id']
88
+ if sid in id_map:
89
+ raise ValueError('duplicate source instance ID within a frame')
90
+ side = hand_side(ann)
91
+ if side is not None:
92
+ entity = 'hand_' + side
93
+ else:
94
+ key = keys(row, ann)
95
+ identity = key + (sid, row['image']['name']) if key in collisions else key
96
+ entity = 'object_' + hashlib.sha256(json.dumps(identity).encode()).hexdigest()[:20]
97
+ if entity not in entities:
98
+ scope = 'frame' if key in collisions else 'subsequence'
99
+ scope_id = f'{video}:{row["image"]["name"]}' if scope == 'frame' else f'{video}:{key[0]}'
100
+ view.object(entity, frame_loc | {'source_instance_id': sid}, scope, scope_id,
101
+ category_id=ann['class_id'], name=ann['name'],
102
+ association_basis='source_frame_instance' if scope == 'frame' else 'official_subsequence_entity_name')
103
+ entities[entity] = True
104
+ id_map[sid] = entity
105
+ for polygon in ann.get('segments', []):
106
+ p = np.asarray(polygon)
107
+ if p.ndim != 2 or p.shape[1] != 2 or len(p) < 3 or not np.isfinite(p).all():
108
+ raise ValueError(f'invalid source polygon {sid}')
109
+ polys.append(dict(mask_value=code, polygons=ann.get('segments', [])))
110
+ labels.append(dict(mask_value=code, category_id=ann['class_id'], entity_id=entity,
111
+ part_id=None, source_instance_id=sid,
112
+ source_attributes={k: v for k, v in ann.items() if k != 'segments'}))
113
+ rr = []
114
+ provided = False
115
+ for ann in row['annotations']:
116
+ raw = ann.get('in_contact_object')
117
+ values = raw if isinstance(raw, list) else [raw]
118
+ for value in values:
119
+ if value is None:
120
+ continue
121
+ provided = True
122
+ status = STATES.get(value)
123
+ obj = None
124
+ if status is None:
125
+ if value not in id_map:
126
+ raise ValueError(f'unresolved source contact target {value} in {video} frame {f}')
127
+ status, obj = 'positive', id_map[value]
128
+ rr.append(dict(relation_type='contact', subject_id=id_map[ann['id']], object_id=obj,
129
+ status=status, source_value=value, source_locator=frame_loc | {'source_instance_id': ann['id']},
130
+ provenance=source('Resolve source contact ID against instances in this frame')))
131
+ polygons.append(dict(frame_index=f, instances=polys))
132
+ mappings.append(dict(frame_index=f, labels=labels))
133
+ relations.append(dict(frame_index=f, relations=rr))
134
+ relation_valid.append(provided)
135
+ jsonl_write(view.path / 'annotation/segment/polygons.jsonl', polygons)
136
+ jsonl_write(view.path / 'annotation/segment/instances.jsonl', mappings)
137
+ torch.save(torch.ones(len(frames), dtype=torch.bool, device='cpu'), view.path / 'annotation/segment/mask_valid.pt')
138
+ view.component('segment', 'segment/instance_polygons/v1', 'annotation/segment/polygons.jsonl', ['T'], ann_loc,
139
+ valid_ref='annotation/segment/mask_valid.pt', valid_axes=['T'], segmentation_type='instance',
140
+ mapping_ref='annotation/segment/instances.jsonl', coverage={'kind': 'unknown', 'exhaustive_ref': 'annotation/segment/instances.jsonl'})
141
+ view.relations(relations, relation_valid, ann_loc)
142
+ for component in ('depth', 'mano', 'keypoints_uv', 'keypoints_xyz', 'intrinsic', 'extrinsic'):
143
+ view.absent(component, 'Not provided by VISOR sparse source annotations')
144
+ return view.finish()
145
+
146
+
147
+ def main(argv=None):
148
+ p = parser('EPIC-KITCHENS-VISOR', __doc__)
149
+ p.add_argument('--videos', help='Comma-separated video names')
150
+ p.add_argument('--splits', default='train,val')
151
+ args = p.parse_args(argv)
152
+ wanted = set(args.videos.split(',')) if args.videos else None
153
+ splits = set(args.splits.split(','))
154
+ if not splits <= {'train', 'val'}:
155
+ p.error('only annotated train/val splits are available')
156
+ out = release(args, 'EPIC-KITCHENS-VISOR')
157
+ archive = find_file(args.root, 'EPIC-KITCHENS VISOR.zip')
158
+ with tempfile.TemporaryDirectory(prefix='visor-source-') as wd:
159
+ work = Path(wd)
160
+ if archive:
161
+ with zipfile.ZipFile(archive) as z:
162
+ suffix = 'GroundTruth-SparseAnnotations/annotations/'
163
+ members = [n for n in z.namelist() if suffix in n and n.endswith('.json')]
164
+ prefix = members[0].split(suffix)[0]
165
+ fm = json.loads(z.read(prefix + 'frame_mapping.json'))
166
+ done = 0
167
+ for member in sorted(members):
168
+ split, filename = member.split(suffix)[1].split('/')
169
+ video = Path(filename).stem
170
+ if split not in splits or wanted and video not in wanted:
171
+ continue
172
+ data = z.read(member)
173
+ rgb_member = prefix + f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip'
174
+ rgb_zip = work / (video + '.zip')
175
+ with z.open(rgb_member) as inp, rgb_zip.open('wb') as dest:
176
+ shutil.copyfileobj(inp, dest)
177
+ with sequence_dir(out, video) as dest:
178
+ report = convert_video(video, split, json.loads(data), locator(archive, member, data),
179
+ rgb_zip, locator(archive, rgb_member), fm.get(video, {}), args, dest / 'ego')
180
+ build_record(out, video, {'ego': report})
181
+ rgb_zip.unlink()
182
+ done += 1
183
+ print(f'Converted {video}', flush=True)
184
+ if args.limit and done >= args.limit:
185
+ break
186
+ else:
187
+ root = next((r for r in roots(args.root) if (r / 'GroundTruth-SparseAnnotations').is_dir()), None)
188
+ if root is None:
189
+ p.error('VISOR outer ZIP or extracted source directory not found')
190
+ fm = json.loads((root / 'frame_mapping.json').read_text()) if (root / 'frame_mapping.json').exists() else {}
191
+ done = 0
192
+ for split in sorted(splits):
193
+ for ann in sorted((root / 'GroundTruth-SparseAnnotations/annotations' / split).glob('*.json')):
194
+ video = ann.stem
195
+ if wanted and video not in wanted:
196
+ continue
197
+ rgb = root / f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip'
198
+ with sequence_dir(out, video) as dest:
199
+ report = convert_video(video, split, json.loads(ann.read_text()), locator(ann), rgb,
200
+ locator(rgb), fm.get(video, {}), args, dest / 'ego')
201
+ build_record(out, video, {'ego': report})
202
+ done += 1
203
+ if args.limit and done >= args.limit:
204
+ return 0
205
+ if not done:
206
+ p.error('no matching annotated videos found')
207
+ return 0
208
+
209
+
210
+ if __name__ == '__main__':
211
+ raise SystemExit(main())
212
+
213
+ # TODO(v2.0): 旧距离猜侧和单层掩码生成仅注释保留;v1.0 不执行。
214
+ # if side is None and len(frame_hands) == 1:
215
+ # # 空间门槛:脱下放在远处的手套不并入(实测双峰 0..25px / ≥44px)
216
+ # hb = frame_hands[0][1]
217
+ # gb = _bbox_of(polys)
218
+ # if hb and gb and _bbox_dist(gb, hb) <= GLOVE60_MERGE_BBOX_DIST:
219
+ # side = frame_hands[0][0]
220
+ # stats["glove60_merged_into_sole_hand"] += 1
221
+ # if side is None:
222
+ # stats["dropped_glove60_unresolved"] += 1
223
+ # id_disp[mid] = ("dropped", "glove60")
224
+ # continue
225
+ # def rasterize_and_encode(vdir, frames, frame_draw, zip_path, n, stats):
226
+ # """流式读 zip 内 jpg + 光栅化多边形 → rgb.mkv / mask.mkv;返回 (w, h)。"""
227
+ # from PIL import Image, ImageDraw
228
+ #
229
+ # with zipfile.ZipFile(zip_path) as zf:
230
+ # member_of = {}
231
+ # for nm in zf.namelist():
232
+ # member_of[os.path.basename(nm)] = nm
233
+ # names = [im["name"] for im in frames]
234
+ # missing = [nm for nm in names if nm not in member_of]
235
+ # if missing:
236
+ # raise RuntimeError(f"{len(missing)} annotated frames missing in zip, "
237
+ # f"e.g. {missing[:3]}")
238
+ # stats["zip_extra_members"] = len(member_of) - len(names)
239
+ #
240
+ # # 首帧定分辨率(官方 1920×1080,实测每帧校验)
241
+ # img0 = Image.open(io.BytesIO(zf.read(member_of[names[0]]))).convert("RGB")
242
+ # w, h = img0.size
243
+ #
244
+ # bin_img = Image.new("L", (w, h), 0)
245
+ # bin_draw = ImageDraw.Draw(bin_img)
246
+ # canvas = np.zeros((h, w), np.uint16)
247
+ # with VideoPipe(vdir / "mask.mkv", w, h, FPS, "mask") as mw, \
248
+ # VideoPipe(vdir / "rgb.mkv", w, h, FPS, "rgb") as rw:
249
+ # for f in range(n):
250
+ # canvas[:] = 0
251
+ # for pid, polys in frame_draw[f]:
252
+ # bin_draw.rectangle((0, 0, w, h), fill=0)
253
+ # for poly in polys:
254
+ # bin_draw.polygon([(float(x), float(y)) for x, y in poly], fill=255)
255
+ # arr = np.asarray(bin_img)
256
+ # canvas[arr > 0] = pid # 后画覆盖先画:物体→手(modal)
257
+ # mw.write(canvas)
258
+ # img = img0 if f == 0 else Image.open(
259
+ # io.BytesIO(zf.read(member_of[names[f]]))).convert("RGB")
260
+ # if img.size != (w, h):
261
+ # raise RuntimeError(f"frame {names[f]}: size {img.size} != {(w, h)}")
262
+ # rw.write(np.asarray(img))
263
+ # n_mask, n_rgb = mw.n, rw.n
264
+ # if (n_rgb, n_mask) != (n, n):
265
+ # raise RuntimeError(f"wrote rgb={n_rgb} mask={n_mask} != {n}")
266
+ # got = (count_frames(vdir / "rgb.mkv"), count_frames(vdir / "mask.mkv"))
267
+ # if got != (n, n):
268
+ # raise RuntimeError(f"encoded rgb={got[0]} mask={got[1]} != {n} (decode verify)")
269
+ # return w, h
270
+ #
271
+ #
dex-ycb/shared-v1.0/script/render_dexycb_validation.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Audit a finished Dex-YCB release and render persisted modalities for manual review."""
3
+ from collections import Counter
4
+ import hashlib
5
+ import json
6
+ from pathlib import Path
7
+ import sys
8
+
9
+ from render_hoi4d_validation import render
10
+
11
+
12
+ def inspect(root):
13
+ data, doc, scripts = root / 'data', root / 'doc', root / 'script'
14
+ sequences = sorted(p for p in data.iterdir() if p.is_dir())
15
+ assert len(sequences) == 1000, f'expected 1000 sequences, got {len(sequences)}'
16
+ assert len(list(doc.glob('*.build.json'))) == 1000
17
+ assert not list(data.glob('*.tmp-*')), 'unfinished temporary sequences'
18
+ config = json.loads((scripts / 'config.json').read_text())
19
+ assert all(config.get(k) is None for k in ('limit', 'max_frames', 'subjects', 'views'))
20
+ hashes = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in scripts.glob('*.py')}
21
+ subjects, splits, availability = Counter(), Counter(), Counter()
22
+ selected = []
23
+ for seq in sequences:
24
+ views = sorted(p for p in seq.iterdir() if p.is_dir())
25
+ assert len(views) == 8, (seq, len(views))
26
+ build = json.loads((doc / (seq.name + '.build.json')).read_text())
27
+ assert set(build['views']) == {p.name for p in views}, seq
28
+ assert all(hashes.get(k) == v for k, v in build['scripts'].items()), seq
29
+ subject = seq.name.split('_')[0]
30
+ subjects[subject] += 1
31
+ if subjects[subject] == 1:
32
+ selected.append(views[0])
33
+ if subject.endswith('subject-09'):
34
+ selected.append(views[-1]) # one more camera, different camera
35
+ if seq.name == '20201015-subject-09_20201015_150838':
36
+ selected.append(views[0]) # source-labelled left-hand sequence
37
+ for view in views:
38
+ meta = json.loads((view / 'metainfo.json').read_text())
39
+ assert meta['sequence_id'] == seq.name and meta['camera_id'] == view.name, view
40
+ assert meta['dataset_id'] == 'dex-ycb' and meta['release_id'] == 'shared-v1.0', view
41
+ assert meta['num_frames'] > 0 and meta.get('view_type') == 'exo', view
42
+ assert (view / 'camera/frames.jsonl').is_file(), view
43
+ assert meta['components']['rgb']['available'], view
44
+ splits[meta['split']] += 1
45
+ for key, part in meta['components'].items():
46
+ if part.get('available'):
47
+ availability[key] += 1
48
+ for ref in ('data_ref', 'valid_ref'):
49
+ if part.get(ref):
50
+ assert (view / part[ref]).is_file(), (view, key, ref)
51
+ assert len(subjects) == 10 and set(subjects.values()) == {100}, subjects
52
+ assert availability['depth'] == availability['rgb'] == 8000, availability
53
+ report = dict(sequences=len(sequences), views=sum(splits.values()), subjects=dict(subjects),
54
+ splits=dict(splits), available_views=dict(availability), config=config,
55
+ published_script_sha256=hashes, sampled_views=[str(v.relative_to(root)) for v in selected],
56
+ scope='Structure and file refs checked for all views; persisted QC and HTML only for sampled views. No manual visual approval yet.')
57
+ destination = doc / 'validation'
58
+ destination.mkdir(exist_ok=True)
59
+ (destination / 'STRUCTURAL_AUDIT.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
60
+ for view in selected:
61
+ render(view, destination)
62
+ return report
63
+
64
+
65
+ if __name__ == '__main__':
66
+ print(json.dumps(inspect(Path(sys.argv[1]).expanduser().resolve()), ensure_ascii=False), flush=True)
dex-ycb/shared-v1.0/script/render_hoi4d_validation.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Standalone, offline HTML review of every persisted component in selected views."""
3
+ import argparse
4
+ import base64
5
+ import html
6
+ import io
7
+ import json
8
+ import random
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ from PIL import Image, ImageDraw
13
+ import torch
14
+
15
+ from warehouse_v1_0 import video_frames, unpack_depth, validate_view
16
+
17
+
18
+ def snapshot(video, fmt, shape, dtype, indices):
19
+ return {i: frame.copy() for i, frame in enumerate(video_frames(video, fmt, shape, dtype)) if i in indices}
20
+
21
+
22
+ def picture(image):
23
+ image.thumbnail((800, 450)) # Previews only; released tensors and videos are not resized.
24
+ output = io.BytesIO()
25
+ image.save(output, format='PNG')
26
+ return '<img loading="lazy" src="data:image/png;base64,' + base64.b64encode(output.getvalue()).decode() + '">'
27
+
28
+
29
+ def preview_color(value, dataset_id):
30
+ # Dex-YCB reserves 255 for the native hand mask. The old mod-240 palette
31
+ # gave it the same color as YCB object 15; keep data codes untouched.
32
+ if dataset_id == 'dex-ycb' and value == 255:
33
+ return (255, 32, 64)
34
+ return tuple((value * factor) % 240 + 15 for factor in (89, 61, 131))
35
+
36
+
37
+ def mesh_preview(path):
38
+ """Project the whole source asset; bound drawing cost without favoring early faces."""
39
+ vertices, faces, referenced = [], [], set()
40
+ rng = random.Random(0)
41
+ face_count = 0
42
+ with path.open(errors='replace') as stream:
43
+ for line in stream:
44
+ if line.startswith('v '):
45
+ vertices.append([float(v) for v in line.split()[1:4]])
46
+ elif line.startswith('f '):
47
+ face = []
48
+ for token in line.split()[1:]:
49
+ index = int(token.split('/')[0])
50
+ face.append(index - 1 if index > 0 else len(vertices) + index)
51
+ if len(face) < 3:
52
+ continue
53
+ referenced.update(face)
54
+ face_count += 1
55
+ # ponytail: bounded static preview; use a full OBJ viewer if 5000 faces miss fine detail.
56
+ if len(faces) < 5000:
57
+ faces.append(face)
58
+ else:
59
+ pick = rng.randrange(face_count)
60
+ if pick < len(faces):
61
+ faces[pick] = face
62
+ if not vertices or not faces:
63
+ return 'OBJ 未提供可绘制的顶点/面'
64
+ if min(referenced) < 0 or max(referenced) >= len(vertices):
65
+ raise ValueError(f'invalid OBJ face index: {path}')
66
+ xyz = np.asarray(vertices, dtype=np.float64)
67
+ if not np.isfinite(xyz).all():
68
+ raise ValueError(f'nonfinite OBJ vertex: {path}')
69
+ # Fixed orthonormal isometric basis: geometry only, not an inferred camera pose.
70
+ projected = np.column_stack(((xyz[:, 0] - xyz[:, 2]) / np.sqrt(2),
71
+ (xyz[:, 0] + xyz[:, 2] - 2 * xyz[:, 1]) / np.sqrt(6)))
72
+ used = projected[np.fromiter(referenced, dtype=np.int64)]
73
+ lo, hi = used.min(axis=0), used.max(axis=0)
74
+ extent = (hi - lo).max()
75
+ if extent <= 0:
76
+ return 'OBJ 所有面投影到同一点'
77
+ projected = (projected - (lo + hi) / 2) * (380 / extent) + 215
78
+ image = Image.new('RGB', (430, 430), 'white')
79
+ draw = ImageDraw.Draw(image)
80
+ for face in faces:
81
+ polygon = [tuple(projected[i]) for i in face]
82
+ draw.line(polygon + [polygon[0]], fill='#205caa', width=1)
83
+ return picture(image)
84
+
85
+
86
+ def render(view, destination):
87
+ meta = json.loads((view / 'metainfo.json').read_text())
88
+ n = meta['num_frames']
89
+ width, height = meta['camera']['image_size']
90
+ components = meta['components']
91
+ frames = [json.loads(line) for line in (view / 'camera/frames.jsonl').read_text().splitlines()]
92
+ assert len(frames) == n
93
+ selected = {0, n // 4, n // 2, 3 * n // 4, n - 1}
94
+ for item in components.values():
95
+ ref = item.get('valid_ref', '')
96
+ if ref.endswith('.pt'):
97
+ valid = torch.load(view / ref, map_location='cpu', weights_only=True).numpy()
98
+ if valid.shape[0] == n:
99
+ matching = np.flatnonzero(valid.reshape(n, -1).any(axis=1))
100
+ if len(matching):
101
+ selected.add(int(matching[0]))
102
+ selected = set(sorted(selected)[:12]) | {n - 1}
103
+ rgb = snapshot(view / components['rgb']['data_ref'], 'rgb24', (height, width, 3), np.uint8, selected)
104
+ depth = (snapshot(view / components['depth']['data_ref'], 'gray16le', (height, 2 * width), '<u2', selected)
105
+ if components.get('depth', {}).get('available') else {})
106
+ masks = (snapshot(view / components['segment']['data_ref'], 'gray16le', (height, width), '<u2', selected)
107
+ if components.get('segment', {}).get('available') else {})
108
+ labels = {}
109
+ mapping = view / 'annotation/segment/instances.jsonl'
110
+ if mapping.exists():
111
+ labels = {row['frame_index']: row['labels'] for row in map(json.loads, mapping.read_text().splitlines()) if row['frame_index'] in selected}
112
+ uv = components.get('keypoints_uv', {})
113
+ uv_points = torch.load(view / uv['data_ref'], map_location='cpu', weights_only=True).numpy() if uv.get('available') else None
114
+ uv_valid = torch.load(view / uv['valid_ref'], map_location='cpu', weights_only=True).numpy() if uv.get('available') else None
115
+ sections = []
116
+ for i in sorted(selected):
117
+ image = Image.fromarray(rgb[i])
118
+ if uv_points is not None:
119
+ draw = ImageDraw.Draw(image)
120
+ for slot, color in enumerate(('#00ffff', '#ff9922')):
121
+ for (x, y), valid in zip(uv_points[i, slot], uv_valid[i, slot], strict=True):
122
+ if valid and np.isfinite([x, y]).all():
123
+ draw.ellipse((x - 3, y - 3, x + 3, y + 3), fill=color)
124
+ panels = ['<figure>' + picture(image) + '<figcaption>RGB + 原生 2D 手关键点(若有)</figcaption></figure>']
125
+ if i in depth:
126
+ z = unpack_depth(depth[i])
127
+ luminance = (np.clip(np.nan_to_num(z, nan=0), 0, 3) * 85).astype(np.uint8)
128
+ panels.append('<figure>' + picture(Image.fromarray(luminance)) + '<figcaption>深度 Z(黑=无效,白≥3 m;仅预览)</figcaption></figure>')
129
+ if i in masks:
130
+ mask = masks[i]
131
+ colors = np.zeros((*mask.shape, 3), dtype=np.uint8)
132
+ for value in np.unique(mask):
133
+ if value not in (0, 65535):
134
+ colors[mask == value] = preview_color(int(value), meta['dataset_id'])
135
+ 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))
136
+ panels.append('<figure>' + picture(Image.fromarray(colors)) + '<figcaption>原生分割整数编码的伪彩色预览(' + html.escape(legend) + ')</figcaption></figure>')
137
+ active = (mask != 0) & (mask != 65535)
138
+ overlay = rgb[i].copy()
139
+ overlay[active] = ((overlay[active].astype(np.uint16) + colors[active]) // 2).astype(np.uint8)
140
+ panels.append('<figure>' + picture(Image.fromarray(overlay)) + '<figcaption>原生分割叠加 RGB(仅预览)</figcaption></figure>')
141
+ details = {'frame': frames[i], 'segment_labels': labels.get(i, [])}
142
+ for name, component in components.items():
143
+ ref = component.get('data_ref', '')
144
+ if component.get('available') and ref.endswith('.pt'):
145
+ values = torch.load(view / ref, map_location='cpu', weights_only=True)
146
+ if values.ndim and values.shape[0] == n:
147
+ details[name] = {'value': values[i].tolist()}
148
+ if component.get('valid_ref', '').endswith('.pt'):
149
+ valid = torch.load(view / component['valid_ref'], map_location='cpu', weights_only=True)
150
+ details[name]['valid'] = valid[i].tolist()
151
+ sections.append('<section><h2>帧 ' + str(i) + ' / ' + str(n) + '</h2><div class="panels">' + ''.join(panels)
152
+ + '</div><details><summary>帧号、来源、全部数值组件与有效性</summary><pre>'
153
+ + html.escape(json.dumps(details, ensure_ascii=False, indent=2)) + '</pre></details></section>')
154
+ assets = []
155
+ for name, component in components.items():
156
+ if component.get('available') and component['data_ref'].lower().endswith('.obj'):
157
+ ref = component['data_ref']
158
+ assets.append('<figure><h3>' + html.escape(name) + '</h3>' + mesh_preview(view / ref)
159
+ + '<figcaption>仅展示网格原生形状;未验证尺度/位姿对应。</figcaption></figure>')
160
+ result = validate_view(view)
161
+ destination.mkdir(parents=True, exist_ok=True)
162
+ title = view.parent.name + '_' + view.name
163
+ 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}'
164
+ page = '<!doctype html><html lang="zh"><meta charset="utf-8"><title>' + html.escape(title) + '</title><style>' + css + '</style><h1>' + html.escape(title) + '</h1><p>预览图仅供人工审核,不是训练输入;未提供的模态在 metainfo 中保留原因。</p>' + ''.join(sections) + '<h2>原始物体模型(独立预览)</h2><div class="panels">' + ''.join(assets) + '</div><details><summary>全部组件元信息及原始来源</summary><pre>' + html.escape(json.dumps(meta, ensure_ascii=False, indent=2)) + '</pre></details><details><summary>持久化 QC 结果</summary><pre>' + html.escape(json.dumps(result, ensure_ascii=False, indent=2)) + '</pre></details></html>'
165
+ (destination / (title + '.html')).write_text(page)
166
+ (destination / (title + '.report.json')).write_text(json.dumps(result, ensure_ascii=False, indent=2))
167
+ links = sorted(p.name for p in destination.glob('*.html') if p.name != 'index.html')
168
+ (destination / 'index.html').write_text('<!doctype html><html lang="zh"><meta charset="utf-8"><title>' + html.escape(meta['dataset_id']) + ' review</title><h1>' + html.escape(meta['dataset_id']) + ' 抽样人工审核</h1><p>选择视图;所有预览均来自已保存的 shared 数据。</p><ul>' + ''.join('<li><a href="' + html.escape(x, quote=True) + '">' + html.escape(x) + '</a></li>' for x in links) + '</ul></html>')
169
+ print(destination / (title + '.html'), 'selected_frames', sorted(selected), flush=True)
170
+
171
+
172
+ def main():
173
+ p = argparse.ArgumentParser(description=__doc__)
174
+ p.add_argument('views', nargs='+', type=Path)
175
+ p.add_argument('--out', type=Path)
176
+ args = p.parse_args()
177
+ for view in args.views:
178
+ render(view, args.out or view.parents[2] / 'doc/validation')
179
+
180
+
181
+ if __name__ == '__main__':
182
+ main()
dex-ycb/shared-v1.0/script/warehouse_v1_0.py ADDED
@@ -0,0 +1,922 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared I/O for CONTRACT.md v1.0. No annotation synthesis."""
2
+ import argparse
3
+ from contextlib import contextmanager
4
+ from functools import lru_cache
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import shlex
9
+ from pathlib import Path
10
+ import pickle
11
+ import random
12
+ import shutil
13
+ import subprocess
14
+ import tempfile
15
+ import time
16
+
17
+ import numpy as np
18
+ from PIL import Image
19
+ import torch
20
+
21
+ SCHEMA_PATH = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/schema.json',
22
+ Path(__file__).resolve().parents[1] / 'doc/schema.json') if p.is_file())
23
+ SCHEMA = json.loads(SCHEMA_PATH.read_text())
24
+ RAW_ROOT = Path.home() / 'Datasets/Hand-Datasets-Raw'
25
+
26
+
27
+ def json_write(path, value):
28
+ path = Path(path)
29
+ path.parent.mkdir(parents=True, exist_ok=True)
30
+ path.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + '\n')
31
+
32
+
33
+ def jsonl_write(path, rows):
34
+ path = Path(path)
35
+ path.parent.mkdir(parents=True, exist_ok=True)
36
+ with path.open('w') as out:
37
+ for row in rows:
38
+ out.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + '\n')
39
+
40
+
41
+ def sha256(path):
42
+ with Path(path).open('rb') as f:
43
+ return hashlib.file_digest(f, 'sha256').hexdigest()
44
+
45
+
46
+ def locator(path, member=None, data=None, **extra):
47
+ result = {'file': str(Path(path).resolve())}
48
+ if member is not None:
49
+ result['member'] = member
50
+ if data is not None:
51
+ result['sha256'] = hashlib.sha256(data).hexdigest()
52
+ return result | extra
53
+
54
+
55
+ def source(method='Copy source annotation; normalize storage only'):
56
+ return {'kind': 'format_conversion', 'method': method}
57
+
58
+
59
+ def run(args, **kwargs):
60
+ return subprocess.run(args, check=True, stderr=subprocess.PIPE, **kwargs)
61
+
62
+
63
+ @lru_cache(maxsize=1)
64
+ def ffversion():
65
+ return run(['ffmpeg', '-version'], stdout=subprocess.PIPE).stdout.decode().splitlines()[0]
66
+
67
+
68
+ def probe(path):
69
+ return json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0',
70
+ '-show_streams', '-of', 'json', str(path)],
71
+ stdout=subprocess.PIPE).stdout)['streams'][0]
72
+
73
+
74
+ def decode_args(path, pixel_format):
75
+ return ['ffmpeg', '-v', 'error', '-nostdin', '-threads', '1', '-noautorotate',
76
+ '-i', str(path), '-map', '0:v:0', '-vsync', '0', '-threads', '1',
77
+ '-f', 'rawvideo', '-pix_fmt', pixel_format]
78
+
79
+
80
+ def decoded_digest(path, pixel_format):
81
+ start = time.monotonic()
82
+ with tempfile.TemporaryFile() as err:
83
+ proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'],
84
+ stdout=subprocess.PIPE, stderr=err)
85
+ digest, size = hashlib.sha256(), 0
86
+ with proc.stdout:
87
+ while chunk := proc.stdout.read(1024 * 1024):
88
+ digest.update(chunk)
89
+ size += len(chunk)
90
+ if proc.wait():
91
+ err.seek(0)
92
+ raise RuntimeError(err.read().decode(errors='replace'))
93
+ return digest.hexdigest(), size, time.monotonic() - start
94
+
95
+
96
+ def video_frames(path, pixel_format, shape, dtype):
97
+ frame_bytes = int(np.prod(shape)) * np.dtype(dtype).itemsize
98
+ with tempfile.TemporaryFile() as err:
99
+ proc = subprocess.Popen(decode_args(path, pixel_format) + ['pipe:1'], stdout=subprocess.PIPE, stderr=err)
100
+ completed = False
101
+ try:
102
+ while True:
103
+ data = proc.stdout.read(frame_bytes)
104
+ if not data:
105
+ break
106
+ if len(data) != frame_bytes:
107
+ raise ValueError('truncated decoded video frame')
108
+ yield np.frombuffer(data, dtype=dtype).reshape(shape)
109
+ if proc.wait():
110
+ err.seek(0)
111
+ raise ValueError(err.read().decode(errors='replace'))
112
+ completed = True
113
+ finally:
114
+ proc.stdout.close()
115
+ if not completed and proc.poll() is None:
116
+ proc.terminate()
117
+ proc.wait()
118
+
119
+
120
+ def storage(path, profile, parameters, source_lossy):
121
+ info = probe(path)
122
+ if info['codec_name'] == 'h264':
123
+ frames = json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0',
124
+ '-show_entries', 'frame=key_frame', '-of', 'json', str(path)], stdout=subprocess.PIPE).stdout)['frames']
125
+ parameters = parameters | {'keyframe_indices': [i for i, f in enumerate(frames) if f['key_frame']]}
126
+ return {'profile': profile, 'codec': info['codec_name'],
127
+ 'pixel_format': info['pix_fmt'], 'encoded_size': [info['width'], info['height']],
128
+ 'decoder': {'name': 'ffmpeg', 'version': ffversion(), 'autorotate': False,
129
+ 'color_space': info.get('color_space', 'unknown'),
130
+ 'color_range': info.get('color_range', 'unknown'),
131
+ 'color_primaries': info.get('color_primaries', 'unknown'),
132
+ 'color_transfer': info.get('color_transfer', 'unknown')},
133
+ 'encoder_parameters': {'version': ffversion()} | parameters,
134
+ 'source_lossy': source_lossy, 'storage_fps': 30, 'timebase_role': 'index_only'}
135
+
136
+
137
+ def encode_raw(raw, target, width, height, pixel_format, profile, codec='ffv1', extra=()):
138
+ start = time.monotonic()
139
+ run(['ffmpeg', '-v', 'error', '-nostdin', '-y', '-f', 'rawvideo',
140
+ '-pixel_format', pixel_format, '-video_size', f'{width}x{height}', '-framerate', '30',
141
+ '-i', str(raw), '-an', '-c:v', codec, '-threads', '1', *extra, str(target)])
142
+ digest, size, decode_seconds = decoded_digest(target, pixel_format)
143
+ if size != Path(raw).stat().st_size or digest != sha256(raw):
144
+ raise ValueError(f'lossless roundtrip failed: {target}')
145
+ config = storage(target, profile, {'name': codec, 'arguments': list(extra)}, False)
146
+ return config, {'bytes': target.stat().st_size, 'encode_seconds': time.monotonic() - start - decode_seconds,
147
+ 'decode_seconds': decode_seconds, 'decoded_sha256': digest, 'all_frames_exact': True}
148
+
149
+
150
+ def measure_rgb_access(video, raw, width, height, count):
151
+ index = count // 2
152
+ start = time.monotonic()
153
+ data = run(['ffmpeg', '-v', 'error', '-nostdin', '-threads', '1', '-noautorotate',
154
+ '-i', str(video), '-vf', f'select=eq(n\\,{index})', '-frames:v', '1', '-threads', '1',
155
+ '-f', 'rawvideo', '-pix_fmt', 'rgb24', 'pipe:1'], stdout=subprocess.PIPE).stdout
156
+ with raw.open('rb') as inp:
157
+ inp.seek(index * width * height * 3)
158
+ if data != inp.read(width * height * 3):
159
+ raise ValueError('exact indexed RGB read failed')
160
+ return {'random_access_strategy': 'decode from first keyframe; select exact presentation index',
161
+ 'random_frame_index': index, 'random_frame_read_seconds': time.monotonic() - start}
162
+
163
+
164
+ def jpeg_sample_indices(sequence, camera, count):
165
+ seed = int.from_bytes(hashlib.sha256(f'{sequence}/{camera}/20260920'.encode()).digest()[:8], 'big')
166
+ indices = {0, count - 1, count // 4, count // 2, 3 * count // 4}
167
+ indices.update(random.Random(seed).sample([i for i in range(count) if i not in indices],
168
+ min(count, 16) - len(indices)))
169
+ return sorted(indices), seed
170
+
171
+
172
+ def check_jpeg_copy(target, paths, hashes, size, sequence, camera, full):
173
+ packets = json.loads(run(['ffprobe', '-v', 'error', '-select_streams', 'v:0',
174
+ '-show_packets', '-show_data_hash', 'sha256', '-of', 'json', str(target)],
175
+ stdout=subprocess.PIPE).stdout)['packets']
176
+ if [p['data_hash'].split(':', 1)[1].lower() for p in packets] != hashes:
177
+ raise ValueError('JPEG packet hashes/order/count differ')
178
+ info = probe(target)
179
+ if [info['width'], info['height']] != list(size):
180
+ raise ValueError('JPEG container dimensions differ')
181
+ indices, seed = jpeg_sample_indices(sequence, camera, len(paths))
182
+ if full:
183
+ indices = list(range(len(paths)))
184
+ select = '+'.join(f'eq(n\\,{i})' for i in indices)
185
+ frame_bytes = size[0] * size[1] * 3
186
+ # Spool selected frames to disk, keeping RAM bounded for full-view audits.
187
+ with tempfile.TemporaryFile() as decoded:
188
+ run(decode_args(target, 'rgb24') + ([] if full else ['-vf', 'select=' + select]) + ['pipe:1'], stdout=decoded)
189
+ decoded.seek(0)
190
+ for i in indices:
191
+ expected = run(decode_args(paths[i], 'rgb24') + ['pipe:1'], stdout=subprocess.PIPE).stdout
192
+ if len(expected) != frame_bytes or decoded.read(frame_bytes) != expected:
193
+ raise ValueError(f'JPEG decoded pixels differ at frame {i}')
194
+ if decoded.read(1):
195
+ raise ValueError('JPEG selected pixel count differs')
196
+ return {'policy': 'jpeg-packets-all-rgb-sample16/v1', 'seed': seed,
197
+ 'selected_frame_indices': indices, 'pixel_frames_checked': len(indices),
198
+ 'packet_frames_checked': len(paths), 'jpeg_packets_exact': True,
199
+ 'packet_count_order_dimensions_exact': True, 'sampled_pixels_exact': True,
200
+ 'all_frames_exact': len(indices) == len(paths), 'full_view_audit': full}
201
+
202
+
203
+ def rgb_video(paths, target, work, video=None, count=None, sequence="", camera="", full_jpeg=False):
204
+ """JPEG packet proof plus deterministic pixels; re-encodings compare all pixels."""
205
+ target.parent.mkdir(parents=True, exist_ok=True)
206
+ raw = work / 'rgb.raw'
207
+ packets = []
208
+ has_missing = video is None and any(p is None for p in paths)
209
+ if has_missing:
210
+ present = next((p for p in paths if p is not None), None)
211
+ if present is None:
212
+ raise ValueError('no source RGB image to establish the pixel format/grid')
213
+ original = probe(present)
214
+ width, height = original['width'], original['height']
215
+ with raw.open('wb') as dest:
216
+ for path in paths:
217
+ if path is None:
218
+ dest.write(bytes(width * height * 3))
219
+ else:
220
+ with Image.open(path) as im:
221
+ if im.mode != 'RGB' or im.size != (width, height):
222
+ raise ValueError('source RGB grid/type changes within view')
223
+ run(decode_args(path, 'rgb24') + ['pipe:1'], stdout=dest)
224
+ lossy, count = 'unknown', len(paths)
225
+ input_args = None
226
+ elif video is None:
227
+ if not paths:
228
+ raise ValueError('RGB timeline must contain existing source images')
229
+ suffix = paths[0].suffix.lower()
230
+ if suffix not in ('.jpg', '.jpeg', '.png'):
231
+ raise ValueError('unsupported source RGB format')
232
+ images = work / 'rgb_source'
233
+ images.mkdir()
234
+ dimensions = None
235
+ for i, path in enumerate(paths):
236
+ with Image.open(path) as im:
237
+ if im.mode != 'RGB' or (dimensions is not None and dimensions != im.size):
238
+ raise ValueError('RGB must be homogeneous 8-bit RGB, with no silent color/size conversion')
239
+ dimensions = im.size
240
+ if im.format == 'PNG' and path.read_bytes()[24] != 8:
241
+ raise ValueError('high bit depth RGB needs a registered schema')
242
+ dest = images / f'{i:08d}{suffix}'
243
+ shutil.copyfile(path, dest)
244
+ packets.append(sha256(path))
245
+ width, height = dimensions
246
+ input_args = ['-framerate', '30', '-i', str(images / ('%08d' + suffix))]
247
+ count = len(paths)
248
+ original = probe(paths[0])
249
+ lossy = suffix in ('.jpg', '.jpeg')
250
+ else:
251
+ original = probe(video)
252
+ if int(original.get('bits_per_raw_sample') or 8) > 8 or any(
253
+ x in original.get('pix_fmt', '') for x in ('10', '12', '16', 'f32')):
254
+ raise ValueError('high bit depth RGB needs a registered schema')
255
+ width, height = original['width'], original['height']
256
+ input_args = ['-i', str(video)]
257
+ lossy = 'unknown'
258
+ limits = ['-frames:v', str(count)] if count else []
259
+ records = []
260
+ if video is None and not has_missing and suffix in ('.jpg', '.jpeg'):
261
+ start = time.monotonic()
262
+ try:
263
+ run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0',
264
+ *limits, '-c:v', 'copy', '-an', str(target)])
265
+ encode_seconds = time.monotonic() - start
266
+ validation = check_jpeg_copy(target, paths, packets, (width, height), sequence, camera, full_jpeg)
267
+ cfg = storage(target, 'mkv/mjpeg_copy/v1', {'stream_copy': True}, lossy)
268
+ cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in
269
+ ('color_space', 'color_range', 'color_primaries', 'color_transfer')}
270
+ records.append(validation | {'profile': cfg['profile'], 'bytes': target.stat().st_size,
271
+ 'encode_seconds': encode_seconds, 'validation_seconds': time.monotonic() - start - encode_seconds})
272
+ return cfg, [width, height], records, count
273
+ except (subprocess.CalledProcessError, ValueError) as exc:
274
+ records.append({'profile': 'mkv/mjpeg_copy/v1', 'rejected': str(exc)})
275
+ target.unlink(missing_ok=True)
276
+ if not has_missing:
277
+ run(['ffmpeg', '-v', 'error', '-nostdin', '-y', '-threads', '1', '-noautorotate',
278
+ *input_args, '-map', '0:v:0', *limits, '-vsync', '0', '-threads', '1',
279
+ '-f', 'rawvideo', '-pix_fmt', 'rgb24', str(raw)])
280
+ frame_bytes = width * height * 3
281
+ actual, remainder = divmod(raw.stat().st_size, frame_bytes)
282
+ if remainder or not actual or (count is not None and actual != count):
283
+ raise ValueError('source RGB frame count mismatch')
284
+ expected_hash = sha256(raw)
285
+ can_copy = video is not None
286
+ if can_copy:
287
+ start = time.monotonic()
288
+ try:
289
+ run(['ffmpeg', '-v', 'error', '-nostdin', '-y', *input_args, '-map', '0:v:0',
290
+ *limits, '-c:v', 'copy', '-an', str(target)])
291
+ digest, size, seconds = decoded_digest(target, 'rgb24')
292
+ if digest != expected_hash or size != raw.stat().st_size:
293
+ raise ValueError('stream-copy RGB bytes/order/count mismatch')
294
+ cfg = storage(target, 'mkv/source_copy/v1',
295
+ {'stream_copy': True}, lossy)
296
+ if video:
297
+ cfg['storage_fps'] = original.get('avg_frame_rate')
298
+ cfg['preserve_source_pts'] = True
299
+ records.append({'profile': cfg['profile'], 'all_frames_exact': True,
300
+ 'decoded_sha256': digest,
301
+ 'bytes': target.stat().st_size, 'decode_seconds': seconds,
302
+ 'encode_seconds': time.monotonic() - start - seconds})
303
+ records[-1].update(measure_rgb_access(target, raw, width, height, actual))
304
+ return cfg, [width, height], records, actual
305
+ except (subprocess.CalledProcessError, ValueError) as exc:
306
+ records.append({'profile': 'stream_copy', 'rejected': str(exc)})
307
+ target.unlink(missing_ok=True)
308
+ candidates = []
309
+ for profile, codec, params in [
310
+ ('mkv/ffv1_rgb/v1', 'ffv1', ['-level', '3', '-pix_fmt', 'bgr0']),
311
+ ('mkv/h264_rgb_lossless/v1', 'libx264rgb', ['-crf', '0', '-preset', 'medium', '-g', '30'])]:
312
+ path = work / (codec + '.mkv')
313
+ try:
314
+ cfg, record = encode_raw(raw, path, width, height, 'rgb24', profile, codec, params)
315
+ cfg['source_lossy'] = lossy
316
+ cfg['decoder']['source_color_metadata'] = {k: original.get(k, 'unknown') for k in
317
+ ('color_space', 'color_range', 'color_primaries', 'color_transfer')}
318
+ record['profile'] = profile
319
+ record.update(measure_rgb_access(path, raw, width, height, actual))
320
+ records.append(record)
321
+ candidates.append((path.stat().st_size, path, cfg))
322
+ except subprocess.CalledProcessError as exc:
323
+ records.append({'profile': profile, 'rejected': exc.stderr.decode(errors='replace')})
324
+ if not candidates:
325
+ raise ValueError('no supported lossless RGB encoder')
326
+ _, chosen, cfg = min(candidates, key=lambda x: x[0])
327
+ shutil.move(chosen, target)
328
+ return cfg, [width, height], records, actual
329
+
330
+
331
+ def pack_depth(depth):
332
+ bits = np.ascontiguousarray(depth, dtype='<f4').view('<u4')
333
+ return np.concatenate([(bits & 65535).astype('<u2'), (bits >> 16).astype('<u2')], axis=-1)
334
+
335
+
336
+ def unpack_depth(encoded):
337
+ low, high = np.split(np.asarray(encoded, dtype='<u2'), 2, axis=-1)
338
+ return (low.astype('<u4') | (high.astype('<u4') << 16)).view('<f4')
339
+
340
+
341
+ def check_transform(values):
342
+ a = np.asarray(values)
343
+ if not np.isfinite(a).all() or a.shape[-2:] != (4, 4):
344
+ raise ValueError('invalid transform shape/values')
345
+ if not np.allclose(a[..., 3, :], [0, 0, 0, 1], atol=1e-5):
346
+ raise ValueError('invalid homogeneous transform row')
347
+ r = a[..., :3, :3]
348
+ if not np.allclose(np.swapaxes(r, -1, -2) @ r, np.eye(3), atol=2e-3) or not np.allclose(
349
+ np.linalg.det(r), 1, atol=2e-3):
350
+ raise ValueError('nonrigid rotation')
351
+
352
+
353
+ class View:
354
+ def __init__(self, path, dataset, release, sequence, camera, frames, sampling='dense', split='unknown'):
355
+ self.path = Path(path)
356
+ self.path.mkdir(parents=True, exist_ok=True)
357
+ self.frames = frames
358
+ self.valid_rules = {}
359
+ self.full_jpeg = False
360
+ self.meta = dict(schema_version=SCHEMA['schema_version'], dataset_id=dataset,
361
+ release_id=release, sequence_id=sequence, camera_id=camera,
362
+ sample_type='video', num_frames=len(frames), hand_slots=['left', 'right'],
363
+ sampling={'type': sampling, 'source_fps': None, 'frames_ref': 'camera/frames.jsonl'},
364
+ camera={'model': 'unknown', 'schema_id': None, 'image_size': None},
365
+ components={}, split=split, view_type='unknown')
366
+ if split == 'unknown':
367
+ self.meta['split_reason'] = 'No verified official split mapping available for this sequence'
368
+ self.build = {'validation': [], 'unresolved': [], 'validity_revision': SCHEMA['validity_revision']}
369
+
370
+ def absent(self, key, reason, status='source_missing'):
371
+ self.meta['components'][key] = {'available': False, 'reason': reason, 'status': status}
372
+ if status != 'source_missing':
373
+ self.build['unresolved'].append({'component': key, 'status': status, 'reason': reason})
374
+
375
+ def component(self, key, schema, ref, axes, loc, **extra):
376
+ if schema not in SCHEMA['components']:
377
+ raise ValueError(f'unregistered schema: {schema}')
378
+ if ref.startswith('annotation/') and extra.get('valid_ref'):
379
+ rule = self.valid_rules.get(key, self.valid_rules.get(key.split('_')[0]))
380
+ if not rule:
381
+ raise ValueError(f'{key}: adapter must declare annotation validity rule')
382
+ extra.setdefault('valid_policy', dict(
383
+ revision=SCHEMA['validity_revision'], meaning=SCHEMA['annotation_validity']['meaning'],
384
+ source_rule=rule, source_locator=loc, scope=extra.get('valid_axes', axes),
385
+ numerical_checks='Schema shape, finite valid floats, SE(3) where applicable; malformed input aborts',
386
+ official_qa={'status': 'not_provided', 'reason': 'No separate applicable official QA in selected source inputs'},
387
+ local_excluded_frame_indices=[], local_exclusion_reasons={}, visibility_independent=True))
388
+ self.meta['components'][key] = dict(available=True, schema_id=schema, data_ref=ref,
389
+ axes=axes, provenance=source(), source_locator=loc) | extra
390
+ return self.meta['components'][key]
391
+
392
+ def tensor(self, key, schema, ref, array, valid, axes, loc, **extra):
393
+ array = np.asarray(array, dtype=np.float32)
394
+ valid = np.asarray(valid, dtype=bool)
395
+ valid_shape = SCHEMA['components'][schema].get('valid_shape')
396
+ if 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))):
397
+ raise ValueError(f'{key}: schema validity shape mismatch')
398
+ if array.shape[:valid.ndim] != valid.shape:
399
+ raise ValueError(f'{key}: validity axes mismatch')
400
+ if not np.isfinite(array[valid]).all():
401
+ raise ValueError(f'{key}: source annotation exists but is nonfinite')
402
+ array = array.copy()
403
+ array[~valid] = np.nan
404
+ if schema in ('transform/se3/v1', 'object/rigid/v1'):
405
+ check_transform(array[valid])
406
+ expected = SCHEMA['components'][schema].get('shape')
407
+ if expected and (len(expected) != array.ndim or any(
408
+ isinstance(n, int) and array.shape[i] != n for i, n in enumerate(expected))):
409
+ raise ValueError(f'{key}: schema shape mismatch {array.shape}')
410
+ dest = self.path / ref
411
+ dest.parent.mkdir(parents=True, exist_ok=True)
412
+ torch.save(torch.from_numpy(array), dest)
413
+ valid_ref = str(Path(ref).with_name(Path(ref).stem + '_valid.pt'))
414
+ torch.save(torch.from_numpy(valid.copy()), self.path / valid_ref)
415
+ return self.component(key, schema, ref, axes, loc, valid_ref=valid_ref,
416
+ valid_axes=axes[:valid.ndim], **extra)
417
+
418
+ def rgb(self, paths, loc, video=None, count=None):
419
+ with tempfile.TemporaryDirectory(prefix='rgb-', dir=self.path) as work:
420
+ cfg, size, records, n = rgb_video(paths, self.path / 'observation/rgb.mkv',
421
+ Path(work), video, count, self.meta['sequence_id'], self.meta['camera_id'], self.full_jpeg)
422
+ if n != len(self.frames):
423
+ raise ValueError('RGB differs from frames timeline')
424
+ torch.save(torch.ones(n, dtype=torch.bool, device='cpu') if video is not None else
425
+ torch.tensor([p is not None for p in paths], dtype=torch.bool, device='cpu'),
426
+ self.path / 'observation/rgb_valid.pt')
427
+ self.component('rgb', 'rgb/uint8/v1', 'observation/rgb.mkv', ['T', 'height', 'width', 'channel'],
428
+ loc, storage=cfg, valid_ref='observation/rgb_valid.pt', valid_axes=['T'],
429
+ provenance=source('Verified source packet copy or lossless fixed-decoder RGB encoding'))
430
+ self.meta['camera']['image_size'] = size
431
+ self.build['validation'].extend(records)
432
+
433
+ def raster(self, key, arrays, valid, loc, labels=None):
434
+ depth = key == 'depth'
435
+ ref = 'observation/depth.mkv' if depth else 'annotation/segment/mask.mkv'
436
+ dest = self.path / ref
437
+ dest.parent.mkdir(parents=True, exist_ok=True)
438
+ width, height = self.meta['camera']['image_size']
439
+ count = 0
440
+ with tempfile.TemporaryDirectory(prefix='raster-', dir=self.path) as wd:
441
+ work = Path(wd)
442
+ with (work / 'data.raw').open('wb') as out, (work / 'valid.raw').open('wb') as vo:
443
+ for arr in arrays:
444
+ arr = np.asarray(arr)
445
+ if arr.shape != (height, width):
446
+ raise ValueError(f'{key}: raster not on RGB grid')
447
+ if depth:
448
+ arr = arr.astype('<f4')
449
+ good = np.isfinite(arr) & (arr > 0)
450
+ arr[~good] = np.nan
451
+ out.write(pack_depth(arr).tobytes())
452
+ vo.write(good.astype(np.uint8).tobytes())
453
+ else:
454
+ if not np.issubdtype(arr.dtype, np.integer) or arr.min() < 0 or arr.max() > 65535:
455
+ raise ValueError('invalid segmentation region codes')
456
+ out.write(arr.astype('<u2').tobytes())
457
+ count += 1
458
+ if count != len(self.frames):
459
+ raise ValueError(f'{key}: frame count mismatch')
460
+ cfg, record = encode_raw(work / 'data.raw', dest, width * (2 if depth else 1), height,
461
+ 'gray16le', 'mkv/depth_float32_bits/v1' if depth else 'mkv/uint16_ffv1/v1')
462
+ self.build['validation'].append(record | {'component': key})
463
+ if depth:
464
+ vcfg, record = encode_raw(work / 'valid.raw', self.path / 'observation/depth_valid.mkv',
465
+ width, height, 'gray', 'mkv/bool_ffv1/v1')
466
+ self.build['validation'].append(record | {'component': 'depth_valid'})
467
+ self.component(key, 'depth/z_float32/v1', ref, ['T', 'height', 'width'], loc,
468
+ storage=cfg, valid_storage=vcfg, valid_ref='observation/depth_valid.mkv',
469
+ valid_axes=['T', 'height', 'width'], unit='m', depth_type='z', depth_origin='measured', invalid_value='NaN')
470
+ else:
471
+ vref = 'annotation/segment/mask_valid.pt'
472
+ torch.save(torch.as_tensor(valid, dtype=torch.bool, device='cpu'), self.path / vref)
473
+ jsonl_write(self.path / 'annotation/segment/instances.jsonl', labels)
474
+ self.component(key, 'segment/uint16_labels/v1', ref, ['T', 'height', 'width'], loc,
475
+ storage=cfg, valid_ref=vref, valid_axes=['T'], segmentation_type='instance',
476
+ mapping_ref='annotation/segment/instances.jsonl', coverage={'kind': 'unknown'})
477
+
478
+ def camera(self, intrinsic, loc, extrinsic=None, extrinsic_loc=None):
479
+ n = len(self.frames)
480
+ if intrinsic is not None:
481
+ a = np.asarray(intrinsic)
482
+ a = np.broadcast_to(a, (n, 3, 3)) if a.shape == (3, 3) else a
483
+ if not np.allclose(a[..., 2, :], [0, 0, 1]) or np.any(a[..., 0, 0] <= 0) or np.any(a[..., 1, 1] <= 0):
484
+ raise ValueError('invalid pinhole intrinsic matrix')
485
+ self.tensor('intrinsic', 'camera/pinhole/v1', 'camera/intrinsic.pt', a,
486
+ np.ones(n, bool), ['T', 'row', 'column'], loc)
487
+ self.meta['camera'].update(model='pinhole', schema_id='camera/pinhole/v1')
488
+ if extrinsic is not None:
489
+ a = np.asarray(extrinsic)
490
+ a = np.broadcast_to(a, (n, 4, 4)) if a.shape == (4, 4) else a
491
+ self.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', a,
492
+ np.ones(n, bool), ['T', 'row', 'column'], extrinsic_loc or loc,
493
+ convention='T_camera_from_world')
494
+
495
+ def object(self, oid, loc, scope='sequence', scope_id=None, **extra):
496
+ info = dict(object_id=oid, identity_scope=scope, scope_id=scope_id or self.meta['sequence_id'],
497
+ source_locator=loc, has_model=False) | extra
498
+ json_write(self.path / f'annotation/object/{oid}/metainfo.json', info)
499
+ return info
500
+
501
+ def relations(self, rows, valid, loc):
502
+ ref = 'annotation/contact/relations.jsonl'
503
+ jsonl_write(self.path / ref, rows)
504
+ vref = 'annotation/contact/relations_valid.pt'
505
+ torch.save(torch.as_tensor(valid, dtype=torch.bool, device='cpu'), self.path / vref)
506
+ self.component('relations', 'contact/relations/v1', ref, ['T'], loc, valid_ref=vref, valid_axes=['T'])
507
+
508
+ def finish(self):
509
+ check_view_type(self.meta)
510
+ for key, component in self.meta['components'].items():
511
+ if component.get('valid_policy'):
512
+ check_valid_policy(component, len(self.frames))
513
+ valid = torch.load(self.path / component['valid_ref'], weights_only=True)
514
+ self.build.setdefault('annotation_validity', {})[key] = {
515
+ 'valid_policy': component['valid_policy'], 'valid_count': int(valid.sum()),
516
+ 'invalid_count': valid.numel() - int(valid.sum())}
517
+ for i, frame in enumerate(self.frames):
518
+ frame.update(frame_index=i)
519
+ frame.setdefault('timestamp_ns', None)
520
+ frame.setdefault('clock_domain', None)
521
+ if 'source_locator' not in frame:
522
+ raise ValueError('frame source locator missing')
523
+ jsonl_write(self.path / 'camera/frames.jsonl', self.frames)
524
+ json_write(self.path / 'metainfo.json', self.meta)
525
+ return self.build
526
+
527
+
528
+ def check_mesh(path, asset_root):
529
+ path, asset_root = Path(path), Path(asset_root).resolve()
530
+ vertices, faces, largest_index = 0, 0, 0
531
+ materials = []
532
+ with path.open() as inp:
533
+ for line in inp:
534
+ fields = line.split()
535
+ if not fields or fields[0].startswith('#'):
536
+ continue
537
+ if fields[0] == 'v':
538
+ if len(fields) < 4 or not all(math.isfinite(float(v)) for v in fields[1:4]):
539
+ raise ValueError(f'invalid mesh vertex: {path}')
540
+ vertices += 1
541
+ elif fields[0] == 'f':
542
+ if len(fields) < 4:
543
+ raise ValueError('degenerate OBJ face')
544
+ for field in fields[1:]:
545
+ index = int(field.split('/')[0])
546
+ if index == 0 or index < -vertices:
547
+ raise ValueError('invalid OBJ vertex index')
548
+ largest_index = max(largest_index, index)
549
+ faces += 1
550
+ elif fields[0] == 'mtllib':
551
+ materials.extend(shlex.split(line)[1:])
552
+ if not vertices or not faces or largest_index > vertices:
553
+ raise ValueError('empty or invalid mesh')
554
+ def dependency(parent, name):
555
+ dep = (parent / name).resolve()
556
+ if not dep.is_relative_to(asset_root) or not dep.is_file():
557
+ raise ValueError(f'missing or escaping asset dependency: {name}')
558
+ return dep
559
+ dependencies = []
560
+ for name in materials:
561
+ mtl = dependency(path.parent, name)
562
+ dependencies.append(mtl)
563
+ for line in mtl.read_text().splitlines():
564
+ fields = shlex.split(line, comments=True)
565
+ if fields and (fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal')):
566
+ dependencies.append(dependency(mtl.parent, fields[-1]))
567
+ return {'vertices': vertices, 'faces': faces, 'sha256': sha256(path),
568
+ 'dependencies': {p.relative_to(asset_root).as_posix(): sha256(p) for p in dependencies}}
569
+
570
+
571
+ def mesh_asset(view, oid, directory, obj, loc):
572
+ dest = view.path / f'annotation/object/{oid}/assets'
573
+ shutil.copytree(directory, dest)
574
+ ref = (dest / Path(obj).relative_to(directory)).relative_to(view.path).as_posix()
575
+ mesh_check = check_mesh(dest / Path(obj).relative_to(directory), dest)
576
+ view.build['validation'].append({'component': f'mesh_{oid}', **mesh_check})
577
+ view.component(f'mesh_{oid}', 'mesh/obj/v1', ref, ['vertex'], loc, valid=True, unit='m')
578
+ p = view.path / f'annotation/object/{oid}/metainfo.json'
579
+ info = json.loads(p.read_text())
580
+ info.update(has_model=True, mesh_ref=ref)
581
+ json_write(p, info)
582
+
583
+
584
+ def safe_member(root, name):
585
+ path = (Path(root) / name).resolve()
586
+ if not path.is_relative_to(Path(root).resolve()):
587
+ raise ValueError(f'unsafe archive path: {name}')
588
+ return path
589
+
590
+
591
+ class ChumpyStub:
592
+ def __setstate__(self, state):
593
+ self.__dict__.update(state)
594
+
595
+
596
+ class ManoUnpickler(pickle.Unpickler):
597
+ def find_class(self, module, name):
598
+ if module.startswith('chumpy'):
599
+ return ChumpyStub
600
+ return super().find_class(module, name)
601
+
602
+
603
+ def mano_models(directory):
604
+ result = {}
605
+ if directory is None:
606
+ return result
607
+ for side in ('left', 'right'):
608
+ path = Path(directory).expanduser() / f'MANO_{side.upper()}.pkl'
609
+ if not path.exists():
610
+ continue
611
+ with path.open('rb') as f:
612
+ data = ManoUnpickler(f, encoding='latin1').load()
613
+ result[side] = {'components': np.asarray(data['hands_components']),
614
+ 'mean': np.asarray(data['hands_mean']), 'sha256': sha256(path),
615
+ 'file': path.name}
616
+ return result
617
+
618
+
619
+ def model_profile(models):
620
+ identity = json.dumps({side: d['sha256'] for side, d in sorted(models.items())}).encode()
621
+ return {'version': 'sha256:' + hashlib.sha256(identity).hexdigest(), 'flat_hand_mean': True,
622
+ 'left_shapedirs_correction': 'not_applied',
623
+ 'models': {side: {'file': d['file'], 'sha256': d['sha256']} for side, d in models.items()}}
624
+
625
+
626
+ def pca_to_axis_angle(coeffs, model):
627
+ coeffs = np.asarray(coeffs)
628
+ if coeffs.shape[-1:] != (45,) or not np.isfinite(coeffs).all():
629
+ raise ValueError('invalid MANO PCA coefficients')
630
+ return coeffs @ model['components'] + model['mean']
631
+
632
+
633
+ def parser(dataset, description):
634
+ p = argparse.ArgumentParser(description=description)
635
+ p.add_argument('--root', f'--{dataset.lower()}-root', dest='root', type=Path, default=RAW_ROOT / dataset)
636
+ p.add_argument('--out', type=Path, default=Path('converted'))
637
+ p.add_argument('--release-id', default='v1.0')
638
+ p.add_argument('--limit', type=int, help='Maximum sequences to convert')
639
+ p.add_argument('--max-frames', type=int, help='First N source frame indices per view (recorded as sampling)')
640
+ p.add_argument('--mano-dir', type=Path)
641
+ p.add_argument('--views', help='Comma-separated source camera IDs')
642
+ p.add_argument('--jpeg-full-check', action='store_true', help='Full decoded RGB check for selected JPEG pilot/final views')
643
+ return p
644
+
645
+
646
+ def roots(root):
647
+ root = Path(root).expanduser()
648
+ return [p for p in (root / 'raw/data', root / 'raw', root) if p.is_dir()]
649
+
650
+
651
+ def find_file(root, name):
652
+ return next((p / name for p in roots(root) if (p / name).exists()), None)
653
+
654
+
655
+ def release(args, dataset):
656
+ if not args.release_id or Path(args.release_id).name != args.release_id or args.release_id in ('.', '..'):
657
+ raise ValueError('release-id must be a single directory name')
658
+ if args.limit is not None and args.limit < 1 or args.max_frames is not None and args.max_frames < 1:
659
+ raise ValueError('limits must be positive')
660
+ out = args.out.expanduser().resolve() / dataset / args.release_id
661
+ raw = args.root.expanduser().resolve()
662
+ if out == raw or out.is_relative_to(raw):
663
+ raise ValueError('output must not modify the raw source tree')
664
+ (out / 'data').mkdir(parents=True, exist_ok=True)
665
+ (out / 'doc').mkdir(exist_ok=True)
666
+ (out / 'script').mkdir(exist_ok=True)
667
+ scripts = list(Path(__file__).resolve().parent.glob('*.py'))
668
+ existing = {p.name for p in (out / 'script').glob('*.py')}
669
+ if existing and existing != {p.name for p in scripts}:
670
+ raise ValueError('converter files changed; choose a new --release-id')
671
+ copies = [(SCHEMA_PATH.parent / name, out / 'doc' / name) for name in ('CONTRACT.md', 'schema.json')]
672
+ copies += [(path, out / 'script' / path.name) for path in scripts]
673
+ # Check every existing file before changing any published definition or script.
674
+ for src, dest in copies:
675
+ if dest.exists() and sha256(dest) != sha256(src):
676
+ raise ValueError('converter or contract changed within an existing release; choose a new --release-id')
677
+ for src, dest in copies:
678
+ if src.resolve() != dest.resolve():
679
+ shutil.copyfile(src, dest)
680
+ json_write(out / 'script/config.json', {k: str(v) if isinstance(v, Path) else v for k, v in vars(args).items()})
681
+ return out
682
+
683
+
684
+ @contextmanager
685
+ def sequence_dir(out, sequence):
686
+ if Path(sequence).name != sequence:
687
+ raise ValueError('sequence ID must be a single path component')
688
+ final = out / 'data' / sequence
689
+ with tempfile.TemporaryDirectory(prefix=sequence + '.tmp-', dir=out / 'data') as wd:
690
+ tmp = Path(wd)
691
+ yield tmp
692
+ if final.exists():
693
+ if any((final / child.name).exists() for child in tmp.iterdir()):
694
+ raise FileExistsError('view already published; use a new release-id to preserve it')
695
+ for child in list(tmp.iterdir()):
696
+ child.rename(final / child.name)
697
+ else:
698
+ tmp.rename(final)
699
+
700
+
701
+ def build_record(out, sequence, reports):
702
+ path = out / 'doc' / (sequence + '.build.json')
703
+ previous = json.loads(path.read_text()) if path.exists() else {}
704
+ config = json.loads((out / 'script/config.json').read_text())
705
+ for report in reports.values():
706
+ report['configuration'] = config
707
+ json_write(path, {'sequence_id': sequence, 'storage_revision': SCHEMA['storage_revision'],
708
+ 'scripts': {p.name: sha256(p) for p in (out / 'script').glob('*.py')},
709
+ 'runtime': {'torch': torch.__version__, 'ffmpeg': ffversion()},
710
+ 'views': previous.get('views', {}) | reports})
711
+
712
+
713
+ def check_view_type(meta):
714
+ if meta.get('view_type') not in SCHEMA['view_metadata']['view_type_values']:
715
+ raise ValueError('view_type must be ego/exo/unknown')
716
+ expected = {'dex-ycb': 'exo', 'EPIC-KITCHENS-VISOR': 'ego', 'HOI4D': 'ego'}.get(meta['dataset_id'])
717
+ if meta['dataset_id'] == 'H2O':
718
+ expected = 'ego' if meta['camera_id'] == 'cam4' else 'exo' if meta['camera_id'] in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown'
719
+ if expected and meta['view_type'] != expected:
720
+ raise ValueError('view_type contradicts known source capture setup')
721
+
722
+
723
+ def check_valid_policy(component, count):
724
+ policy = component.get('valid_policy', {})
725
+ for field in ('revision', 'meaning', 'source_rule', 'source_locator', 'scope', 'numerical_checks',
726
+ 'official_qa', 'local_excluded_frame_indices', 'local_exclusion_reasons', 'visibility_independent'):
727
+ if field not in policy:
728
+ raise ValueError(f'valid_policy missing {field}')
729
+ if policy['revision'] != SCHEMA['validity_revision'] or policy['meaning'] != SCHEMA['annotation_validity']['meaning']:
730
+ raise ValueError('outdated annotation validity semantics')
731
+ if not policy['source_rule'] or not policy['numerical_checks'] or policy['scope'] != component['valid_axes']:
732
+ raise ValueError('incomplete validity rule/scope')
733
+ if policy['official_qa'].get('status') != 'not_provided' or not policy['official_qa'].get('reason'):
734
+ raise ValueError('official QA requires a verified adapter; supervision acceptance paused')
735
+ excluded = policy['local_excluded_frame_indices']
736
+ if any(type(i) is not int or not 0 <= i < count for i in excluded):
737
+ raise ValueError('invalid local exclusion frame index')
738
+ if excluded:
739
+ raise ValueError('local exclusions require a reviewed rule/report; not supported by these adapters')
740
+ if policy['visibility_independent'] is not True:
741
+ raise ValueError('visibility must remain independent of validity')
742
+
743
+
744
+ def validate_view(path):
745
+ """Validate the persisted contract, not a rendering of the source labels."""
746
+ path = Path(path)
747
+ meta = json.loads((path / 'metainfo.json').read_text())
748
+ n = meta['num_frames']
749
+ check_view_type(meta)
750
+ if meta['schema_version'] != SCHEMA['schema_version'] or meta['hand_slots'] != ['left', 'right'] or n < 1:
751
+ raise ValueError('invalid view header')
752
+ def resolve(ref):
753
+ if Path(ref).is_absolute() or '\\' in ref:
754
+ raise ValueError('component reference must be relative POSIX')
755
+ dest = safe_member(path, ref)
756
+ if not dest.is_file():
757
+ raise ValueError(f'referenced file missing: {ref}')
758
+ return dest
759
+ def tensor(ref):
760
+ def cpu_storage(storage, location):
761
+ if location != 'cpu':
762
+ raise ValueError('PT storage must be on CPU')
763
+ return storage
764
+ value = torch.load(resolve(ref), map_location=cpu_storage, weights_only=True)
765
+ if not isinstance(value, torch.Tensor) or value.device.type != 'cpu':
766
+ raise ValueError('PT must contain only a CPU Tensor')
767
+ return value.numpy()
768
+ frames = [json.loads(line) for line in resolve(meta['sampling']['frames_ref']).read_text().splitlines()]
769
+ if len(frames) != n or [f['frame_index'] for f in frames] != list(range(n)):
770
+ raise ValueError('frame index/count mismatch')
771
+ for f in frames:
772
+ if not all(k in f for k in ('source_frame_id', 'timestamp_ns', 'clock_domain', 'source_locator')):
773
+ raise ValueError('incomplete frame provenance')
774
+ entities = {'hand_left', 'hand_right'}
775
+ parts = {}
776
+ for p in (path / 'annotation/object').glob('*/metainfo.json'):
777
+ obj = json.loads(p.read_text())
778
+ if obj['object_id'] != p.parent.name or obj['identity_scope'] not in ('frame', 'subsequence', 'sequence'):
779
+ raise ValueError('invalid object identity')
780
+ entities.add(obj['object_id'])
781
+ if obj.get('mesh_ref'):
782
+ if not resolve(obj['mesh_ref']).is_relative_to(p.parent.resolve()):
783
+ raise ValueError('mesh must belong to its object')
784
+ if obj.get('articulation_ref'):
785
+ art = json.loads(resolve(obj['articulation_ref']).read_text())
786
+ part_ids = {part['part_id'] for part in art['parts']}
787
+ if len(part_ids) != len(art['parts']):
788
+ raise ValueError('duplicate part ID')
789
+ parents = {part['part_id']: part['parent_id'] for part in art['parts']}
790
+ for part_id in parents:
791
+ visited, cur = set(), part_id
792
+ while cur is not None:
793
+ if cur in visited or cur not in parents:
794
+ raise ValueError('invalid or cyclic part hierarchy')
795
+ visited.add(cur)
796
+ cur = parents[cur]
797
+ parts[obj['object_id']] = part_ids
798
+ video_stats = {}
799
+ for key, component in meta['components'].items():
800
+ if not component.get('available'):
801
+ if not component.get('reason'):
802
+ raise ValueError('unavailable component needs a reason')
803
+ continue
804
+ schema = SCHEMA['components'][component['schema_id']]
805
+ for required in ('axes', 'provenance', 'source_locator'):
806
+ if required not in component:
807
+ raise ValueError(f'{key}: {required} missing')
808
+ for required in schema.get('required_metadata', []):
809
+ if required not in component:
810
+ raise ValueError(f'{key}: {required} missing')
811
+ if component['provenance']['kind'] == 'derived':
812
+ raise ValueError('v1.0 must not synthesize annotations')
813
+ if component['data_ref'].startswith('annotation/') and schema.get('valid_shape'):
814
+ if not component.get('valid_ref') or not component.get('valid_axes'):
815
+ raise ValueError(f'{key}: annotation validity reference/axes missing')
816
+ check_valid_policy(component, n)
817
+ data_path = resolve(component['data_ref'])
818
+ valid = tensor(component['valid_ref']) if component.get('valid_ref', '').endswith('.pt') else None
819
+ valid_shape = schema.get('valid_shape')
820
+ if valid is not None and valid_shape and (len(valid_shape) != valid.ndim or any(
821
+ isinstance(s, int) and valid.shape[i] != s for i, s in enumerate(valid_shape))):
822
+ raise ValueError(f'{key}: validity schema shape mismatch')
823
+ if valid is not None and (valid.dtype != bool or valid.shape[0] != n):
824
+ raise ValueError(f'{key}: invalid validity tensor')
825
+ if component['schema_id'] == 'mesh/obj/v1':
826
+ objroot = next((parent for parent in data_path.parents if parent.parent.name == 'object'), None)
827
+ if objroot is None:
828
+ raise ValueError('mesh must be owned by an object')
829
+ check_mesh(data_path, objroot)
830
+ if data_path.suffix == '.pt':
831
+ arr = tensor(component['data_ref'])
832
+ if arr.dtype != np.float32 or arr.shape[0] != n:
833
+ raise ValueError(f'{key}: float dtype or timeline mismatch')
834
+ shape = schema.get('shape')
835
+ if shape and (len(shape) != arr.ndim or any(isinstance(s, int) and arr.shape[i] != s for i, s in enumerate(shape))):
836
+ raise ValueError(f'{key}: schema shape mismatch')
837
+ if valid is not None:
838
+ if arr.shape[:valid.ndim] != valid.shape or not np.isfinite(arr[valid]).all() or not np.isnan(arr[~valid]).all():
839
+ raise ValueError(f'{key}: invalid finite/NaN/validity values')
840
+ if component['schema_id'] in ('object/rigid/v1', 'transform/se3/v1'):
841
+ check_transform(arr[valid])
842
+ if data_path.suffix == '.mkv':
843
+ cfg = component['storage']
844
+ if cfg['profile'] not in SCHEMA['storage_profiles']:
845
+ raise ValueError('unregistered video profile')
846
+ for field in SCHEMA['video_metadata']['required']:
847
+ if field not in cfg:
848
+ raise ValueError('video storage declaration incomplete')
849
+ w, h = meta['camera']['image_size']
850
+ if cfg['encoded_size'] != [w * (2 if key == 'depth' else 1), h]:
851
+ raise ValueError('encoded raster differs from logical RGB grid')
852
+ actual = probe(data_path)
853
+ if (actual['codec_name'] != cfg['codec'] or actual['pix_fmt'] != cfg['pixel_format'] or
854
+ [actual['width'], actual['height']] != cfg['encoded_size']):
855
+ raise ValueError('video storage metadata differs from file')
856
+ if key == 'rgb':
857
+ fmt, bpp = 'rgb24', 3
858
+ else:
859
+ fmt, bpp = 'gray16le', 2
860
+ digest, size, _ = decoded_digest(data_path, fmt)
861
+ w, h = cfg['encoded_size']
862
+ if size != n * w * h * bpp:
863
+ raise ValueError('raster timeline mismatch')
864
+ video_stats[key] = {'decoded_sha256': digest, 'frames': n}
865
+ if key == 'depth':
866
+ validity = component['valid_storage']
867
+ vp = resolve(component['valid_ref'])
868
+ actual_valid = probe(vp)
869
+ if (validity['profile'] != 'mkv/bool_ffv1/v1' or actual_valid['codec_name'] != 'ffv1'
870
+ or actual_valid['pix_fmt'] != 'gray' or [actual_valid['width'], actual_valid['height']] != [w // 2, h]):
871
+ raise ValueError('invalid depth validity video')
872
+ count = 0
873
+ for encoded, mask in zip(video_frames(data_path, 'gray16le', (h, w), '<u2'),
874
+ video_frames(vp, 'gray', (h, w // 2), np.uint8), strict=True):
875
+ if not np.isin(mask, [0, 1]).all():
876
+ raise ValueError('depth valid pixels must be 0 or 1')
877
+ depth, good = unpack_depth(encoded), mask.astype(bool)
878
+ if not (np.isfinite(depth[good]) & (depth[good] > 0)).all() or not np.isnan(depth[~good]).all():
879
+ raise ValueError('invalid depth/validity semantics')
880
+ count += 1
881
+ if count != n:
882
+ raise ValueError('depth validity timeline mismatch')
883
+ if component['schema_id'].startswith('segment/') and component.get('mapping_ref'):
884
+ rows = [json.loads(line) for line in resolve(component['mapping_ref']).read_text().splitlines()]
885
+ if len(rows) != n or [row['frame_index'] for row in rows] != list(range(n)):
886
+ raise ValueError('segmentation mapping timeline mismatch')
887
+ for row in rows:
888
+ labels = row['labels']
889
+ if len({a['mask_value'] for a in labels}) != len(labels):
890
+ raise ValueError('duplicate region mapping')
891
+ for label in labels:
892
+ if label['entity_id'] is not None and label['entity_id'] not in entities:
893
+ raise ValueError('unresolved segmentation entity')
894
+ if label['part_id'] is not None and label['part_id'] not in parts.get(label['entity_id'], set()):
895
+ raise ValueError('unresolved segmentation part')
896
+ if component['schema_id'] == 'segment/uint16_labels/v1':
897
+ width, height = meta['camera']['image_size']
898
+ for i, mask in enumerate(video_frames(data_path, 'gray16le', (height, width), '<u2')):
899
+ codes = set(np.unique(mask).tolist()) - {0, 65535}
900
+ mapped = {label['mask_value'] for label in rows[i]['labels']} - {0, 65535}
901
+ if codes != mapped or not valid[i] and codes:
902
+ raise ValueError('mask values differ from declared instances/validity')
903
+ if component['schema_id'] == 'segment/instance_polygons/v1':
904
+ polygons = [json.loads(line) for line in data_path.read_text().splitlines()]
905
+ if len(polygons) != n:
906
+ raise ValueError('polygon timeline mismatch')
907
+ for i, row in enumerate(polygons):
908
+ if row['frame_index'] != i or {x['mask_value'] for x in row['instances']} != {x['mask_value'] for x in rows[i]['labels']}:
909
+ raise ValueError('polygon/mapping mismatch')
910
+ if component['schema_id'] == 'contact/relations/v1':
911
+ rows = [json.loads(line) for line in data_path.read_text().splitlines()]
912
+ if len(rows) != n:
913
+ raise ValueError('relation timeline mismatch')
914
+ for i, row in enumerate(rows):
915
+ if row['frame_index'] != i or not valid[i] and row['relations']:
916
+ raise ValueError('relation validity mismatch')
917
+ for relation in row['relations']:
918
+ if relation['subject_id'] not in entities or relation['status'] not in ('positive', 'negative', 'unknown', 'target_unannotated'):
919
+ raise ValueError('invalid relation')
920
+ if relation['status'] == 'positive' and relation['object_id'] not in entities:
921
+ raise ValueError('unresolved positive contact')
922
+ return {'view': str(path), 'num_frames': n, 'videos': video_stats, 'validated': True}