Upload H2O shared-v1.0 (part 88)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- H2O/shared-v1.0/script/check_dexycb_projection.pyAdded+31
- H2O/shared-v1.0/script/config.jsonAdded+24
- H2O/shared-v1.0/script/convert_dexycb_v1.0.pyAdded+349
- H2O/shared-v1.0/script/convert_h2o_v1.0.pyAdded+678
- H2O/shared-v1.0/script/convert_hoi4d_v1.0.pyAdded+595
- H2O/shared-v1.0/script/convert_visor_v1.0.pyAdded+271
- H2O/shared-v1.0/script/provenance/operations/h2o-check-fallback.pyAdded+137
- H2O/shared-v1.0/script/provenance/operations/h2o-finalize-quick-validation.pyAdded+39
- H2O/shared-v1.0/script/provenance/operations/h2o-pipeline-bench-job.shAdded+25
- H2O/shared-v1.0/script/provenance/operations/h2o-pipeline-benchmark.pyAdded+48
- H2O/shared-v1.0/script/provenance/operations/h2o-pipeline-process-benchmark.pyAdded+48
- H2O/shared-v1.0/script/provenance/operations/h2o-prepare-pipeline-bench.pyAdded+28
- H2O/shared-v1.0/script/provenance/operations/h2o-prepare-process-full.pyAdded+45
- H2O/shared-v1.0/script/provenance/operations/h2o-process-final-tests.logAdded+39
- H2O/shared-v1.0/script/provenance/operations/h2o-quick-validation.pyAdded+161
- H2O/shared-v1.0/script/provenance/operations/h2o-shared-final-tests.logAdded+1
- H2O/shared-v1.0/script/provenance/operations/h2o-switch-process-full.shAdded+12
- H2O/shared-v1.0/script/provenance/operations/watch-steady-cpu.pyAdded+38
- H2O/shared-v1.0/script/provenance/previous-run/docs/CONTRACT.mdAdded+457
- H2O/shared-v1.0/script/provenance/previous-run/docs/h2o-RAW_TO_SHARED.mdAdded+48
- H2O/shared-v1.0/script/provenance/previous-run/docs/schema.jsonAdded+869
- H2O/shared-v1.0/script/provenance/previous-run/full.logAdded+61
- H2O/shared-v1.0/script/provenance/previous-run/full.statusAdded+7
- H2O/shared-v1.0/script/provenance/previous-run/run-full.shAdded+26
- H2O/shared-v1.0/script/provenance/previous-run/script/check_dexycb_projection.pyAdded+31
- H2O/shared-v1.0/script/provenance/previous-run/script/config.jsonAdded+17
- H2O/shared-v1.0/script/provenance/previous-run/script/convert_dexycb_v1.0.pyAdded+349
- H2O/shared-v1.0/script/provenance/previous-run/script/convert_h2o_v1.0.pyAdded+545
- H2O/shared-v1.0/script/provenance/previous-run/script/convert_hoi4d_v1.0.pyAdded+595
- H2O/shared-v1.0/script/provenance/previous-run/script/convert_visor_v1.0.pyAdded+271
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/h2o-benchmark-decode.pyAdded+74
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/h2o-prepare-d10.pyAdded+55
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/h2o-switch-d10.shAdded+16
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/worker4-encode10-decode10-depth4-regression.logAdded+37
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/workspace-regression.logAdded+37
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/docs/CONTRACT.mdAdded+457
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/docs/h2o-RAW_TO_SHARED.mdAdded+30
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/docs/schema.jsonAdded+869
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/full.logAdded+8
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/full.statusAdded+7
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/run-full.shAdded+26
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/check_dexycb_projection.pyAdded+31
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/config.jsonAdded+15
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_dexycb_v1.0.pyAdded+349
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_h2o_v1.0.pyAdded+527
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_hoi4d_v1.0.pyAdded+595
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_visor_v1.0.pyAdded+271
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/operations/prepare-w4-c10.pyAdded+52
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/operations/retry-w4-c10.shAdded+11
- H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/CONTRACT.mdAdded+457
12345678910111213141516171819202122232425262728293031#!/usr/bin/env python3"""Check saved Dex-YCB source 3D joints against saved source 2D joints in sampled views."""import jsonfrom pathlib import Pathimport sys
import numpy as npimport torch
root = Path(sys.argv[1])report = json.loads((root / 'doc/validation/STRUCTURAL_AUDIT.json').read_text())checks = []for name in report['sampled_views']: view = root / name load = lambda path: torch.load(view / path, weights_only=True, map_location='cpu').numpy() k = load('camera/intrinsic.pt') xyz = load('annotation/keypoints/xyz.pt') uv = load('annotation/keypoints/uv.pt') valid = load('annotation/keypoints/xyz_valid.pt') & load('annotation/keypoints/uv_valid.pt') z = xyz[..., 2] valid &= np.isfinite(xyz).all(axis=-1) & np.isfinite(uv).all(axis=-1) & (z > 0) z = np.where(valid, z, 1) pred = np.stack((k[:, 0, 0, None, None] * xyz[..., 0] / z + k[:, 0, 2, None, None], k[:, 1, 1, None, None] * xyz[..., 1] / z + k[:, 1, 2, None, None]), axis=-1) errors = np.linalg.norm(pred[valid] - uv[valid], axis=-1) checks.append(dict(view=name, points=int(errors.size), median_px=float(np.median(errors)) if errors.size else None, p95_px=float(np.percentile(errors, 95)) if errors.size else None))(root / 'doc/validation/KEYPOINT_PROJECTION_QC.json').write_text(json.dumps({ 'scope': 'Saved source 3D joints projected with saved color intrinsics vs saved source 2D joints; independent of hand mesh rendering.', 'views': checks}, ensure_ascii=False, indent=2) + '\n')print(json.dumps(checks, ensure_ascii=False), flush=True)123456789101112131415161718192021222324{ "root": "/home/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O", "out": "/home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe", "release_id": "shared-v1.0", "limit": null, "max_frames": null, "mano_dir": "/home/xuzhefeng/Projects/WiLoR/mano_data", "views": null, "jpeg_full_check": false, "workers": 4, "view_backend": "processes", "camera_pipeline": true, "ffv1_slices": 16, "view_workers": 16, "ram_stage_dir": "/dev/shm/xuzhefeng-h2o-full-process16-20260930", "ram_stage_gib": 32, "stream_media": true, "codec_threads": 10, "decode_threads": 10, "depth_threads": 4, "subjects": null, "include_casa": false, "archive": null}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349#!/usr/bin/env python3"""Dex-YCB source annotations → CONTRACT.md v1.0. No derived annotations."""import ioimport reimport shutilimport tarfileimport tempfilefrom pathlib import Path
import numpy as npfrom PIL import Imageimport yaml
from warehouse_v1_0 import (View, build_record, find_file, locator, mano_models, mesh_asset, model_profile, parser, pca_to_axis_angle, release, roots, safe_member, sequence_dir)
IMG_W, IMG_H = 640, 480
class _Loader(yaml.SafeLoader): pass
_Loader.add_constructor("tag:yaml.org,2002:python/tuple", lambda l, n: tuple(l.construct_sequence(n)))
def yaml_load_bytes(data: bytes): return yaml.load(io.BytesIO(data), Loader=_Loader)
class Calibration: def __init__(self, dexycb_root: Path): self.intrinsics = {} # serial -> {fx,fy,cx,cy,w,h} self.extrinsics = {} # group -> {serial: [12] 行优先 3×4 cam→world} self.betas = {} # mano_calib_name -> [10] calib_dir = dexycb_root / "calibration" if calib_dir.is_dir(): self._load((p.as_posix(), p.read_bytes()) for p in sorted(calib_dir.rglob("*")) if p.is_file()) else: tar_path = dexycb_root / "calibration.tar.gz" if not tar_path.exists(): raise FileNotFoundError(f"no calibration/ nor calibration.tar.gz in {dexycb_root}") with tarfile.open(tar_path, "r:gz") as tf: self._load((m.name, tf.extractfile(m).read()) for m in tf if m.isfile())
_RE_INTR = re.compile(r"(?:^|/)intrinsics/(\d+)_\d+x\d+\.yml$") _RE_EXTRA = re.compile(r"(?:^|/)extrinsics_(\d{8}_\d{6})/extrinsics\.yml$") _RE_MANO = re.compile(r"(?:^|/)mano_(\d{8}_\d{6}_subject-\d{2}_right)/mano\.yml$")
def _load(self, files): for rel, data in files: m = self._RE_INTR.search(rel) if m: c = yaml_load_bytes(data)["color"] self.intrinsics[m.group(1)] = {"fx": float(c["fx"]), "fy": float(c["fy"]), "cx": float(c["ppx"]), "cy": float(c["ppy"]), "w": IMG_W, "h": IMG_H} continue m = self._RE_EXTRA.search(rel) if m: raw = yaml_load_bytes(data)["extrinsics"] self.extrinsics[m.group(1)] = { str(s): [float(x) for x in np.asarray(v).ravel()] for s, v in raw.items()} continue m = self._RE_MANO.search(rel) if m: self.betas[m.group(1)] = [float(b) for b in yaml_load_bytes(data)["betas"]]
def calibration_locator(path, member, **extra): if path.is_dir(): return locator(path / member.removeprefix('calibration/'), **extra) return locator(path, member, **extra)
def prepare_models(root, destination): archive = find_file(root, 'models.tar.gz') if archive is None: return {}, None pattern = re.compile(r'^models/(\d{3}_[a-z0-9_]+)/(textured_simple\.obj(?:\.mtl)?|texture_map\.png)$') names = set() with tarfile.open(archive, 'r|gz') as tf: for member in tf: match = pattern.fullmatch(member.name) if member.isfile() and match: names.add(match[1]) path = safe_member(destination, '/'.join(match.groups())) path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(tf.extractfile(member).read()) if len(names) != 21: raise ValueError('expected all 21 source YCB model directories') return {i: destination / name for i, name in enumerate(sorted(names), 1)}, archive
def convert_view(path, args, seq, serial, frames, meta, meta_loc, calib, calib_path, models, assets, asset_archive): total = int(meta.get('num_frames', max(frames) + 1)) ids = list(range(min(total, args.max_frames) if args.max_frames else total)) for f in ids: frames.setdefault(f, {}) if not ids: raise ValueError('no RGB frames') source_rows = [] for f in ids: row = frames[f] source_rows.append(dict(source_frame_id=f, sync_id=f'{seq}:{f}', source_locator=row['color'][1] if 'color' in row else (meta_loc | {'source_frame_id': f, 'missing_rgb': True}), annotation_matches={ 'labels': {'source_frame_id': f, 'source_timestamp_ns': None, 'clock_domain': None, 'match_method': 'index_map', 'delta_ns': None, 'source_locator': row['labels'][1]} for _ in [0] if 'labels' in row}, component_sources={k: v[1] for k, v in row.items()})) view = View(path, 'dex-ycb', args.release_id, seq, serial, source_rows, sampling='dense' if ids == list(range(ids[0], ids[-1] + 1)) else 'sparse') view.valid_rules = { 'mano': 'Source pose_m present and not all zero; side model/calibration available', 'keypoints': 'Corresponding joint_2d/joint_3d present; whole-hand all -1 is missing, broadcast to its 21 points', 'pose': 'Source pose_y for this ycb_ids slot present and not an all-zero matrix', 'segment': 'Source seg array provided for this frame; region codes and entity references validated', 'relations': 'Source sequence ycb_grasp_ind resolves through ycb_ids; broadcast sequence grasp to selected frames', } view.full_jpeg = getattr(args, 'jpeg_full_check', False) view.meta['view_type'] = 'exo' view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} subject = re.search(r'subject-(\d+)', seq) if subject and 1 <= int(subject[1]) <= 10: index = int(subject[1]) view.meta.update(split='val' if index == 7 else 'test' if index in (8, 9) else 'train', split_scheme='Dex-YCB/s1', split_source_locator={ 'url': 'https://github.com/NVlabs/dex-ycb-toolkit/blob/master/dex_ycb_toolkit/dex_ycb.py', 'rule': 's1 unseen-subject: 01-06/10 train, 07 val, 08-09 test'}) view.meta.pop('split_reason', None) view.rgb([frames[f]['color'][0] if 'color' in frames[f] else None for f in ids], {'frames_ref': 'camera/frames.jsonl'}) n = len(ids) intr = calib.intrinsics.get(serial) K = None if intr is None else np.array([[intr['fx'], 0, intr['cx']], [0, intr['fy'], intr['cy']], [0, 0, 1]]) ext = calib.extrinsics.get(str(meta['extrinsics']), {}).get(serial) E = None if ext is not None: E = np.eye(4) E[:3] = np.asarray(ext).reshape(3, 4) E = np.linalg.inv(E) view.camera(K, calibration_locator(calib_path, f'calibration/intrinsics/{serial}_640x480.yml'), E, calibration_locator(calib_path, f'calibration/extrinsics_{meta["extrinsics"]}/extrinsics.yml', conversion='inverse of source T_world_from_camera')) sides = meta.get('mano_sides') if sides not in (['left'], ['right']): raise ValueError(f'expected exactly one anatomical source hand: {sides}') side = sides[0] slot = ['left', 'right'].index(side) cal_name = meta['mano_calib'][0] if isinstance(meta['mano_calib'], list) else meta['mano_calib'] labels = [dict(np.load(frames[f]['labels'][0])) if 'labels' in frames[f] else {} for f in ids] label_loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources.labels'} motion = np.full((n, 2, 61), np.nan, np.float32) mv = np.zeros((n, 2), bool) if side in models and any('pose_m' in lab for lab in labels): for i, lab in enumerate(labels): if 'pose_m' not in lab: continue pose = np.asarray(lab['pose_m']).reshape(51) if not np.any(pose): # Official Dex-YCB missing-pose sentinel, independent of joints/seg. continue motion[i, slot] = np.r_[pose[:3], pca_to_axis_angle(pose[3:48], models[side]), calib.betas[cal_name], pose[48:51]] mv[i, slot] = True view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, ['T', 'hand', 'parameter'], label_loc, model_profile=model_profile(models), calibration_source=calibration_locator(calib_path, f'calibration/mano_{cal_name}/mano.yml'), provenance={'kind': 'format_conversion', 'method': 'source PCA @ hands_components + hands_mean; explicit axis-angle consumed with flat_hand_mean=true'}) elif any('pose_m' in lab for lab in labels): view.absent('mano', 'Source PCA exists; provide --mano-dir to expand it', 'dependency_missing') else: view.absent('mano', 'No source pose_m field') for source_key, key, dim, unit in [('joint_2d', 'uv', 2, 'pixel'), ('joint_3d', 'xyz', 3, 'm')]: if not any(source_key in x for x in labels): view.absent('keypoints_' + key, 'No source ' + source_key) continue points = np.full((n, 2, 21, dim), np.nan, np.float32) valid = np.zeros((n, 2, 21), bool) for i, lab in enumerate(labels): if source_key not in lab: continue p = np.asarray(lab[source_key]).reshape(21, dim) points[i, slot] = p valid[i, slot] = not np.all(p == -1) # Official sentinel covers the whole source hand. # An individual off-image point (-1, -1) is not evidence of missing annotation. view.tensor('keypoints_' + key, f'keypoints/{key}/v1', f'annotation/keypoints/{key}.pt', points, valid, ['T', 'hand', 'keypoint', 'coordinate'], label_loc, keypoint_schema='mano21/v1', unit=unit) ycb_ids = [int(x) for x in meta['ycb_ids']] for j, oid in enumerate(ycb_ids): entity = f'ycb_{oid:02d}' view.object(entity, meta_loc, source_object_id=oid, category_id=oid) poses = np.full((n, 4, 4), np.nan, np.float32) valid = np.zeros(n, bool) for i, lab in enumerate(labels): if 'pose_y' in lab: pose = np.asarray(lab['pose_y']) if pose.shape != (len(ycb_ids), 3, 4): raise ValueError('pose_y shape differs from ycb_ids') if np.any(pose[j]): # Official all-zero missing object pose sentinel. poses[i] = np.eye(4) poses[i, :3] = pose[j] valid[i] = True if any('pose_y' in lab for lab in labels): view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', poses, valid, ['T', 'row', 'column'], label_loc, convention='T_camera_from_object', unit='m') else: view.absent('pose_' + entity, 'No source pose_y field') if oid in assets: mesh_asset(view, entity, assets[oid], assets[oid] / 'textured_simple.obj', locator(asset_archive, f'models/{assets[oid].name}/textured_simple.obj')) else: view.absent('mesh_' + entity, 'models.tar.gz unavailable', 'not_downloaded') if any('seg' in lab for lab in labels): mask_rows = [] width, height = view.meta['camera']['image_size'] for i, lab in enumerate(labels): values = np.unique(lab.get('seg', np.zeros((height, width), np.uint8))) mappings = [] for value in values: value = int(value) if value == 0: continue if value != 255 and value not in ycb_ids: raise ValueError(f'unknown Dex-YCB region value {value}') mappings.append(dict(mask_value=value, category_id='hand' if value == 255 else value, entity_id='hand_' + side if value == 255 else f'ycb_{value:02d}', part_id=None, source_instance_id=value)) mask_rows.append(dict(frame_index=i, labels=mappings)) view.raster('segment', (lab.get('seg', np.zeros((height, width), np.uint16)) for lab in labels), ['seg' in lab for lab in labels], label_loc, mask_rows) view.meta['components']['segment'].update(coverage={'kind': 'selected_entities', 'entities': ['hand_' + side] + [f'ycb_{o:02d}' for o in ycb_ids]}, source_zero_meaning='background') else: view.absent('segment', 'No source seg field') if any('aligned_depth_to_color' in frames[f] for f in ids): def depths(): width, height = view.meta['camera']['image_size'] for f in ids: item = frames[f].get('aligned_depth_to_color') if item is None: yield np.full((height, width), np.nan, np.float32) else: with Image.open(item[0]) as im: yield np.asarray(im).astype(np.float32) / 1000.0 view.raster('depth', depths(), None, {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources.aligned_depth_to_color', 'conversion': 'millimetres to metres'}) else: view.absent('depth', 'No source aligned_depth_to_color frames') grasp = meta.get('ycb_grasp_ind') if grasp is not None: if not 0 <= int(grasp) < len(ycb_ids): raise ValueError('invalid ycb_grasp_ind') relation = dict(relation_type='grasp', subject_id='hand_' + side, object_id=f'ycb_{ycb_ids[int(grasp)]:02d}', status='positive', source_locator=meta_loc, provenance={'kind': 'source', 'method': 'sequence ycb_grasp_ind resolved through ycb_ids; not per-frame contact'}) view.relations([{'frame_index': i, 'relations': [relation]} for i in range(n)], np.ones(n, bool), meta_loc) else: view.absent('relations', 'No source grasp/contact relation') return view.finish()
MEMBER = re.compile(r'^([^/]+)/(\d{8}_\d{6})/(meta\.yml|(\d{12})/(color|labels|aligned_depth_to_color)_(\d+)\.(jpg|npz|png))$')
def convert_archive(archive, args, out, calib, calib_path, models, assets, asset_archive): selected_views = set(args.views.split(',')) if args.views else None done = 0 current, meta, meta_loc, rows = None, None, None, {} with tempfile.TemporaryDirectory(prefix='dex-source-') as wd: work = Path(wd) def flush(): nonlocal done if not rows: return seq = archive.name.split('.tar')[0] + '_' + current reports = {} with sequence_dir(out, seq) as target: for serial, frames in sorted(rows.items()): reports[serial] = convert_view(target / serial, args, seq, serial, frames, meta, meta_loc, calib, calib_path, models, assets, asset_archive) build_record(out, seq, reports) for staged in list(work.iterdir()): if staged.is_dir(): shutil.rmtree(staged) else: staged.unlink() done += 1 print(f'Converted {seq}', flush=True) with tarfile.open(archive, 'r|gz') as tf: for member in tf: match = MEMBER.fullmatch(member.name) if not member.isfile() or not match: continue seq = match[2] if seq != current: flush() if args.limit and done >= args.limit: break current, meta, meta_loc, rows = seq, None, None, {} data_kind = match[3] if data_kind == 'meta.yml': data = tf.extractfile(member).read() meta = yaml_load_bytes(data) meta_loc = locator(archive, member.name, data) continue serial, kind, f = match[4], match[5], int(match[6]) if selected_views and serial not in selected_views or args.max_frames and f >= args.max_frames: continue data = tf.extractfile(member).read() dest = safe_member(work, member.name) dest.parent.mkdir(parents=True, exist_ok=True) dest.write_bytes(data) row = rows.setdefault(serial, {}).setdefault(f, {}) if kind in row: raise ValueError('duplicate archive frame') row[kind] = (dest, locator(archive, member.name, data)) else: flush() return done
def main(argv=None): p = parser('dex-ycb', __doc__) p.add_argument('--subjects') args = p.parse_args(argv) archives = sorted({a for r in roots(args.root) for a in r.glob('*-subject-*.tar.gz')}) if args.subjects: subjects = {s.strip().zfill(2) for s in args.subjects.split(',')} archives = [a for a in archives if re.search(r'subject-(\d+)', a.name)[1] in subjects] if not archives: p.error('no Dex-YCB subject archives found') cp = find_file(args.root, 'calibration.tar.gz') or find_file(args.root, 'calibration') if cp is None: p.error('calibration source missing') calib = Calibration(cp.parent) models = mano_models(args.mano_dir) out = release(args, 'dex-ycb') with tempfile.TemporaryDirectory(prefix='dex-models-') as wd: assets, asset_archive = prepare_models(args.root, Path(wd)) for archive in archives: convert_archive(archive, args, out, calib, cp, models, assets, asset_archive) return 0
if __name__ == '__main__': raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678#!/usr/bin/env python3"""H2O native RGB-D, MANO, joints and objects → CONTRACT.md v1.0 (no rendered masks)."""from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutorimport ioimport jsonimport multiprocessingimport osimport reimport shutilimport tarfileimport tempfileimport threadingfrom pathlib import Pathimport zipfile
# Bound native libraries before loading NumPy/Torch; each worker still uses independent FFmpeg processes.for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): os.environ[key] = '1'
import numpy as npfrom PIL import Imageimport torch
from warehouse_v1_0 import (View, build_record, check_mesh, find_file, locator, mano_models, mesh_asset, model_profile, parser, release, roots, safe_member, sequence_dir, sha256)
OBJECTS = {1: 'book', 2: 'espresso', 3: 'lotion', 4: 'spray', 5: 'milk', 6: 'cocoa', 7: 'chips', 8: 'cappuccino'}MEMBER = re.compile(r'^(?:h2o_CASA/)?(subject\d+)/([^/]+)/(\d+)/(cam\d)/(.+)$')FRAME = re.compile(r'(rgb|depth|cam_pose|hand_pose|hand_pose_mano|obj_pose|obj_pose_rt)/(\d+)\.(png|jpg|txt)$')
def load_splits(root): archive = find_file(root, 'label_split.zip') result = {} if archive is not None: with zipfile.ZipFile(archive) as z: for split in ('train', 'val', 'test'): member = f'label_split/action_{split}.txt' for line_no, line in enumerate(z.read(member).decode().splitlines(), 1): fields = line.split() if len(fields) < 2 or fields[1] == 'path': continue key = fields[1] if key in result and result[key][0] != split: raise ValueError('conflicting official splits') result[key] = (split, locator(archive, member, record=line_no)) return result
def load_assets(root, work): archive = find_file(root, 'object.zip') if archive is None: return {}, None with zipfile.ZipFile(archive) as z: for member in z.infolist(): if member.is_dir(): continue path = safe_member(work, member.filename) path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(z.read(member)) result = {} for oid, name in OBJECTS.items(): directory = work / 'object' / name aliases = [] # Source cocoa.obj -> ovomaltine.mtl -> cocoa.png, but the ZIP names the # supplied texture ovomaltine.png. Keep all originals and add a byte-identical alias. if name == 'cocoa' and not (directory / 'cocoa.png').exists(): mtl = directory / 'ovomaltine.mtl' if mtl.is_file() and 'map_Kd cocoa.png' in mtl.read_text().splitlines(): texture = directory / 'ovomaltine.png' shutil.copyfile(texture, directory / 'cocoa.png') aliases.append({'file': 'cocoa.png', 'sha256': sha256(texture), 'source': locator(archive, 'object/cocoa/ovomaltine.png')}) candidates = list(directory.glob('*.obj')) if len(candidates) != 1: raise ValueError(f'expected one source OBJ for {name}') check_mesh(candidates[0], directory) # Fail before decoding any large subject archive. result[oid] = (directory, candidates[0], aliases) return result, archive
def convert_view(path, args, seq, cam, rows, intr, splits, models, assets, asset_archive): codec_threads = getattr(args, 'codec_threads', 1) ids = list(range(min(rows), max(rows) + 1)) for f in ids: rows.setdefault(f, {}) n = len(ids) if not n: raise ValueError('no RGB frames') split, split_loc = splits.get(seq, ('unknown', None)) frame_rows = [dict(source_frame_id=f, sync_id=f'{seq}:{f}', source_locator=rows[f]['rgb'][1] if 'rgb' in rows[f] else {'sequence': seq, 'camera': cam, 'source_frame_id': f, 'missing_rgb': True}, component_sources={k: item[1] for k, item in rows[f].items()}, annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, clock_domain=None, match_method='index_map', delta_ns=None) for k in rows[f] if k != 'rgb'}) for f in ids] view = View(path, 'H2O', args.release_id, seq.replace('/', '_'), cam, frame_rows, split=split) view.valid_rules = { 'mano': 'Per-hand hand_pose_mano flag equals 1; corresponding side model available', 'keypoints': "Per-hand hand_pose flag equals 1, broadcast to that hand's 21 source points independently of MANO", 'pose': 'Source obj_pose_rt class equals this nonzero object class', 'points': 'Source obj_pose class equals this nonzero object class, broadcast to its 21 points', } view.full_jpeg = getattr(args, 'jpeg_full_check', False) view.meta['view_type'] = 'ego' if cam == 'cam4' else 'exo' if cam in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown' view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} if split_loc: view.meta.update(split_scheme='official_action_split', split_source_locator=split_loc) # In the measured 275 H2O views, exact FFV1 was always smaller than exact H.264. view.rgb([rows[f]['rgb'][0] if 'rgb' in rows[f] else None for f in ids], {'frames_ref': 'camera/frames.jsonl'}, ffv1_first=True, codec_threads=codec_threads, stream_source=getattr(args, 'stream_media', False)) loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} if intr is not None: fx, fy, cx, cy, width, height = np.loadtxt(io.BytesIO(intr[0])).ravel() if [int(width), int(height)] != view.meta['camera']['image_size']: raise ValueError('source intrinsics resolution mismatch') K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) view.camera(K, intr[1]) camps = np.full((n, 4, 4), np.nan, np.float32) cv = np.zeros(n, bool) data = [] for i, f in enumerate(ids): lab = {k: np.loadtxt(io.BytesIO(item[0])).ravel() for k, item in rows[f].items() if k not in ('rgb', 'depth')} data.append(lab) if 'cam_pose' in lab: camps[i] = np.linalg.inv(lab['cam_pose'].reshape(4, 4)) cv[i] = True if cv.any(): view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', camps, cv, ['T', 'row', 'column'], loc, convention='T_camera_from_world', source_convention='T_world_from_camera') motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) points, pv = np.full((n, 2, 21, 3), np.nan, np.float32), np.zeros((n, 2, 21), bool) object_ids = set() for i, lab in enumerate(data): if 'hand_pose_mano' in lab: hands = lab['hand_pose_mano'].reshape(2, 62) for side, row in enumerate(hands): if row[0] not in (0, 1): raise ValueError('unexpected H2O MANO presence flag') if row[0] == 1: motion[i, side] = np.r_[row[4:52], row[52:62], row[1:4]] mv[i, side] = True if 'hand_pose' in lab: hands = lab['hand_pose'].reshape(2, 64) for side, row in enumerate(hands): if row[0] not in (0, 1): raise ValueError('unexpected H2O keypoint presence flag') if row[0] == 1: points[i, side] = row[1:].reshape(21, 3) pv[i, side] = True for key in ('obj_pose', 'obj_pose_rt'): if key in lab and lab[key][0] != 0: object_ids.add(int(lab[key][0])) if any('hand_pose_mano' in lab for lab in data): if len(models) == 2: view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) else: view.absent('mano', 'Source parameters exist; --mano-dir must identify both model profiles', 'dependency_missing') if any('hand_pose' in lab for lab in data): view.tensor('keypoints_xyz', 'keypoints/xyz/v1', 'annotation/keypoints/xyz.pt', points, pv, ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='m') for oid in sorted(object_ids): if oid not in OBJECTS: raise ValueError(f'unknown H2O object class {oid}') entity = OBJECTS[oid] view.object(entity, loc, category_id=oid, source_object_id=oid) poses, ov = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) pts, kv = np.full((n, 21, 3), np.nan, np.float32), np.zeros((n, 21), bool) for i, lab in enumerate(data): if 'obj_pose_rt' in lab and lab['obj_pose_rt'][0] == oid: poses[i] = lab['obj_pose_rt'][1:].reshape(4, 4) ov[i] = True if 'obj_pose' in lab and lab['obj_pose'][0] == oid: pts[i] = lab['obj_pose'][1:].reshape(21, 3) kv[i] = True if ov.any(): view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', poses, ov, ['T', 'row', 'column'], loc, convention='T_camera_from_object', unit='m') if kv.any(): view.tensor('points_' + entity, 'object_keypoints/camera/v1', f'annotation/object/{entity}/keypoints/xyz.pt', pts, kv, ['T', 'keypoint', 'coordinate'], loc, keypoint_schema='H2O_official_object21', keypoint_names=['center'] + [f'corner_{i}' for i in range(8)] + [f'edge_midpoint_{i}' for i in range(12)], source_order='official obj_point_order.jpg: center, 8 corners, 12 edge midpoints', unit='m') if oid in assets: directory, obj, aliases = assets[oid] asset_loc = locator(asset_archive, f'object/{entity}/{obj.name}') if aliases: asset_loc['texture_aliases'] = aliases mesh_asset(view, entity, directory, obj, asset_loc) else: view.absent('mesh_' + entity, 'Source object.zip unavailable', 'not_downloaded') if any('depth' in rows[f] for f in ids): width, height = view.meta['camera']['image_size'] depth_threads = getattr(args, 'depth_threads', 1) def read_depth(f): item = rows[f].get('depth') if item: with Image.open(item[0]) as im: return np.asarray(im).astype(np.float32) / 1000.0 return np.full((height, width), np.nan, np.float32) def depths(): if depth_threads == 1: yield from map(read_depth, ids) else: with ThreadPoolExecutor(max_workers=depth_threads) as pool: # Ordered batches bound decoded arrays to depth_threads frames per view. for start in range(0, len(ids), depth_threads): yield from pool.map(read_depth, ids[start:start + depth_threads]) view.raster('depth', depths(), None, loc | {'source_field': 'component_sources.depth', 'definition': 'https://github.com/taeinkwon/h2oplayer/blob/main/utils.py', 'conversion': 'registered millimetre camera-Z to metres; no viewer range clipping'}, codec_threads=codec_threads, stream=getattr(args, 'stream_media', False)) else: view.absent('depth', 'No source depth frames') view.absent('segment', 'H2O provides no native segmentation; rendering deferred to v2.0') view.absent('relations', 'No source contact/grasp annotation') return view.finish()
def convert_archive(archive, args, out, splits, models, assets, asset_archive, view_pool=None, ram_budget=None): selected_views = set(args.views.split(',')) if args.views else None subjects = {'subject' + s.strip() for s in args.subjects.split(',')} if args.subjects else None current, rows, intrinsics, done = None, {}, {}, 0 published_views = set() camera_jobs, closed_cameras = {}, set() last_camera = None pipeline_active = False ram_reserved = 0 try: with tempfile.TemporaryDirectory(prefix='h2o-source-') as wd, \ tempfile.TemporaryDirectory(prefix='h2o-ram-', dir=args.ram_stage_dir) as rd: work, ram_work = Path(wd), Path(rd) def queue_camera(cam): if cam in closed_cameras: return closed_cameras.add(cam) if cam not in published_views and rows.get(cam): camera_jobs[cam] = view_pool.submit(convert_view, work / '.converted' / cam, args, '/'.join(current), cam, rows[cam], intrinsics.get(cam), splits, models, assets, asset_archive) def flush(): nonlocal done, ram_reserved if not rows: return seq = '/'.join(current) reports, pending = {}, {} for cam, frames in sorted(rows.items()): existing = out / 'data' / seq.replace('/', '_') / cam if (existing / 'metainfo.json').is_file(): old_frames = [json.loads(line) for line in (existing / 'camera/frames.jsonl').read_text().splitlines()] if [f['source_frame_id'] for f in old_frames] != list(range(min(frames), max(frames) + 1)): raise ValueError('existing view has different sampling; choose a new release-id') for frame in old_frames: incoming = frames.get(frame['source_frame_id'], {}) previous = frame.get('component_sources', {}) if set(previous) != set(incoming) or any(previous[k].get('sha256') != v[1].get('sha256') for k, v in incoming.items()): raise ValueError('duplicate H2O view differs from the published source; choose a new release-id') else: pending[cam] = frames if pending: if pipeline_active: for cam in pending: queue_camera(cam) failure = None for cam, job in camera_jobs.items(): try: reports[cam] = job.result() except Exception as exc: failure = failure or exc if failure is not None: raise failure with sequence_dir(out, seq.replace('/', '_')) as target: if pipeline_active: for cam in pending: shutil.move(work / '.converted' / cam, target / cam) elif view_pool is None: for cam, frames in pending.items(): reports[cam] = convert_view(target / cam, args, seq, cam, frames, intrinsics.get(cam), splits, models, assets, asset_archive) else: jobs = {cam: view_pool.submit(convert_view, target / cam, args, seq, cam, frames, intrinsics.get(cam), splits, models, assets, asset_archive) for cam, frames in pending.items()} failure = None # Every sibling must finish before sequence_dir can remove its inputs. for cam, job in jobs.items(): try: reports[cam] = job.result() except Exception as exc: failure = failure or exc if failure is not None: raise failure build_record(out, seq.replace('/', '_'), reports) for directory in (work, ram_work): for staged in list(directory.iterdir()): if staged.is_dir(): shutil.rmtree(staged) else: staged.unlink() if ram_budget is not None: lock, used, limit = ram_budget with lock: used[0] -= ram_reserved ram_reserved = 0 done += 1 print(f'{"Converted" if pending else "Verified existing"} {seq}', flush=True) # Uncompressed CASA supports seeking over large frames; gzip is single-pass. mode = 'r:' if archive.suffix == '.tar' else 'r|gz' try: with tarfile.open(archive, mode) as tf: for member in tf: match = MEMBER.fullmatch(member.name) if not member.isfile() or not match: continue subj, scene, seq, cam, tail = match.groups() if subjects and subj not in subjects: continue key = (subj, scene, seq) if key != current: flush() if args.limit and done >= args.limit: break current, rows, intrinsics = key, {}, {} camera_jobs.clear() closed_cameras.clear() last_camera = None pipeline_active = args.camera_pipeline published_views = {view.name for view in (out / 'data' / '_'.join(key)).glob('cam*') if (view / 'metainfo.json').is_file()} if selected_views and cam not in selected_views: continue if pipeline_active and cam != last_camera: if last_camera is not None: queue_camera(last_camera) if cam in closed_cameras: # Complete queued readers before accepting late fields for those cameras. for job in camera_jobs.values(): try: job.result() except Exception: pass shutil.rmtree(work / '.converted', ignore_errors=True) camera_jobs.clear() closed_cameras.clear() pipeline_active = False print(f'Camera-order fallback: {"/".join(current)}', flush=True) last_camera = cam frame = FRAME.fullmatch(tail) if tail != 'cam_intrinsics.txt' and not frame: continue if frame and args.max_frames and int(frame[2]) >= args.max_frames: continue data = tf.extractfile(member).read() if tail.endswith('.txt'): payload = data # Small source annotations stay in RAM, not thousands of HDD files. else: staging = work if ram_budget is not None and cam not in published_views: lock, used, limit = ram_budget needed = (len(data) + 4095) // 4096 * 4096 with lock: if used[0] + needed <= limit: used[0] += needed ram_reserved += needed staging = ram_work payload = safe_member(staging, member.name) if cam not in published_views: payload.parent.mkdir(parents=True, exist_ok=True) payload.write_bytes(data) # Published views still verify source bytes, but never read their staging paths. item = (payload, locator(archive, member.name, data)) if tail == 'cam_intrinsics.txt': intrinsics[cam] = item else: kind, f = frame[1], int(frame[2]) row = rows.setdefault(cam, {}).setdefault(f, {}) if kind in row: raise ValueError('duplicate H2O frame') row[kind] = item else: flush() finally: # Never delete staging while a closed-camera job can still read from it. for job in camera_jobs.values(): try: job.result() except Exception: pass finally: if ram_budget is not None: lock, used, limit = ram_budget with lock: used[0] -= ram_reserved return done
def main(argv=None): p = parser('H2O', __doc__) p.set_defaults(release_id='shared-v1.0') p.add_argument('--workers', type=int, choices=range(1, 5), default=1, help='Independent subject archives in parallel, 1..4; benchmark before using >2') p.add_argument('--view-backend', choices=('threads', 'processes'), default='threads', help='Use spawn processes to isolate Python camera processing') p.add_argument('--camera-pipeline', action='store_true', help='Overlap contiguous-camera extraction and conversion; reject interleaved input') p.add_argument('--ffv1-slices', type=int, choices=(16,), help='Optional FFV1 v3 slice parallelism; decoded frames must still match exactly') p.add_argument('--view-workers', type=int, choices=range(1, 17), default=1, help='Shared camera-view conversion pool, independent of archive readers') p.add_argument('--ram-stage-dir', type=Path, help='Optional tmpfs staging; excess PNGs fall back to disk') p.add_argument('--ram-stage-gib', type=int, choices=range(1, 65), default=32, help='Shared PNG tmpfs quota across all archive readers, not per worker') p.add_argument('--stream-media', action='store_true', help='Pipe RGB/depth frames to FFmpeg instead of spooling huge RAW files') p.add_argument('--codec-threads', type=int, choices=(1, 2, 4, 8, 10), default=4, help='FFV1 slice threads per encode; default 4, use 10 for the current full run') p.add_argument('--decode-threads', type=int, choices=(1, 2, 4, 8, 10), default=1, help='FFmpeg threads for source RGB decoding and decoded-media checks') p.add_argument('--depth-threads', type=int, choices=(1, 2, 4), default=1, help='Bounded ordered source depth PNG loading per worker') p.add_argument('--subjects') p.add_argument('--include-casa', action='store_true') p.add_argument('--archive', type=Path, help='Convert one explicit source archive') args = p.parse_args(argv) if args.camera_pipeline and args.view_workers < 2: p.error('--camera-pipeline requires at least two --view-workers') os.environ['HAND_WAREHOUSE_FFMPEG_THREADS'] = str(args.decode_threads) if args.ffv1_slices is None: os.environ.pop('HAND_WAREHOUSE_FFV1_SLICES', None) else: os.environ['HAND_WAREHOUSE_FFV1_SLICES'] = str(args.ffv1_slices) if args.include_casa and args.workers != 1: p.error('CASA can share sequence IDs with subject archives; convert it sequentially in a separate release') archives = [args.archive.expanduser()] if args.archive else sorted( {a for root in roots(args.root) for a in root.glob('subject*_v1_1.tar.gz')}) if args.subjects and not args.archive: requested = {'subject' + s.strip() for s in args.subjects.split(',')} archives = [arc for arc in archives if arc.name.split('_', 1)[0] in requested] if args.include_casa: casa = find_file(args.root, 'h2o_CASA.tar') if casa: archives.append(casa) if not archives: p.error('no H2O archives found') out = release(args, 'H2O') source_mapping = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/h2o-RAW_TO_SHARED.md', Path(__file__).resolve().parents[1] / 'doc/RAW_TO_SHARED.md', out / 'doc/RAW_TO_SHARED.md') if p.is_file()) mapping = out / 'doc/RAW_TO_SHARED.md' if mapping.exists() and mapping.read_bytes() != source_mapping.read_bytes(): raise ValueError('RAW_TO_SHARED.md changed; choose a new release-id') if not mapping.exists(): shutil.copyfile(source_mapping, mapping) os.environ.pop('HAND_WAREHOUSE_MEDIA_TMPDIR', None) ram_budget = None if args.ram_stage_dir is not None: args.ram_stage_dir = args.ram_stage_dir.expanduser().resolve() if not args.ram_stage_dir.is_relative_to(Path('/dev/shm').resolve()): p.error('--ram-stage-dir must be on /dev/shm; it is temporary input, not an output dataset') args.ram_stage_dir.mkdir(parents=True, exist_ok=True) limit = args.ram_stage_gib * 1024**3 if shutil.disk_usage(args.ram_stage_dir).free < limit + 8 * 1024**3: p.error('not enough tmpfs headroom for the requested shared staging quota') ram_budget = (threading.Lock(), [0], limit) if args.stream_media: os.environ['HAND_WAREHOUSE_MEDIA_TMPDIR'] = str(args.ram_stage_dir) torch.set_num_threads(1) models, splits = mano_models(args.mano_dir), load_splits(args.root) executor = ProcessPoolExecutor if args.view_backend == 'processes' else ThreadPoolExecutor options = {'mp_context': multiprocessing.get_context('spawn')} if args.view_backend == 'processes' else {'thread_name_prefix': 'h2o-view'} with tempfile.TemporaryDirectory(prefix='h2o-assets-') as wd, \ executor(max_workers=args.view_workers, **options) as views: assets, asset_archive = load_assets(args.root, Path(wd)) def convert_one(archive): return convert_archive(archive, args, out, splits, models, assets, asset_archive, views if args.view_workers > 1 else None, ram_budget) if args.workers == 1: for archive in archives: convert_one(archive) else: with ThreadPoolExecutor(max_workers=args.workers) as pool: for archive, count in zip(archives, pool.map(convert_one, archives), strict=True): print(f'Archive {archive.name}: {count} sequences', flush=True) return 0
if __name__ == '__main__': raise SystemExit(main())
# TODO(v2.0): 以下旧 MANO 网格和渲染分割代码仅保留备查;v1.0 不生成标注。# def load_mano_model(path: Path):# """MPI MANO pkl → numpy 字典。shapedirs 在 pkl 内为 chumpy Select(对 (778,3,20) 基# 底 flat 选取前 10 个 shape 分量;idxs 已核实等价于 base[:,:,:10])。"""# with open(path, "rb") as f:# d = _ManoUnpickler(f, encoding="latin1").load()# sd = d["shapedirs"]# base = np.asarray(sd.a.x, np.float64) # (778, 3, 20)# shapedirs = base.reshape(-1)[np.asarray(sd.idxs)].reshape(base.shape[0], 3, -1)# jreg = d["J_regressor"]# jreg = np.asarray(jreg.todense()) if hasattr(jreg, "todense") else np.asarray(jreg)# return {"v_template": np.asarray(d["v_template"], np.float64),# "shapedirs": shapedirs,# "posedirs": np.asarray(d["posedirs"], np.float64),# "weights": np.asarray(d["weights"], np.float64),# "J_regressor": np.asarray(jreg, np.float64),# "kintree": np.asarray(d["kintree_table"], np.int64),# "faces": np.asarray(d["f"], np.int64)}### def rodrigues(r):# """axis-angle (N,3) → 旋转矩阵 (N,3,3)。公式 I + sinθ·K + (1−cosθ)·K²(已对 scipy 核验)。"""# r = np.asarray(r, np.float64).reshape(-1, 3)# th = np.linalg.norm(r, axis=1)# R = np.zeros((len(r), 3, 3))# nz = th > 1e-12# R[~nz] = np.eye(3)# k = r[nz] / th[nz, None]# K = np.zeros((len(k), 3, 3))# K[:, 0, 1], K[:, 0, 2], K[:, 1, 2] = -k[:, 2], k[:, 1], -k[:, 0]# K[:, 1, 0], K[:, 2, 0], K[:, 2, 1] = k[:, 2], -k[:, 1], k[:, 0]# s, c = np.sin(th[nz])[:, None, None], np.cos(th[nz])[:, None, None]# R[nz] = np.eye(3) + s * K + (1 - c) * (K @ K)# return R### def _mano_chain(model, betas, pose):# """返回 (v_shaped, J, Rs, G):G 为 16 个关节的全局变换(平移列 = 关节位置)。"""# v = model["v_template"] + np.einsum("nkc,c->nk", model["shapedirs"], betas)# J = model["J_regressor"] @ v# Rs = rodrigues(np.asarray(pose, np.float64).reshape(16, 3))# kt = model["kintree"]# G = np.zeros((16, 4, 4))# for j in range(16):# p = kt[0, j] if j else -1# loc = np.eye(4)# loc[:3, :3] = Rs[j]# loc[:3, 3] = J[j] - (J[p] if j else 0.0)# G[j] = loc if not j else G[p] @ loc# return v, J, Rs, G### def mano_forward(model, betas, pose, transl):# """MANO LBS 前向(经典蒙皮 M_j = G_j·G0_j⁻¹;对 hand_pose 21 关节实证 0.0 mm)。# pose: 48 axis-angle([0:3] 全局);返回相机系米顶点 (778,3)。"""# v, J, Rs, G = _mano_chain(model, betas, pose)# lrot = (Rs[1:] - np.eye(3)).ravel()# v_posed = v + np.einsum("nkc,c->nk", model["posedirs"], lrot)# kt = model["kintree"]# G0 = np.zeros((16, 4, 4))# for j in range(16):# p = kt[0, j] if j else -1# loc = np.eye(4)# loc[:3, 3] = J[j] - (J[p] if j else 0.0)# G0[j] = loc if not j else G0[p] @ loc# M = np.einsum("nj,jab->nab", model["weights"], G @ np.linalg.inv(G0))# out = np.einsum("nab,nb->na", M[:, :3, :3], v_posed) + M[:, :3, 3]# return out + np.asarray(transl, np.float64)### def mano_chain_joints(model, betas, pose, transl):# """16 个关节位置(相机系米)= 链平移列;自检用。"""# _, _, _, G = _mano_chain(model, betas, pose)# return G[:, :3, 3] + np.asarray(transl, np.float64)### def rasterize(verts_cam, faces, labels, W, H, fx, fy, cx, cy):# z = verts_cam[:, 2]# P = faces# ok = (z[P] > 0.02).all(1) # 任一顶点在相机后 → 丢弃该三角形# P, labels = P[ok], labels[ok]# if len(P) == 0:# return np.zeros((H, W), np.uint16), np.zeros(0, np.int64)# x = verts_cam[:, 0] / z * fx + cx# y = verts_cam[:, 1] / z * fy + cy# xa = np.maximum(0, np.minimum(np.floor(x[P[:, 0]]), np.minimum(# np.floor(x[P[:, 1]]), np.floor(x[P[:, 2]]))).astype(np.int64))# xb = np.minimum(W - 1, np.maximum(np.ceil(x[P[:, 0]]), np.maximum(# np.ceil(x[P[:, 1]]), np.ceil(x[P[:, 2]]))).astype(np.int64))# ya = np.maximum(0, np.minimum(np.floor(y[P[:, 0]]), np.minimum(# np.floor(y[P[:, 1]]), np.floor(y[P[:, 2]]))).astype(np.int64))# yb = np.minimum(H - 1, np.maximum(np.ceil(y[P[:, 0]]), np.maximum(# np.ceil(y[P[:, 1]]), np.ceil(y[P[:, 2]]))).astype(np.int64))# xa, ya = np.minimum(xa, xb), np.minimum(ya, yb) # 完全出画的三角形 → 空 bbox# wdt, hgt = xb - xa + 1, yb - ya + 1# cnt = wdt * hgt# tot = int(cnt.sum())# tri = np.repeat(np.arange(len(P)), cnt)# k = np.arange(tot) - (np.cumsum(cnt) - cnt)[tri]# px = xa[tri] + k % wdt[tri] + 0.5# py = ya[tri] + k // wdt[tri] + 0.5# ax, ay = x[P[tri, 0]], y[P[tri, 0]]# bx, by = x[P[tri, 1]], y[P[tri, 1]]# cx_, cy_ = x[P[tri, 2]], y[P[tri, 2]]# area = ((x[P[:, 1]] - x[P[:, 0]]) * (y[P[:, 2]] - y[P[:, 0]])# - (y[P[:, 1]] - y[P[:, 0]]) * (x[P[:, 2]] - x[P[:, 0]]))# areat = area[tri]# e0 = (bx - ax) * (py - ay) - (by - ay) * (px - ax)# e1 = (cx_ - bx) * (py - by) - (cy_ - by) * (px - bx)# e2 = (ax - cx_) * (py - cy_) - (ay - cy_) * (px - cx_)# s = np.sign(areat)# inside = (np.abs(areat) > 1e-9) & ((e0 * s >= 0) & (e1 * s >= 0) & (e2 * s >= 0))# px, py, tri = px[inside], py[inside], tri[inside]# at = areat[inside]# w0, w1, w2 = e1[inside] / at, e2[inside] / at, e0[inside] / at# zz = w0 * z[P[tri, 0]] + w1 * z[P[tri, 1]] + w2 * z[P[tri, 2]]# pix = py.astype(np.int64) * W + px.astype(np.int64)# order = np.lexsort((zz, pix)) # 同像素按深度升序 → 首条即最近# pix, tri = pix[order], tri[order]# first = np.unique(pix, return_index=True)[1]# mask = np.zeros(H * W, np.uint16)# win = tri[first]# mask[pix[first]] = labels[win] + 1 # 临时标签 +1(0=背景)# return mask.reshape(H, W), np.bincount(labels[win] + 1)### # ============================================================================# # ffmpeg 写出与核验(与 convert_dexycb.py 同构)# # ============================================================================# verts, faces_all, labels = [], [], []# for ti, (tid, kind) in enumerate(tracks):# if kind == "hand_left" and b["mano"][0] > 0.5:# verts.append(mano_forward(mano_models["left"], b["mano"][52:62],# b["mano"][4:52], b["mano"][1:4]))# faces_all.append(mano_models["left"]["faces"])# elif kind == "hand_right" and b["mano"][62] > 0.5:# verts.append(mano_forward(mano_models["right"], b["mano"][114:124],# b["mano"][66:114], b["mano"][63:66]))# faces_all.append(mano_models["right"]["faces"])# elif isinstance(kind, tuple) and int(b["objp"][0]) == kind[1]:# M = np.asarray(b["objrt"][1:17], np.float64).reshape(4, 4)# V0, F0 = meshes[kind[1]]# verts.append(V0 @ M[:3, :3].T + M[:3, 3])# faces_all.append(F0)# else:# continue# labels.append(np.full(len(faces_all[-1]), ti))# if verts:# V = np.concatenate(verts)# offs = np.cumsum([0] + [len(v) for v in verts[:-1]])# F = np.concatenate([fa + o for fa, o in zip(faces_all, offs)])# mask, counts = rasterize(V, F, np.concatenate(labels),# IMG_W, IMG_H, fx, fy, cx, cy)# else:# mask, counts = np.zeros((IMG_H, IMG_W), np.uint16), np.zeros(0, np.int64)# lut = np.zeros(n_tracks + 1, np.uint16)# for ti in range(n_tracks):# present = ti + 1 < len(counts) and counts[ti + 1] > 0# if present:# presence[tracks[ti][0]][f] = True# if active_id[ti] is None:# pid = next(i for i in range(1, 65535) if i not in used)# used.add(pid)# active_id[ti], seg_start[ti] = pid, f# frame_maps[ti].append({"id": pid})# lut[ti + 1] = active_id[ti]# elif active_id[ti] is not None:# frame_maps[ti][-1]["frames"] = [seg_start[ti], f - 1]# segments[ti].append([seg_start[ti], f - 1])# used.discard(active_id[ti])# active_id[ti] = None# mw.write(lut[mask])
# TODO(v2.0): 旧物体尺寸派生代码;v1.0 仅保留源物体关键点。# pts = np.asarray(b["objp"][1:64], np.float64).reshape(21, 3)# half = np.abs((pts[1:9] - pts[0]) @ M[:3, :3]).max(0)# obj_recs.append({# "track_id": f"o{classes.index(c)}", "frame": f,# "mesh_ref": f"h2o/{OBJ_CLASSES[c]}.obj",# "pose": {"quat": rotmat_to_quat_wxyz(M[:3, :3])[0].tolist(),# "trans": M[:3, 3].tolist()},# "bbox_center3d": pts[0].tolist(),# "bbox_size": (2 * half).tolist()})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595#!/usr/bin/env python3"""HOI4D native observations and annotations → CONTRACT.md v1.0."""from collections import Counterfrom concurrent.futures import ThreadPoolExecutorfrom contextlib import ExitStackfrom functools import lru_cacheimport gzipimport ioimport jsonimport osfrom pathlib import Pathimport pickleimport reimport shutilimport shleximport posixpathimport subprocessimport tempfileimport tarfileimport threadingimport zipfile
# Each worker owns one Python thread; prevent native libraries spawning CPU pools.for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): os.environ[key] = '1'
import numpy as npfrom PIL import Imagefrom scipy.spatial.transform import Rotation
import torch
from warehouse_v1_0 import (View, build_record, check_mesh, decode_args, find_file, json_write, locator, mano_models, model_profile, parser, probe, release, run, safe_member, sequence_dir)
CATEGORIES = { 1: dict(cad="rigid/ToyCar", groups=[("main", [1], "Toy Car", 1)], hands={2: "right"}, objmap={"Toycar": "main"}), 2: dict(cad="rigid/Mug", groups=[("a", [1], "Mug", 2), ("b", [3], "Mug", 2)], hands={2: "right"}, objmap={"Watercup": "a"}), 3: dict(cad="articulated/Laptop", groups=[("main", [1, 3], "Laptop", 3)], hands={2: "right"}, objmap={"Laptopdisplay": "main", "Laptopkeyboard": "main"}), 4: dict(cad="articulated/StorageFurniture", groups=[("main", [1, 3, 4], "Storage Furniture", 4), ("bottle", [5], "Bottle", 5)], hands={2: "right"}, objmap={"Lockerbody": "main", "Lockersldingdoor": "main", "Lockerdrawer": "main", "Safebox": "main"}), 5: dict(cad="rigid/Bottle", groups=[("main", [1], "Bottle", 5), ("mug", [3], "Mug", 2)], hands={2: "right"}, objmap={"bottleddrinks": "main"}), 6: dict(cad="articulated/Safe", groups=[("main", [1, 3], "Safe", 6), ("bottle", [4], "Bottle", 5)], hands={2: "right"}, objmap={"Safebox": "main", "Safedoor": "main"}), 7: dict(cad="rigid/Bowl", groups=[("main", [1], "Bowl", 7), ("ball", [3], "Ball", None)], hands={2: "right"}, objmap={"bowl": "main"}), 8: dict(cad="articulated/Bucket", groups=[("a", [1, 3], "Bucket", 8), ("b", [4, 5], "Bucket", 8)], hands={2: "right", 6: "left"}, objmap={"bucket": "a", "Buckethandle": "a"}), 9: dict(cad="articulated/Scissors", groups=[("main", [1, 3], "Scissors", 9)], hands={2: "right"}, objmap={"scissors": "main", "scissors2": None}), # scissors2:场景道具,无掩码 11: dict(cad="articulated/Pliers", groups=[("main", [1, 3], "Pliers", 11)], hands={2: "right"}, objmap={"Pliersleft": "main", "Pliersright": "main"}), 12: dict(cad="rigid/Kettle", groups=[("main", [1], "Kettle", 12), ("mug", [3], "Mug", 2)], hands={2: "right"}, objmap={"kettle": "main"}), 13: dict(cad="rigid/Knife", groups=[("main", [1], "Knife", 13), ("apple", [3], "Apple", None)], hands={2: "right"}, objmap={"knife": "main"}), 14: dict(cad="articulated/TrashCan", groups=[("main", [1, 3], "Trash Can", 14), ("bottle", [4], "Bottle", 5)], hands={2: "right"}, objmap={"Dustbinbase": "main", "Dustbincover": "main"}), 17: dict(cad="articulated/Lamp", groups=[("main", [1, 3, 4, 5], "Lamp", 17)], hands={2: "right", 6: "left"}, objmap={"Lampbase": "main", "Tablelampfirstjoint": "main", "Tablelampsecondjoint": "main", "Thirdjointoftablelamp": "main"}), 18: dict(cad="articulated/Stapler", groups=[("main", [1, 3, 4], "Stapler", 18), ("paper", [5], "Paper", None)], hands={2: "right", 6: "left"}, # 6=左手:官方 label.csv 缺列,实测修正 objmap={"Staplerbase": "main", "Staplercover": "main"}), 20: dict(cad="rigid/Chair", groups=[("main", [1], "Chair", 20)], hands={2: "right", 3: "left"}, objmap={"chair": "main"}),}
# Official HOI4D definitions/motion segmentation/label.csv; no spatial side inference.REGION_NAMES = {1: {1: 'Toy Car', 2: 'Right Hand'}, 2: {1: 'Mug', 2: 'Right Hand', 3: 'Mug'}, 3: {1: 'Screen', 2: 'Right Hand', 3: 'Keyboard'}, 4: {1: 'Door', 2: 'Right Hand', 3: 'Body of the Cabinet', 4: 'Drawer', 5: 'Bottle'}, 5: {1: 'Bottle', 2: 'Right Hand', 3: 'Mug'}, 6: {1: 'Body of the Safe', 2: 'Right Hand', 3: 'Door', 4: 'Bottle'}, 7: {1: 'Bowl', 2: 'Right Hand', 3: 'Ball'}, 8: {1: 'Body of the Bucket', 2: 'Right Hand', 3: 'Handle', 4: 'Body of the Bucket', 5: 'Handle', 6: 'Left Hand'}, 9: {1: 'Left Part of the Scissors', 2: 'Right Hand', 3: 'Right Part of the Scissors'}, 11: {1: 'Left Part of the Pliers', 2: 'Right Hand', 3: 'Right Part of the Pliers'}, 12: {1: 'Kettle', 2: 'Right Hand', 3: 'Mug'}, 13: {1: 'Knife', 2: 'Right Hand', 3: 'Apple'}, 14: {1: 'Body of the Trash Can', 2: 'Right Hand', 3: 'Lid', 4: 'Bottle'}, 17: {1: 'Base', 2: 'Right Hand', 3: 'Tube', 4: 'Top Link', 5: 'Bottom Link', 6: 'Left Hand'}, 18: {1: 'Base', 2: 'Right Hand', 3: 'Slot', 4: 'Lid', 5: 'Paper'}, 20: {1: 'Chair', 2: 'Right Hand', 3: 'Left Hand'}}
class SplitFiles(io.RawIOBase): """Read concatenated source gzip parts without concatenating 119 GB on disk.""" def __init__(self, paths): self.paths = iter(paths) self.current = None
def readable(self): return True
def readinto(self, buffer): while True: if self.current is None: path = next(self.paths, None) if path is None: return 0 self.current = path.open('rb') n = self.current.readinto(buffer) if n: return n self.current.close() self.current = None
def close(self): if self.current is not None: self.current.close() super().close()
def extract_depths(root, sequences, work): directory = find_file(root, 'DEPTH') if directory is None: return {}, [] parts = sorted(directory.glob('HOI4D_depth_video.tar.gz*'), key=lambda p: int(p.name.split('.gz')[1] or 0)) if not parts: return {}, [] wanted = {f'HOI4D_depth_video/{seq}/align_depth/depth_video.avi': seq for seq in sequences} found = {} with SplitFiles(parts) as joined, io.BufferedReader(joined) as inp, gzip.GzipFile(fileobj=inp) as gz: with tarfile.open(fileobj=gz, mode='r|') as tf: for member in tf: if member.isfile() and member.name in wanted: seq = wanted[member.name] dest = work / (seq.replace('/', '_') + '.avi') with tf.extractfile(member) as src, dest.open('wb') as dst: shutil.copyfileobj(src, dst) found[seq] = (dest, {'files': [str(p.resolve()) for p in parts], 'member': member.name}) if len(found) == len(wanted): break return found, parts
def palette_mask(data): with Image.open(io.BytesIO(data)) as im: arr = np.asarray(im) if arr.ndim == 2: return arr.astype(np.uint16) if arr.shape[-1] != 3: raise ValueError('unsupported HOI4D mask representation') # VOC's 256-color palette interleaves eight label bits into the high RGB bits. # Invert it directly instead of sorting every pixel with np.unique. if np.any(arr & np.array([31, 31, 63], dtype=np.uint8)): raise ValueError('source mask has colors outside official VOC palette') mask = np.zeros(arr.shape[:2], dtype=np.uint16) for bit in range(8): mask |= ((arr[..., bit % 3] >> (7 - bit // 3)) & 1).astype(np.uint16) << bit return mask
# Four workers each reuse annotation and hand indices instead of rebuilding the ZIP directory.@lru_cache(maxsize=8)def index_frames(z): index = {} for name in z.namelist(): parent, _, filename = name.rpartition('/') stem, dot, suffix = filename.rpartition('.') if not dot or not stem.isdigit() or suffix not in ('png', 'json', 'pickle'): continue entries = index.setdefault((parent + '/', '.' + suffix), {}) f = int(stem) if f in entries: raise ValueError(f'duplicate frame number under {parent}') entries[f] = name return index
def frame_members(z, prefix, suffix): return index_frames(z).get((prefix, suffix), {})
def convert_sequence(seq, args, target, rgbz, annz, hpz, calz, cadz, paths, models, depth): # ponytail: cache only one sequence's encoded annotation bytes; no decoded masks or CAD cache. @lru_cache(maxsize=None) def read_annotation(archive, name): return archive.read(name)
category = int(re.search(r'/C(\d+)/', seq)[1]) definition = CATEGORIES.get(category) if definition is None: raise ValueError(f'category mapping unavailable: {category}') prefix = f'HOI4D_annotations/{seq}' mask_members = frame_members(annz, prefix + '/2Dseg/mask/', '.png') shifted = frame_members(annz, prefix + '/2Dseg/shift_mask/', '.png') if not mask_members: mask_members = shifted pose_members = frame_members(annz, prefix + '/objpose/', '.json') hand_members = {side: frame_members(hpz, f'Hand_pose/handpose_{side}_hand/{seq}/', '.pickle') for side in ('left', 'right')} if hpz else {'left': {}, 'right': {}} with tempfile.TemporaryDirectory(prefix='hoi4d-source-') as wd: work = Path(wd) member = f'HOI4D_release/{seq}/align_rgb/image.mp4' video = work / 'rgb.mp4' with rgbz.open(member) as src, video.open('wb') as dst: shutil.copyfileobj(src, dst) info = probe(video) if 'nb_frames' not in info: info['nb_frames'] = json.loads(run(['ffprobe', '-v', 'error', '-count_frames', '-select_streams', 'v:0', '-show_entries', 'stream=nb_read_frames', '-of', 'json', str(video)], stdout=subprocess.PIPE).stdout)['streams'][0]['nb_read_frames'] n = int(info['nb_frames']) if args.max_frames: n = min(n, args.max_frames) if shifted and mask_members != shifted and any(f not in mask_members and f in shifted for f in range(n)): raise ValueError('shift_mask has frames absent from mask; correspondence unverified') frames = [] for f in range(n): sources = {} if f in mask_members: sources['segment'] = locator(paths['annotations'], mask_members[f], read_annotation(annz, mask_members[f])) if f in pose_members: sources['object'] = locator(paths['annotations'], pose_members[f], read_annotation(annz, pose_members[f])) for side in ('left', 'right'): if f in hand_members[side]: sources['hand_' + side] = locator(paths['hand'], hand_members[side][f], read_annotation(hpz, hand_members[side][f])) frames.append(dict(source_frame_id=f, source_locator=locator(paths['release'], member, frame=f), component_sources=sources, annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, clock_domain=None, match_method='index_map', delta_ns=None) for k in sources})) view = View(target, 'HOI4D', args.release_id, seq.replace('/', '_'), 'ego', frames) view.valid_rules = { 'mano': 'Matched side pickle contains poseCoeff, beta, trans and corresponding model available; zero angles are not missing', 'keypoints': 'Matched side pickle contains kps2D; independently provided source points, no visibility gate', 'pose': 'Matched source object record contains rotation and center; record identity retained', 'dimensions': 'Matched source object record contains dimensions; size/mesh relation remains source_unspecified', 'segment': 'Source mask or shift_mask present with verified palette codes and entity/part mapping', } view.full_jpeg = getattr(args, 'jpeg_full_check', False) view.meta['view_type'] = 'ego' view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'source_sequence': seq} view.rgb([], locator(paths['release'], member), video=video, count=n) intr_name = f'camera_params/{seq.split("/")[0]}/intrin.npy' if calz and intr_name in calz.namelist(): view.camera(np.load(io.BytesIO(calz.read(intr_name))), locator(paths['camera'], intr_name)) extr_name = prefix + '/3Dseg/output.log' if extr_name in annz.NameToInfo: lines = [line for line in annz.read(extr_name).decode().splitlines() if line.strip()] if len(lines) % 5: raise ValueError('invalid Open3D camera trajectory') extr, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) for i in range(0, len(lines), 5): idx = int(lines[i].split()[0]) if idx < n: if valid[idx]: raise ValueError('duplicate trajectory index') extr[idx] = np.linalg.inv(np.loadtxt(io.StringIO('\n'.join(lines[i + 1:i + 5])))) valid[idx] = True view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', extr, valid, ['T', 'row', 'column'], locator(paths['annotations'], extr_name), convention='T_camera_from_world', source_convention='Open3D LOG camera-to-world; inverted') loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) points, pv = np.full((n, 2, 21, 2), np.nan, np.float32), np.zeros((n, 2, 21), bool) for slot, side in enumerate(('left', 'right')): for f, name in hand_members[side].items(): if f >= n: continue data = pickle.loads(read_annotation(hpz, name), encoding='latin1') if all(k in data for k in ('poseCoeff', 'beta', 'trans')): motion[f, slot] = np.r_[np.asarray(data['poseCoeff']).reshape(48), np.asarray(data['beta']).reshape(10), np.asarray(data['trans']).reshape(3)] mv[f, slot] = True # Zero angles are a valid pose, not a missing sentinel. if 'kps2D' in data: points[f, slot] = np.asarray(data['kps2D']).reshape(21, 2) pv[f, slot] = True if mv.any(): if all(side in models for slot, side in enumerate(('left', 'right')) if mv[:, slot].any()): view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) else: view.absent('mano', 'Source MANO exists; provide --mano-dir to fix model identity', 'dependency_missing') if pv.any(): view.tensor('keypoints_uv', 'keypoints/uv/v1', 'annotation/keypoints/uv.pt', points, pv, ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='pixel', source_method='Upstream fitted MANO projection already present in kps2D') objects = {} groups = {key: (vals, name, cls) for key, vals, name, cls in definition['groups']} def ensure_object(key, source_loc, category_id=None, frame=None, source_id=None): if key not in objects: view.object(key, source_loc, scope='frame' if frame is not None else 'sequence', scope_id=f'{seq}:{frame}' if frame is not None else None, category_id=category_id, source_object_id=source_id) objects[key] = {} mappings = [] mask_valid = [f in mask_members for f in range(n)] if any(mask_valid): width, height = view.meta['camera']['image_size'] def masks(): for f in range(n): labels = [] if f in mask_members: mask = palette_mask(read_annotation(annz, mask_members[f])) for value in np.unique(mask): value = int(value) if value in (0, 255): if value == 255: raise ValueError('HOI4D 255 region semantics unverified') continue if REGION_NAMES[category].get(value) in ('Left Hand', 'Right Hand'): entity, part, cls = 'hand_' + REGION_NAMES[category][value].split()[0].lower(), None, 'hand' else: group = next((k for k, (vals, _, _) in groups.items() if value in vals), None) entity = group or f'unknown_region_{value}' cls = groups[group][2] if group else None part = f'region_{value}' if group and len(groups[group][0]) > 1 else None ensure_object(entity, frames[f]['component_sources']['segment'], cls) if part: objects[entity].setdefault('parts', {})[part] = {'part_id': part, 'parent_id': None, 'has_model': False, 'mesh_ref': None, 'source_region_code': value, 'name': REGION_NAMES[category].get(value)} labels.append(dict(mask_value=value, category_id=cls, entity_id=entity, part_id=part, source_instance_id=value, source_attributes={'region_name': REGION_NAMES[category].get(value)})) else: mask = np.zeros((height, width), np.uint16) mappings.append(dict(frame_index=f, labels=labels)) yield mask view.raster('segment', masks(), mask_valid, loc, mappings) view.meta['components']['segment']['coverage'] = {'kind': 'unknown'} if any(label['part_id'] for row in mappings for label in row['labels']): view.meta['components']['segment']['segmentation_type'] = 'part' else: view.absent('segment', 'No native segmentation for this source sequence') records = {} for f, name in pose_members.items(): if f >= n: continue data = json.loads(read_annotation(annz, name)) # isEffective is not used to erase existing numerical annotations. source_records = data.get('dataList', data.get('objects')) if source_records is None: raise ValueError('unrecognized source object annotation structure') if category == 2 and source_records and (len(source_records) != 1 or source_records[0].get('id') != 1 or source_records[0].get('label') != 'Watercup'): raise ValueError('C2 native pose differs from the verified one-object target; cannot map to mask region 1') label_counts = Counter(record['label'] for record in source_records) per_frame = set() for record_index, record in enumerate(source_records): label = record['label'] group = definition['objmap'].get(label) # Pinned official ObjTracking reads dataList[0] with segmentation label 1. source_primary = category == 2 and record_index == 0 and record.get('id') == 1 and group == 'a' ambiguous = group is not None and sum(g[2] == groups[group][2] for g in groups.values()) > 1 and not source_primary ambiguous = ambiguous or (label_counts[label] > 1 and not source_primary) or group is None entity = f'pose_frame_{f}_{record_index}' if ambiguous else group ensure_object(entity, locator(paths['annotations'], name, record=record_index), groups[group][2] if group else None, frame=f if ambiguous else None, source_id=record.get('id')) if ambiguous: view.build['unresolved'].append({'component': entity, 'status': 'source_semantics_unverified', 'reason': 'Source pose retained with frame identity; no guessed association to same-class mask instances'}) label_key = (entity, label) if label_key in per_frame: raise ValueError(f'ambiguous repeated object label {label}; source identity must be resolved') per_frame.add(label_key) records.setdefault(label_key, {})[f] = (record, locator(paths['annotations'], name, record=record.get('id'))) if category == 2 and any(entity == 'a' for entity, _ in records): view.build['validation'].append({'component': 'C2_source_pose_mask_identity', 'rule': 'Official ObjTracking process_data.py reads dataList[0] with semantic mask label 1', 'source_revision': 'afa7bf37b02b7e33cf245acd08b98c207ccc175c', 'source_pose_id': 1, 'mask_value': 1, 'matched_frames': sum(len(by_frame) for (entity, _), by_frame in records.items() if entity == 'a')}) for (entity, label), by_frame in records.items(): part_labels = [k[1] for k in records if k[0] == entity] articulated = definition['cad'].startswith('articulated/') and entity == definition['groups'][0][0] part = 'pose_' + re.sub(r'[^a-zA-Z0-9_]', '_', label) if articulated or len(part_labels) > 1 else None base = f'annotation/object/{entity}' if part: base += '/parts/' + part objects[entity].setdefault('parts', {})[part] = dict(part_id=part, parent_id=None, has_model=False, mesh_ref=None, source_label=label) poses, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) dimensions = np.full((n, 3), np.nan, np.float32) dv = np.zeros(n, bool) for f, (record, _) in by_frame.items(): if all(k in record for k in ('rotation', 'center')): poses[f] = np.eye(4) poses[f, :3, :3] = Rotation.from_euler('XYZ', [record['rotation'][k] for k in ('x', 'y', 'z')]).as_matrix() poses[f, :3, 3] = [record['center'][k] for k in ('x', 'y', 'z')] valid[f] = True if 'dimensions' in record: dimensions[f] = [record['dimensions'][k] for k in ('length', 'width', 'height')] dv[f] = True key = entity + ('_' + part if part else '') view.tensor('pose_' + key, 'transform/se3/v1' if part else 'object/rigid/v1', base + '/pose.pt', poses, valid, ['T', 'row', 'column'], loc, convention='T_camera_from_part' if part else 'T_camera_from_object', unit='m', source_label=label, source_euler_order='XYZ', definition='https://github.com/hoi4d/ObjTracking/blob/main/process_data.py') if dv.any(): view.tensor('dimensions_' + key, 'object/dimensions/v1', base + '/dimensions.pt', dimensions, dv, ['T', 'dimension'], loc, dimensions_semantics='source_unspecified', unit='m', scale_applied_to_mesh=False) if cadz: primary = definition['groups'][0][0] if category != 2 and sum(g[2] == category for g in groups.values()) > 1: primary = 'source_cad_instance' instance = int(re.search(r'/N(\d+)/', seq)[1]) mesh_prefix = f'HOI4D_CAD_Model_for_release/{definition["cad"]}/{instance:03d}' candidates = [name for name in cadz.namelist() if not name.endswith('/') and (name == mesh_prefix + '.obj' or name.startswith(mesh_prefix + '/'))] if candidates: # Retain OBJ material/texture dependencies beside their original names. queue = list(candidates) for name in queue: if Path(name).suffix.lower() not in ('.obj', '.mtl'): continue for line in cadz.read(name).decode().splitlines(): fields = shlex.split(line, comments=True) if not fields: continue refs = fields[1:] if fields[0] == 'mtllib' else ([fields[-1]] if fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal') else []) for ref in refs: dependency = posixpath.normpath(posixpath.join(posixpath.dirname(name), ref)) if dependency not in cadz.NameToInfo: raise ValueError(f'missing CAD dependency: {dependency}') if dependency not in candidates: candidates.append(dependency) queue.append(dependency) ensure_object(primary, locator(paths['cad'], mesh_prefix), category) asset_dir = view.path / f'annotation/object/{primary}/assets' asset_refs = [] for name in candidates: relative = posixpath.relpath(name, mesh_prefix if definition['cad'].startswith('articulated/') else posixpath.dirname(mesh_prefix)) dest = safe_member(asset_dir, relative) dest.parent.mkdir(parents=True, exist_ok=True) dest.write_bytes(cadz.read(name)) ref = dest.relative_to(view.path).as_posix() if dest.suffix.lower() == '.obj': asset_key = re.sub(r'[^a-zA-Z0-9_]', '_', relative) view.component('mesh_' + primary + '_' + asset_key, 'mesh/obj/v1', ref, ['vertex'], locator(paths['cad'], name), unit='m', valid=True, scale_applied_to_mesh=False, dimensions_semantics='source_unspecified') asset_refs.append(ref) if definition['cad'].startswith('articulated/'): part_id = 'asset_' + asset_key objects[primary].setdefault('parts', {})[part_id] = dict(part_id=part_id, parent_id=None, has_model=True, mesh_ref=ref, source_asset=relative, note='Source asset; correspondence to motion part labels remains unverified') for asset_ref in asset_refs: mesh_check = check_mesh(view.path / asset_ref, asset_dir) view.build['validation'].append({'component': asset_ref, **mesh_check, 'unit_basis': 'official ObjTracking loads source canonical CAD without scaling in metre camera coordinates', 'geometric_acceptance': 'physical dimensions-to-mesh relation remains source_unspecified'}) metadata_path = view.path / f'annotation/object/{primary}/metainfo.json' metadata = json.loads(metadata_path.read_text()) metadata.update(has_model=bool(asset_refs), asset_refs=asset_refs) if definition['cad'].startswith('rigid/') and len(asset_refs) == 1: metadata['mesh_ref'] = asset_refs[0] json_write(metadata_path, metadata) if definition['cad'].startswith('articulated/'): view.build['unresolved'].append({'component': 'object_part_asset_association', 'status': 'source_semantics_unverified', 'reason': 'All source assets and motion labels retained, but no guessed correspondence or joint_state'}) for entity, info in objects.items(): if 'parts' in info: ref = f'annotation/object/{entity}/articulation.json' json_write(view.path / ref, {'parts': list(info['parts'].values()), 'joints': [], 'hierarchy_semantics': 'semantic_containment', 'note': 'Unassociated source region, motion and asset nodes; original CAD trees retained in assets'}) view.component('articulation_' + entity, 'object/articulated/v1', ref, [], loc) meta_path = view.path / f'annotation/object/{entity}/metainfo.json' metadata = json.loads(meta_path.read_text()) metadata['articulation_ref'] = ref json_write(meta_path, metadata) if depth is not None: dpath, dloc = depth dmeta = probe(dpath) if [dmeta['width'], dmeta['height']] != view.meta['camera']['image_size']: raise ValueError('HOI4D depth grid differs from RGB') if dmeta['pix_fmt'] != 'gray16le': raise ValueError('unexpected HOI4D depth pixel format') width, height = view.meta['camera']['image_size'] raw = work / 'depth.raw' limits = ['-frames:v', str(n)] if args.max_frames else [] run(decode_args(dpath, 'gray16le') + limits + ['-y', str(raw)]) if raw.stat().st_size != n * width * height * 2: raise ValueError('depth/RGB frame count or grid mismatch') def depths(): with raw.open('rb') as inp: for _ in range(n): yield np.frombuffer(inp.read(width * height * 2), '<u2').reshape(height, width).astype(np.float32) / 1000 view.raster('depth', depths(), None, dloc | {'conversion': 'registered millimetre camera-Z to metres'}) else: if find_file(args.root, 'DEPTH'): raise ValueError('DEPTH source exists, but no matching depth video was found') view.absent('depth', 'Depth source not downloaded', 'not_downloaded') return view.finish()
def main(argv=None): p = parser('HOI4D', __doc__) p.set_defaults(release_id='shared-v1.0') # Four workers reached 21 observed OS threads including timing; stay below the 24-thread budget. p.add_argument('--workers', type=int, choices=range(1, 5), default=1, help='Independent views in parallel, 1..4; codec/BLAS threads fixed at 1') p.add_argument('--tasks', help='Comma-separated substrings of source sequence paths') p.add_argument('--sessions', help='Comma-separated sessions') p.add_argument('--categories', help='Comma-separated category numbers') args = p.parse_args(argv) if args.views and args.views != 'ego': p.error('HOI4D source camera ID is ego') paths = {key: find_file(args.root, name) for key, name in { 'release': 'HOI4D_release.zip', 'annotations': 'HOI4D_annotations.zip', 'hand': 'HOI4D_Hand_pose.zip', 'camera': 'camera_params.zip', 'cad': 'HOI4D_CAD_Model_for_release.zip'}.items()} if not paths['release'] or not paths['annotations']: p.error('HOI4D release and annotation ZIPs are required') out = release(args, 'HOI4D') mapping = Path(__file__).resolve().parent.parent / 'docs/hoi4d-RAW_TO_SHARED.md' published_mapping = out / 'doc/RAW_TO_SHARED.md' if published_mapping.exists() and published_mapping.read_bytes() != mapping.read_bytes(): raise ValueError('RAW_TO_SHARED.md changed; choose a new release-id') if not published_mapping.exists(): shutil.copyfile(mapping, published_mapping) torch.set_num_threads(1) models = mano_models(args.mano_dir) with ExitStack() as stack, tempfile.TemporaryDirectory(prefix='hoi4d-depth-') as wd: archives = {key: stack.enter_context(zipfile.ZipFile(path)) if path else None for key, path in paths.items()} sequences = sorted(name.removeprefix('HOI4D_release/').removesuffix('/align_rgb/image.mp4') for name in archives['release'].namelist() if name.endswith('/align_rgb/image.mp4')) if args.tasks: sequences = [s for s in sequences if any(token in s for token in args.tasks.split(','))] if args.sessions: sequences = [s for s in sequences if s.split('/')[0] in args.sessions.split(',')] if args.categories: sequences = [s for s in sequences if re.search(r'/C(\d+)/', s)[1] in args.categories.split(',')] if args.limit: sequences = sequences[:args.limit] if not sequences: p.error('no matching source sequences') depths, _ = extract_depths(args.root, sequences, Path(wd)) worker = threading.local() worker_stacks = [] def init_worker(): owned = ExitStack() try: # ZipFile.read mutates a shared seek position: never share a handle across workers. worker.archives = {key: owned.enter_context(zipfile.ZipFile(path)) if path else None for key, path in paths.items()} index_frames(worker.archives['annotations']) if worker.archives['hand']: index_frames(worker.archives['hand']) except BaseException: owned.close() raise worker_stacks.append(owned) def convert_one(seq): source = archives if args.workers == 1 else worker.archives name = seq.replace('/', '_') with sequence_dir(out, name) as target: report = convert_sequence(seq, args, target / 'ego', source['release'], source['annotations'], source['hand'], source['camera'], source['cad'], paths, models, depths.get(seq)) build_record(out, name, {'ego': report}) return seq if args.workers == 1: for seq in map(convert_one, sequences): print(f'Converted {seq}', flush=True) else: try: with ThreadPoolExecutor(max_workers=args.workers, initializer=init_worker) as pool: for seq in pool.map(convert_one, sequences): print(f'Converted {seq}', flush=True) finally: for owned in worker_stacks: owned.close() return 0
if __name__ == '__main__': raise SystemExit(main())
# TODO(v2.0): 旧 bbox IoU 实例重分配属于推断,注释保留,不在 v1.0 执行。# # 同类多实例(C8 双桶 / C2 双杯):2dBox 可用时按 IoU 复核归属# cls = next(x[3] for x in cat["groups"] if x[0] == gk)# sibs = [g for g in cat["groups"]# if g[0] != gk and cls is not None and g[3] == cls]# box = (d.get("2dBox") or {}).get("camera1")# box = (box[0][0], box[0][1], box[1][0], box[1][1]) \# if box and len(box) == 2 else None# if box is not None and sibs:# gvals = next(x[1] for x in cat["groups"] if x[0] == gk)# best, best_iou = gk, box_iou(box, bbox_of(mask, gvals))# for s in sibs:# if ("obj", s[0]) not in tid_of_group:# continue# i = box_iou(box, bbox_of(mask, s[1]))# if i > best_iou + 0.1 and i > 0.15:# best, best_iou = s[0], i# if best != gk:# gk, iou_fixups = best, iou_fixups + 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271#!/usr/bin/env python3"""VISOR source polygons and contact → CONTRACT.md v1.0, without rasterization or side inference."""from collections import Counterimport hashlibimport jsonimport reimport shutilimport tempfilefrom pathlib import Pathimport zipfile
import numpy as npimport torch
from warehouse_v1_0 import (View, build_record, find_file, jsonl_write, locator, parser, release, roots, sequence_dir, source)
FRAME = re.compile(r'frame_(\d+)')HAND = {300: 'left', 301: 'right'}GLOVE = {303: 'left', 304: 'right'}STATES = {'hand-not-in-contact': 'negative', 'glove-not-in-contact': 'negative', 'none-of-the-above': 'target_unannotated', 'inconclusive': 'unknown'}
def hand_side(ann): if ann['class_id'] in HAND: return HAND[ann['class_id']] if ann['class_id'] not in (60, 303, 304): return None raw = ann.get('on_which_hand') raw = raw if isinstance(raw, list) else [raw] sides = set() for item in raw: if item == 'left hand': sides.add('left') if item in ('right hand', 'rigth hand'): sides.add('right') if len(sides) == 1: return next(iter(sides)) if not sides and ann['class_id'] in GLOVE: return GLOVE[ann['class_id']] return None
def convert_video(video, split, annotation, ann_loc, rgb_zip, rgb_loc, mapping, args, target): indexed = sorted(enumerate(annotation['video_annotations']), key=lambda row: int(FRAME.search(row[1]['image']['name'])[1])) if args.max_frames: indexed = indexed[:args.max_frames] if len({row['image']['name'] for _, row in indexed}) != len(indexed): raise ValueError('duplicate VISOR frame') keys = lambda row, ann: (row['image']['subsequence'], ann['class_id'], ann['name']) collisions = set() for _, row in indexed: collisions.update(key for key, number in Counter(keys(row, a) for a in row['annotations']).items() if number > 1) frames, paths = [], [] with tempfile.TemporaryDirectory(prefix='visor-rgb-') as wd, zipfile.ZipFile(rgb_zip) as z: work = Path(wd) for original_index, row in indexed: name = row['image']['name'] data = z.read(name) path = work / Path(name).name path.write_bytes(data) paths.append(path) loc = rgb_loc | {'nested_member': name, 'sha256': hashlib.sha256(data).hexdigest()} frames.append(dict(source_frame_id=int(FRAME.search(name)[1]), source_locator=loc, source_image=row['image'], original_frame_name=mapping.get(name), annotation_matches={'segment': dict(source_frame_id=name, source_timestamp_ns=None, clock_domain=None, match_method='index_map', delta_ns=None, source_locator=ann_loc | {'record': f'video_annotations[{original_index}]'})})) view = View(target, 'EPIC-KITCHENS-VISOR', args.release_id, video, 'ego', frames, sampling='sparse', split=split) view.valid_rules = { 'segment': 'Selected sparse annotation frame present; all source polygons finite with at least three vertices and entity mapping valid', 'relations': 'At least one source in_contact_object value present; positive targets resolve in the same frame; unknown is an explicit usable status', } view.full_jpeg = getattr(args, 'jpeg_full_check', False) view.meta.update(view_type='ego', split_scheme='VISOR_GroundTruth_SparseAnnotations', split_source_locator=ann_loc) view.meta['sampling']['selection'] = {'representation': 'official sparse annotations', 'max_frames': args.max_frames} view.rgb(paths, rgb_loc) entities = {} polygons, mappings, relations, relation_valid = [], [], [], [] for f, (original_index, row) in enumerate(indexed): frame_loc = ann_loc | {'record': f'video_annotations[{original_index}]'} id_map, labels, polys = {}, [], [] for code, ann in enumerate(row['annotations'], 1): if code >= 65535: raise ValueError('too many source instances') sid = ann['id'] if sid in id_map: raise ValueError('duplicate source instance ID within a frame') side = hand_side(ann) if side is not None: entity = 'hand_' + side else: key = keys(row, ann) identity = key + (sid, row['image']['name']) if key in collisions else key entity = 'object_' + hashlib.sha256(json.dumps(identity).encode()).hexdigest()[:20] if entity not in entities: scope = 'frame' if key in collisions else 'subsequence' scope_id = f'{video}:{row["image"]["name"]}' if scope == 'frame' else f'{video}:{key[0]}' view.object(entity, frame_loc | {'source_instance_id': sid}, scope, scope_id, category_id=ann['class_id'], name=ann['name'], association_basis='source_frame_instance' if scope == 'frame' else 'official_subsequence_entity_name') entities[entity] = True id_map[sid] = entity for polygon in ann.get('segments', []): p = np.asarray(polygon) if p.ndim != 2 or p.shape[1] != 2 or len(p) < 3 or not np.isfinite(p).all(): raise ValueError(f'invalid source polygon {sid}') polys.append(dict(mask_value=code, polygons=ann.get('segments', []))) labels.append(dict(mask_value=code, category_id=ann['class_id'], entity_id=entity, part_id=None, source_instance_id=sid, source_attributes={k: v for k, v in ann.items() if k != 'segments'})) rr = [] provided = False for ann in row['annotations']: raw = ann.get('in_contact_object') values = raw if isinstance(raw, list) else [raw] for value in values: if value is None: continue provided = True status = STATES.get(value) obj = None if status is None: if value not in id_map: raise ValueError(f'unresolved source contact target {value} in {video} frame {f}') status, obj = 'positive', id_map[value] rr.append(dict(relation_type='contact', subject_id=id_map[ann['id']], object_id=obj, status=status, source_value=value, source_locator=frame_loc | {'source_instance_id': ann['id']}, provenance=source('Resolve source contact ID against instances in this frame'))) polygons.append(dict(frame_index=f, instances=polys)) mappings.append(dict(frame_index=f, labels=labels)) relations.append(dict(frame_index=f, relations=rr)) relation_valid.append(provided) jsonl_write(view.path / 'annotation/segment/polygons.jsonl', polygons) jsonl_write(view.path / 'annotation/segment/instances.jsonl', mappings) torch.save(torch.ones(len(frames), dtype=torch.bool, device='cpu'), view.path / 'annotation/segment/mask_valid.pt') view.component('segment', 'segment/instance_polygons/v1', 'annotation/segment/polygons.jsonl', ['T'], ann_loc, valid_ref='annotation/segment/mask_valid.pt', valid_axes=['T'], segmentation_type='instance', mapping_ref='annotation/segment/instances.jsonl', coverage={'kind': 'unknown', 'exhaustive_ref': 'annotation/segment/instances.jsonl'}) view.relations(relations, relation_valid, ann_loc) for component in ('depth', 'mano', 'keypoints_uv', 'keypoints_xyz', 'intrinsic', 'extrinsic'): view.absent(component, 'Not provided by VISOR sparse source annotations') return view.finish()
def main(argv=None): p = parser('EPIC-KITCHENS-VISOR', __doc__) p.add_argument('--videos', help='Comma-separated video names') p.add_argument('--splits', default='train,val') args = p.parse_args(argv) wanted = set(args.videos.split(',')) if args.videos else None splits = set(args.splits.split(',')) if not splits <= {'train', 'val'}: p.error('only annotated train/val splits are available') out = release(args, 'EPIC-KITCHENS-VISOR') archive = find_file(args.root, 'EPIC-KITCHENS VISOR.zip') with tempfile.TemporaryDirectory(prefix='visor-source-') as wd: work = Path(wd) if archive: with zipfile.ZipFile(archive) as z: suffix = 'GroundTruth-SparseAnnotations/annotations/' members = [n for n in z.namelist() if suffix in n and n.endswith('.json')] prefix = members[0].split(suffix)[0] fm = json.loads(z.read(prefix + 'frame_mapping.json')) done = 0 for member in sorted(members): split, filename = member.split(suffix)[1].split('/') video = Path(filename).stem if split not in splits or wanted and video not in wanted: continue data = z.read(member) rgb_member = prefix + f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' rgb_zip = work / (video + '.zip') with z.open(rgb_member) as inp, rgb_zip.open('wb') as dest: shutil.copyfileobj(inp, dest) with sequence_dir(out, video) as dest: report = convert_video(video, split, json.loads(data), locator(archive, member, data), rgb_zip, locator(archive, rgb_member), fm.get(video, {}), args, dest / 'ego') build_record(out, video, {'ego': report}) rgb_zip.unlink() done += 1 print(f'Converted {video}', flush=True) if args.limit and done >= args.limit: break else: root = next((r for r in roots(args.root) if (r / 'GroundTruth-SparseAnnotations').is_dir()), None) if root is None: p.error('VISOR outer ZIP or extracted source directory not found') fm = json.loads((root / 'frame_mapping.json').read_text()) if (root / 'frame_mapping.json').exists() else {} done = 0 for split in sorted(splits): for ann in sorted((root / 'GroundTruth-SparseAnnotations/annotations' / split).glob('*.json')): video = ann.stem if wanted and video not in wanted: continue rgb = root / f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' with sequence_dir(out, video) as dest: report = convert_video(video, split, json.loads(ann.read_text()), locator(ann), rgb, locator(rgb), fm.get(video, {}), args, dest / 'ego') build_record(out, video, {'ego': report}) done += 1 if args.limit and done >= args.limit: return 0 if not done: p.error('no matching annotated videos found') return 0
if __name__ == '__main__': raise SystemExit(main())
# TODO(v2.0): 旧距离猜侧和单层掩码生成仅注释保留;v1.0 不执行。# if side is None and len(frame_hands) == 1:# # 空间门槛:脱下放在远处的手套不并入(实测双峰 0..25px / ≥44px)# hb = frame_hands[0][1]# gb = _bbox_of(polys)# if hb and gb and _bbox_dist(gb, hb) <= GLOVE60_MERGE_BBOX_DIST:# side = frame_hands[0][0]# stats["glove60_merged_into_sole_hand"] += 1# if side is None:# stats["dropped_glove60_unresolved"] += 1# id_disp[mid] = ("dropped", "glove60")# continue# def rasterize_and_encode(vdir, frames, frame_draw, zip_path, n, stats):# """流式读 zip 内 jpg + 光栅化多边形 → rgb.mkv / mask.mkv;返回 (w, h)。"""# from PIL import Image, ImageDraw## with zipfile.ZipFile(zip_path) as zf:# member_of = {}# for nm in zf.namelist():# member_of[os.path.basename(nm)] = nm# names = [im["name"] for im in frames]# missing = [nm for nm in names if nm not in member_of]# if missing:# raise RuntimeError(f"{len(missing)} annotated frames missing in zip, "# f"e.g. {missing[:3]}")# stats["zip_extra_members"] = len(member_of) - len(names)## # 首帧定分辨率(官方 1920×1080,实测每帧校验)# img0 = Image.open(io.BytesIO(zf.read(member_of[names[0]]))).convert("RGB")# w, h = img0.size## bin_img = Image.new("L", (w, h), 0)# bin_draw = ImageDraw.Draw(bin_img)# canvas = np.zeros((h, w), np.uint16)# with VideoPipe(vdir / "mask.mkv", w, h, FPS, "mask") as mw, \# VideoPipe(vdir / "rgb.mkv", w, h, FPS, "rgb") as rw:# for f in range(n):# canvas[:] = 0# for pid, polys in frame_draw[f]:# bin_draw.rectangle((0, 0, w, h), fill=0)# for poly in polys:# bin_draw.polygon([(float(x), float(y)) for x, y in poly], fill=255)# arr = np.asarray(bin_img)# canvas[arr > 0] = pid # 后画覆盖先画:物体→手(modal)# mw.write(canvas)# img = img0 if f == 0 else Image.open(# io.BytesIO(zf.read(member_of[names[f]]))).convert("RGB")# if img.size != (w, h):# raise RuntimeError(f"frame {names[f]}: size {img.size} != {(w, h)}")# rw.write(np.asarray(img))# n_mask, n_rgb = mw.n, rw.n# if (n_rgb, n_mask) != (n, n):# raise RuntimeError(f"wrote rgb={n_rgb} mask={n_mask} != {n}")# got = (count_frames(vdir / "rgb.mkv"), count_frames(vdir / "mask.mkv"))# if got != (n, n):# raise RuntimeError(f"encoded rgb={got[0]} mask={got[1]} != {n} (decode verify)")# return w, h##123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137"""Full coverage/numeric audit, plus representative persisted-media QC and offline HTML."""import osfor key in ('OMP_NUM_THREADS','OPENBLAS_NUM_THREADS','MKL_NUM_THREADS','NUMEXPR_NUM_THREADS'): os.environ[key]='1'os.environ['HAND_WAREHOUSE_FFMPEG_THREADS']='4'os.environ.pop('HAND_WAREHOUSE_FFV1_SLICES',None)os.environ.pop('HAND_WAREHOUSE_MEDIA_TMPDIR',None)import collections,datetime,hashlib,html,json,re,sys,time,zipfilefrom concurrent.futures import ThreadPoolExecutor,as_completedfrom pathlib import Pathfrom zoneinfo import ZoneInfoimport numpy as npimport torchroot=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe')release=root/'H2O/shared-v1.0'sys.path.insert(0,str(root/'frozen-code/scripts'))from warehouse_v1_0 import SCHEMA,check_transform,check_valid_policy,check_view_type,safe_member,sha256from render_h2o_validation import renderout=release/'doc/validation/final-quick-check'out.mkdir(exist_ok=True)torch.set_num_threads(1)started=time.monotonic()expected={}with zipfile.ZipFile('/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/label_split.zip') as z: for name in z.namelist(): if '/action_' not in name:continue for line in z.read(name).decode().splitlines(): fields=line.split() if len(fields)>1 and fields[1]!='path': seq=fields[1].replace('/','_') expected[seq]=max(expected.get(seq,0),int(fields[-1])+1)folders={p.name:p for p in (release/'data').iterdir() if p.is_dir()}assert set(folders)==set(expected),(sorted(set(expected)-set(folders)),sorted(set(folders)-set(expected)))assert len(expected)==184 and sum(expected.values())==114329receipts={p.name.removesuffix('.build.json'):p for p in (release/'doc').glob('*.build.json')}assert set(receipts)==set(expected)assert 'EXIT=0' in (root/'full.status').read_text()failures=[]rows=[]def require(ok,message): if not ok:raise ValueError(message)def load(path): def cpu(storage,location): require(location=='cpu',f'non-CPU storage: {path}') return storage obj=torch.load(path,map_location=cpu,weights_only=True) require(type(obj) is torch.Tensor,f'non-tensor: {path}') return obj.numpy()def check_sequence(seq): folder=folders[seq];n=expected[seq] require({p.name for p in folder.iterdir() if p.is_dir()}=={f'cam{i}' for i in range(5)},'five-camera coverage') receipt=json.loads(receipts[seq].read_text()) require(receipt['sequence_id']==seq and set(receipt['views'])=={f'cam{i}' for i in range(5)},'build receipt') result=[] for i in range(5): cam=f'cam{i}';view=folder/cam meta=json.loads((view/'metainfo.json').read_text()) require((meta['dataset_id'],meta['sequence_id'],meta['camera_id'],meta['num_frames'])==('H2O',seq,cam,n),'header/timeline') require(meta['view_type']==('ego' if i==4 else 'exo'),'view role') require(meta['sampling']['selection']=={'max_frames':None,'views':None},'unexpected subsampling') check_view_type(meta) components=meta['components'] require(all(components[k].get('available') for k in ('rgb','depth','mano','keypoints_xyz','intrinsic','extrinsic')),'required modality absent') require(not components['segment']['available'] and not components['relations']['available'],'unexpected synthesized component') rgb_sources=[];depth_sources=[];rgb_count=depth_count=0 with (view/'camera/frames.jsonl').open() as inp: count=0 for index,line in enumerate(inp): f=json.loads(line) require(f['frame_index']==index and f['source_frame_id']==index,'source frame index') require(f['sync_id']==f'{seq.replace("_","/")}:{index}','synchronization ID') sources=f['component_sources'] for kind,loc in sources.items(): require(re.fullmatch('[0-9a-f]{64}',loc.get('sha256','')) is not None,f'source SHA256: {kind}') require(f'/{cam}/' in loc.get('member',''),'wrong source camera') rgb_sources.append('rgb' in sources);depth_sources.append('depth' in sources) rgb_count+=rgb_sources[-1];depth_count+=depth_sources[-1];count+=1 require(count==n,'frames.jsonl length') numeric=0 object_names=[] for key,c in components.items(): if not c['available']:continue for field in ('data_ref','valid_ref','mapping_ref'): if c.get(field): path=safe_member(view,c[field]) require(path.is_file() and path.stat().st_size>0,f'missing/empty {c[field]}') schema=SCHEMA['components'][c['schema_id']] if c.get('valid_policy'):check_valid_policy(c,n) valid=load(view/c['valid_ref']) if c.get('valid_ref','').endswith('.pt') else None if valid is not None: shape=schema.get('valid_shape') require(valid.dtype==np.bool_ and valid.shape[0]==n,f'{key}: validity dtype/timeline') if shape:require(len(shape)==valid.ndim and all(not isinstance(s,int) or valid.shape[j]==s for j,s in enumerate(shape)),f'{key}: validity shape') if key=='rgb':require(np.array_equal(valid,np.asarray(rgb_sources)), 'RGB existence validity mismatch') if c['data_ref'].endswith('.pt'): arr=load(view/c['data_ref']);numeric+=1 require(arr.dtype==np.float32 and arr.shape[0]==n,f'{key}: dtype/timeline') shape=schema.get('shape') if shape:require(len(shape)==arr.ndim and all(not isinstance(s,int) or arr.shape[j]==s for j,s in enumerate(shape)),f'{key}: tensor shape') if valid is not None: require(arr.shape[:valid.ndim]==valid.shape and np.isfinite(arr[valid]).all() and np.isnan(arr[~valid]).all(),f'{key}: finite/NaN validity semantics') if c['schema_id'] in ('transform/se3/v1','object/rigid/v1'):check_transform(arr[valid]) if key=='intrinsic':require(np.allclose(arr[:,2],[0,0,1]) and (arr[:,0,0]>0).all() and (arr[:,1,1]>0).all(),'camera intrinsics') if key.startswith('mesh_'):object_names.append(key.removeprefix('mesh_')) proof=receipt['views'][cam] require(not proof['unresolved'],'unresolved QC components') media={} for p in proof['validation']: if p.get('profile')==components['rgb']['storage']['profile'] and p.get('all_frames_exact') is True:media['rgb']=p elif p.get('component') in ('depth','depth_valid'):media[p['component']]=p require(set(media)=={'rgb','depth','depth_valid'},'media roundtrip proof missing') for key,p in media.items(): require(p.get('all_frames_exact') is True and re.fullmatch('[0-9a-f]{64}',p.get('decoded_sha256','')) is not None,f'{key}: failed original roundtrip proof') require((view/'observation'/f'{key}.mkv').stat().st_size==p['bytes'],f'{key}: encoded file size changed since conversion') result.append({'sequence_id':seq,'camera':cam,'frames':n,'numeric_components':numeric, 'rgb_source_frames':rgb_count,'depth_source_frames':depth_count,'objects':sorted(object_names)}) return result
result=check_sequence('subject1_k2_6')from warehouse_v1_0 import decoded_digestreceipt=json.loads(receipts['subject1_k2_6'].read_text())view=folders['subject1_k2_6']/'cam0'meta=json.loads((view/'metainfo.json').read_text())proofs=receipt['views']['cam0']['validation']verified=[]for name,pix in (('rgb','rgb24'),('depth','gray16le'),('depth_valid','gray')): p=next(x for x in proofs if (x.get('profile')==meta['components']['rgb']['storage']['profile'] if name=='rgb' else x.get('component')==name)) digest,size,seconds=decoded_digest(view/'observation'/f'{name}.mkv',pix) assert digest==p['decoded_sha256'],(name,digest,p['decoded_sha256']) expected_bytes=expected['subject1_k2_6']*1280*720*({'rgb':3,'depth':4,'depth_valid':1}[name]) assert size==expected_bytes,(name,size,expected_bytes) verified.append({'component':name,'decoded_sha256':digest,'decoded_bytes':size,'seconds':seconds})page=render(view,out/'subject1_k2_6_cam0_fallback')json_result={'passed':True,'views':result,'full_decode_comparison':verified,'html':str(page.relative_to(out)), 'note':'Registered lossless H.264 fallback; all current decoded media digests equal original conversion receipts'}(out/'H264_FALLBACK_CHECK.json').write_text(json.dumps(json_result,indent=2)+'\n')print('FALLBACK_PASS',json.dumps(json_result),flush=True)123456789101112131415161718192021222324252627282930313233343536373839import datetime,html,json,shutilfrom pathlib import Pathfrom zoneinfo import ZoneInforelease=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe/H2O/shared-v1.0')out=release/'doc/validation/final-quick-check'report=json.loads((out/'QUICK_VALIDATION.json').read_text())assert report['failures']==[{'sequence':'subject1_k2_6','error':"ValueError('rgb: failed original roundtrip proof')"}]fallback=json.loads((out/'H264_FALLBACK_CHECK.json').read_text());assert fallback['passed']shutil.copy2(out/'QUICK_VALIDATION.json',out/'INITIAL_CHECKER_ALERT.json')rows=fallback['views']report['checked_sequences']+=1;report['checked_views']+=len(rows)report['checked_view_frames']+=sum(r['frames'] for r in rows)report['rgb_source_frames']+=sum(r['rgb_source_frames'] for r in rows)report['depth_source_frames']+=sum(r['depth_source_frames'] for r in rows)report['numeric_components']+=sum(r['numeric_components'] for r in rows)report['samples'].append({'sequence_id':'subject1_k2_6','camera':'cam0','object':'espresso', 'frames':678,'passed':True,'html':fallback['html'], 'extra_check':'Full RGB/depth/valid current decoded digests equal original receipts'})report['resolved_alerts']=[{'view':'subject1_k2_6/cam0','classification':'Registered lossless H.264 fallback, not missing data or corruption', 'original_checker_limitation':'First pass selected only FFV1 proofs; fixed to select the profile actually declared by metainfo', 'followup':'All five cameras rechecked; problematic view RGB, depth and validity fully decoded and matched original SHA256/byte length'}]report['failures']=[];report['passed']=Truereport['time']=datetime.datetime.now(ZoneInfo('Asia/Shanghai')).isoformat()report['sample_views']=len(report['samples'])assert report['checked_sequences']==184 and report['checked_views']==920assert report['checked_view_frames']==report['rgb_source_frames']==report['depth_source_frames']==571645report['rgb_profiles']={}for meta in (release/'data').glob('*/cam*/metainfo.json'): name=json.loads(meta.read_text())['components']['rgb']['storage']['profile'] report['rgb_profiles'][name]=report['rgb_profiles'].get(name,0)+1(out/'QUICK_VALIDATION.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')summary={k:v for k,v in report.items() if k!='samples'}(out/'index.html').write_text('<!doctype html><html lang="zh"><meta charset="utf-8"><title>H2O 全量后抽样验收</title><h1>H2O 全量后抽样验收</h1><p>自动检查通过不等于原始几何标注准确。覆盖四个 subject、八类物体、ego/exo;青色为源手部关节点投影,粉色为源物体点投影,仅用于预览。</p><ul>'+''.join('<li><a href="'+html.escape(x['html'],quote=True)+'">'+html.escape(x['sequence_id']+' '+x['camera']+' '+x['object'])+'</a></li>' for x in sorted(report['samples'],key=lambda x:(x['object'],x['sequence_id'],x['camera'])))+'</ul><pre>'+html.escape(json.dumps(summary,ensure_ascii=False,indent=2))+'</pre></html>')operations=release/'script/provenance/operations'for src in ('h2o-quick-validation.py','h2o-check-fallback.py','h2o-finalize-quick-validation.py'): shutil.copy2(Path('/tmp')/src,operations/src)shutil.copy2('/tmp/h2o-quick-validation.log',out/'INITIAL_RUN.log')shutil.copy2('/tmp/h2o-fallback-check.log',out/'FALLBACK_RUN.log')print(json.dumps(summary,ensure_ascii=False,indent=2),flush=True)12345678910111213141516171819202122232425#!/usr/bin/env bashset -ucd /home/xuzhefeng/Projects/uni-hoi-dataset || exit 1case "$1" in old) code=/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10/frozen-code/scripts/convert_h2o_v1.0.py; extra=();; v8) code=/tmp/h2o-stream-v8-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 8 --stream-media);; v8ram) code=/tmp/h2o-stream-v8ram-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 8 --stream-media --ram-stage-dir /dev/shm/xuzhefeng-h2o-pipeline-v8ram-20260930 --ram-stage-gib 32);; s16) code=/tmp/h2o-stream-s16-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 16 --stream-media --ffv1-slices 16 --ram-stage-dir /dev/shm/xuzhefeng-h2o-pipeline-s16-20260930 --ram-stage-gib 32);; pipeline) code=/tmp/h2o-stream-pipeline-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 16 --camera-pipeline --stream-media --ffv1-slices 16 --ram-stage-dir /dev/shm/xuzhefeng-h2o-pipeline-overlap-20260930 --ram-stage-gib 32);; process) code=/tmp/h2o-process-pipeline-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 16 --view-backend processes --camera-pipeline --stream-media --ffv1-slices 16 --ram-stage-dir /dev/shm/xuzhefeng-h2o-pipeline-process-20260930 --ram-stage-gib 32);; v16) code=/tmp/h2o-stream-v8-recovery/scripts/convert_h2o_v1.0.py; extra=(--view-workers 16 --stream-media);; *) exit 2;;esacroot=/data/xuzhefeng/Datasets/uni-hoi-h2o-pipeline-bench-20260930caseout="$root/$1"mkdir -p "$caseout/scratch"export TMPDIR="$caseout/scratch" PYTHONUNBUFFERED=1cg=$(awk -F: '$1=="0" {print $3}' /proc/self/cgroup)cat "/sys/fs/cgroup$cg/cpu.stat" > "$caseout/cpu.start"date -Is > "$caseout/start".venv/bin/python "$code" --root "$root/raw" --out "$caseout" --workers 4 --codec-threads 10 --decode-threads 10 --depth-threads 4 --max-frames 200 --mano-dir /home/xuzhefeng/Projects/WiLoR/mano_data "${extra[@]}" > "$caseout/convert.log" 2>&1code=$?cat "/sys/fs/cgroup$cg/cpu.stat" > "$caseout/cpu.end"printf '%s\n' "$code" > "$caseout/exit"exit "$code"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748import datetime,json,os,subprocess,timefrom pathlib import Pathroot=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-pipeline-bench-20260930')cpus=os.cpu_count()records=[]for mode in ('old','v8'): unit=f'h2o-pipeline-{mode}-20260930.scope' begin=time.monotonic() proc=subprocess.Popen(['systemd-run','--user','--scope','--unit='+unit,'-p','CPUAccounting=yes', '/bin/bash','/tmp/h2o-pipeline-bench-job.sh',mode]) path=Path(f'/sys/fs/cgroup/user.slice/user-{os.getuid()}.slice/user@{os.getuid()}.service/app.slice/{unit}') samples=[] while proc.poll() is None: try: stat=dict(line.split() for line in (path/'cpu.stat').read_text().splitlines()) samples.append((time.monotonic()-begin,int(stat['usage_usec']))) except (FileNotFoundError,PermissionError):pass time.sleep(0.5) elapsed=time.monotonic()-begin assert proc.returncode==0,(mode,(root/mode/'convert.log').read_text()[-3000:]) def usage(name):return int(dict(line.split() for line in (root/mode/name).read_text().splitlines())['usage_usec']) total=usage('cpu.end')-usage('cpu.start') peak=max(((b[1]-a[1])/(b[0]-a[0])/1e6/cpus*100 for a,b in zip(samples,samples[10:])),default=0) row=dict(mode=mode,seconds=elapsed,cpu_seconds=total/1e6,cpu_percent_machine=total/elapsed/1e6/cpus*100, peak_5s_cpu_percent_machine=peak,samples=samples) records.append(row) (root/'performance.json').write_text(json.dumps(records,indent=2)+'\n') print(json.dumps({k:v for k,v in row.items() if k!='samples'}),flush=True)# Prove actual media and every numeric tensor match, not just wall-clock speed.os.environ['HAND_WAREHOUSE_FFMPEG_THREADS'] = '10'import syssys.path.insert(0,'/tmp/h2o-stream-v8-recovery/scripts')from warehouse_v1_0 import decoded_digest,validate_viewimport torchfor view in sorted((root/'old/H2O/shared-v1.0/data').glob('*/cam*')): rel=view.relative_to(root/'old/H2O/shared-v1.0/data') candidate=root/'v8/H2O/shared-v1.0/data'/rel assert validate_view(candidate)['validated'] for name,pix in (('rgb','rgb24'),('depth','gray16le'),('depth_valid','gray')): aa=decoded_digest(view/'observation'/f'{name}.mkv',pix)[:2] bb=decoded_digest(candidate/'observation'/f'{name}.mkv',pix)[:2] assert aa==bb,(rel,name) for pt in view.rglob('*.pt'): aa=torch.load(pt,weights_only=True) bb=torch.load(candidate/pt.relative_to(view),weights_only=True) assert aa.shape==bb.shape and aa.dtype==bb.dtype and aa.numpy().tobytes()==bb.numpy().tobytes(),(rel,pt)print('PASS all 10 real views: full RGB/depth/valid decoded digests and every numeric tensor match',flush=True)(root/'validation.exit').write_text('0\n')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748import datetime,json,os,subprocess,timefrom pathlib import Pathroot=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-pipeline-bench-20260930')cpus=os.cpu_count()records=[]for mode in ('process',): unit=f'h2o-pipeline-{mode}-20260930.scope' begin=time.monotonic() proc=subprocess.Popen(['systemd-run','--user','--scope','--unit='+unit,'-p','CPUAccounting=yes', '/bin/bash','/tmp/h2o-pipeline-bench-job.sh',mode]) path=Path(f'/sys/fs/cgroup/user.slice/user-{os.getuid()}.slice/user@{os.getuid()}.service/app.slice/{unit}') samples=[] while proc.poll() is None: try: stat=dict(line.split() for line in (path/'cpu.stat').read_text().splitlines()) samples.append((time.monotonic()-begin,int(stat['usage_usec']))) except (FileNotFoundError,PermissionError):pass time.sleep(0.5) elapsed=time.monotonic()-begin assert proc.returncode==0,(mode,(root/mode/'convert.log').read_text()[-3000:]) def usage(name):return int(dict(line.split() for line in (root/mode/name).read_text().splitlines())['usage_usec']) total=usage('cpu.end')-usage('cpu.start') peak=max(((b[1]-a[1])/(b[0]-a[0])/1e6/cpus*100 for a,b in zip(samples,samples[10:])),default=0) row=dict(mode=mode,seconds=elapsed,cpu_seconds=total/1e6,cpu_percent_machine=total/elapsed/1e6/cpus*100, peak_5s_cpu_percent_machine=peak,samples=samples) records.append(row) (root/'performance-process.json').write_text(json.dumps(records,indent=2)+'\n') print(json.dumps({k:v for k,v in row.items() if k!='samples'}),flush=True)# Prove actual media and every numeric tensor match, not just wall-clock speed.os.environ['HAND_WAREHOUSE_FFMPEG_THREADS'] = '10'import syssys.path.insert(0,'/tmp/h2o-process-pipeline-recovery/scripts')from warehouse_v1_0 import decoded_digest,validate_viewimport torchfor view in sorted((root/'old/H2O/shared-v1.0/data').glob('*/cam*')): rel=view.relative_to(root/'old/H2O/shared-v1.0/data') candidate=root/'process/H2O/shared-v1.0/data'/rel assert validate_view(candidate)['validated'] for name,pix in (('rgb','rgb24'),('depth','gray16le'),('depth_valid','gray')): aa=decoded_digest(view/'observation'/f'{name}.mkv',pix)[:2] bb=decoded_digest(candidate/'observation'/f'{name}.mkv',pix)[:2] assert aa==bb,(rel,name) for pt in view.rglob('*.pt'): aa=torch.load(pt,weights_only=True) bb=torch.load(candidate/pt.relative_to(view),weights_only=True) assert aa.shape==bb.shape and aa.dtype==bb.dtype and aa.numpy().tobytes()==bb.numpy().tobytes(),(rel,pt)print('PASS all 10 real views: full RGB/depth/valid decoded digests and every numeric tensor match',flush=True)(root/'validation-process.exit').write_text('0\n')12345678910111213141516171819202122232425262728import json,os,tarfile,shutilfrom pathlib import Pathroot=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-pipeline-bench-20260930')root.mkdir(exist_ok=True)raw=root/'raw'; raw.mkdir(exist_ok=True)old=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10')records=[]for subj in ('subject3','subject4'): subject=next((old/'scratch').glob('h2o-source-*/'+subj)) sequences=[p for p in subject.glob('*/*') if all((p/f'cam{i}/rgb/000199.png').is_file() for i in range(5))] assert sequences, (subj,subject) seq=sequences[0] snapshot=root/'input-snapshot'/subj/seq.relative_to(subject) for src in seq.glob('cam*/*/*'): if src.is_file() and src.parent.name in ('rgb','depth','cam_pose','hand_pose','hand_pose_mano','obj_pose','obj_pose_rt') and int(src.stem)<200: dest=snapshot/src.relative_to(seq);dest.parent.mkdir(parents=True,exist_ok=True) os.link(src,dest) for src in seq.glob('cam*/cam_intrinsics.txt'): dest=snapshot/src.relative_to(seq);dest.parent.mkdir(parents=True,exist_ok=True);os.link(src,dest) archive=raw/f'{subj}_v1_1.tar.gz' with tarfile.open(archive,'w:gz',compresslevel=0) as tf: tf.add(snapshot,arcname=str(snapshot.relative_to(root/'input-snapshot'))) records.append({'sequence':str(snapshot.relative_to(root/'input-snapshot')),'frames':200,'views':5,'archive':str(archive), 'origin':str(seq),'gzip_compression_level':0})for name in ('object.zip','label_split.zip'): os.link(Path('/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data')/name,raw/name)(root/'input-manifest.json').write_text(json.dumps(records,indent=2)+'\n')print('PREPARED',records,flush=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445"""Preserve complete persistent views; frozen process pipeline only changes execution/storage work."""import datetime,json,os,shutilfrom pathlib import Pathold=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10')new=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe')new.mkdir()shutil.copytree('/tmp/h2o-process-pipeline-recovery',new/'frozen-code')release=new/'H2O/shared-v1.0'for directory in ('data','doc/validation','script/provenance/previous-run','script/provenance/operations'): (release/directory).mkdir(parents=True,exist_ok=True)history=release/'script/provenance/previous-run'shutil.copytree(old/'H2O/shared-v1.0/script',history/'script')shutil.copytree(old/'frozen-code/docs',history/'docs')for name in ('full.log','full.status','run-full.sh'): shutil.copy2(old/name,history/name)records=[]for record in sorted((old/'H2O/shared-v1.0/doc').glob('*.build.json')): build=json.loads(record.read_text());seq=build['sequence_id'] assert Path(seq).name==seq and seq not in ('.','..') assert set(build['views'])=={f'cam{i}' for i in range(5)} folder=old/'H2O/shared-v1.0/data'/seq for cam in build['views']:assert (folder/cam/'metainfo.json').is_file() shutil.copytree(folder,release/'data'/seq,copy_function=os.link) shutil.copy2(record,release/'doc'/record.name) records.append({'sequence_id':seq,'original_script_sha256':build['scripts']})manifest={'time':datetime.datetime.now().astimezone().isoformat(),'source_run':str(old),'destination_run':str(new), 'reason':'Native bytes unchanged; process/view pipeline, streaming RAW and bounded RAM staging', 'target_cpu_percent_machine':80,'cpu_limit':None,'reused_sequences':records, 'reuse':'Read-only hardlinks; original build records retained; source frame/component SHA256 checked on resume', 'previous_run_provenance':'script/provenance/previous-run'}(release/'doc/RESTART_PROVENANCE.json').write_text(json.dumps(manifest,indent=2)+'\n')operations=release/'script/provenance/operations'for name in ('h2o-prepare-process-full.py','h2o-switch-process-full.sh','h2o-pipeline-benchmark.py', 'h2o-pipeline-process-benchmark.py','h2o-pipeline-bench-job.sh','h2o-prepare-pipeline-bench.py', 'h2o-process-final-tests.log','h2o-shared-final-tests.log'): shutil.copy2(Path('/tmp')/name,operations/name)bench=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-pipeline-bench-20260930')for p in bench.glob('performance*.json'):shutil.copy2(p,release/'doc/validation'/p.name)shutil.copy2(bench/'input-manifest.json',release/'doc/validation/PIPELINE_BENCH_INPUTS.json')shutil.copy2('/tmp/h2o-pipeline-process-benchmark.log',release/'doc/validation/PIPELINE_BENCHMARK.log')shutil.copy2('/tmp/h2o-runtime-profile.log',release/'doc/validation/BEFORE_RUNTIME_PROFILE.log')shutil.copy2('/tmp/h2o-current-iostat.log',release/'doc/validation/BEFORE_IOSTAT.log')for destination in (new/'run-full.sh',release/'script/run-full.sh'): shutil.copy2('/tmp/h2o-run-process-full.sh',destination)print('REUSED_SEQUENCES',len(records),'REUSED_VIEWS',5*len(records),flush=True)123456789101112131415161718192021222324252627282930313233343536373839Converted subject1/h1/0Converted subject2/h1/0Converted subject3/h1/0Converted subject4/h1/0Converted subject1/h1/0Archive subject1_v1_1.tar.gz: 1 sequencesConverted subject2/h1/0Archive subject2_v1_1.tar.gz: 1 sequencesConverted subject3/h1/0Archive subject3_v1_1.tar.gz: 1 sequencesConverted subject4/h1/0Archive subject4_v1_1.tar.gz: 1 sequencesConverted subject2/h1/0Converted subject3/h1/0Converted subject1/h1/0Archive subject1_v1_1.tar.gz: 1 sequencesArchive subject2_v1_1.tar.gz: 1 sequencesArchive subject3_v1_1.tar.gz: 1 sequencesConverted subject4/h1/0Archive subject4_v1_1.tar.gz: 1 sequencesVerified existing subject1/h1/0Verified existing subject3/h1/0Archive subject1_v1_1.tar.gz: 1 sequencesVerified existing subject2/h1/0Verified existing subject4/h1/0Archive subject2_v1_1.tar.gz: 1 sequencesArchive subject3_v1_1.tar.gz: 1 sequencesArchive subject4_v1_1.tar.gz: 1 sequencesCamera-order fallback: subject1/h1/0Converted subject1/h1/0Converted subject2/h1/0Converted subject1/h1/0Archive subject1_v1_1.tar.gz: 1 sequencesArchive subject2_v1_1.tar.gz: 1 sequencesConverted subject3/h1/0Archive subject3_v1_1.tar.gz: 1 sequencesConverted subject4/h1/0Archive subject4_v1_1.tar.gz: 1 sequencesPASS H2O pipe RGB/depth, RAM annotations, shared view pool 1/4/8, four archive workers, codec/decode 1/4/10, ordered depth 1/2/4 and missing-depth preservation, no resume PNG writes, RGB FFV1-only, depth and persistent QC123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161"""Full coverage/numeric audit, plus representative persisted-media QC and offline HTML."""import osfor key in ('OMP_NUM_THREADS','OPENBLAS_NUM_THREADS','MKL_NUM_THREADS','NUMEXPR_NUM_THREADS'): os.environ[key]='1'os.environ['HAND_WAREHOUSE_FFMPEG_THREADS']='4'os.environ.pop('HAND_WAREHOUSE_FFV1_SLICES',None)os.environ.pop('HAND_WAREHOUSE_MEDIA_TMPDIR',None)import collections,datetime,hashlib,html,json,re,sys,time,zipfilefrom concurrent.futures import ThreadPoolExecutor,as_completedfrom pathlib import Pathfrom zoneinfo import ZoneInfoimport numpy as npimport torchroot=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe')release=root/'H2O/shared-v1.0'sys.path.insert(0,str(root/'frozen-code/scripts'))from warehouse_v1_0 import SCHEMA,check_transform,check_valid_policy,check_view_type,safe_member,sha256from render_h2o_validation import renderout=release/'doc/validation/final-quick-check'out.mkdir(exist_ok=True)torch.set_num_threads(1)started=time.monotonic()expected={}with zipfile.ZipFile('/data/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O/raw/data/label_split.zip') as z: for name in z.namelist(): if '/action_' not in name:continue for line in z.read(name).decode().splitlines(): fields=line.split() if len(fields)>1 and fields[1]!='path': seq=fields[1].replace('/','_') expected[seq]=max(expected.get(seq,0),int(fields[-1])+1)folders={p.name:p for p in (release/'data').iterdir() if p.is_dir()}assert set(folders)==set(expected),(sorted(set(expected)-set(folders)),sorted(set(folders)-set(expected)))assert len(expected)==184 and sum(expected.values())==114329receipts={p.name.removesuffix('.build.json'):p for p in (release/'doc').glob('*.build.json')}assert set(receipts)==set(expected)assert 'EXIT=0' in (root/'full.status').read_text()failures=[]rows=[]def require(ok,message): if not ok:raise ValueError(message)def load(path): def cpu(storage,location): require(location=='cpu',f'non-CPU storage: {path}') return storage obj=torch.load(path,map_location=cpu,weights_only=True) require(type(obj) is torch.Tensor,f'non-tensor: {path}') return obj.numpy()def check_sequence(seq): folder=folders[seq];n=expected[seq] require({p.name for p in folder.iterdir() if p.is_dir()}=={f'cam{i}' for i in range(5)},'five-camera coverage') receipt=json.loads(receipts[seq].read_text()) require(receipt['sequence_id']==seq and set(receipt['views'])=={f'cam{i}' for i in range(5)},'build receipt') result=[] for i in range(5): cam=f'cam{i}';view=folder/cam meta=json.loads((view/'metainfo.json').read_text()) require((meta['dataset_id'],meta['sequence_id'],meta['camera_id'],meta['num_frames'])==('H2O',seq,cam,n),'header/timeline') require(meta['view_type']==('ego' if i==4 else 'exo'),'view role') require(meta['sampling']['selection']=={'max_frames':None,'views':None},'unexpected subsampling') check_view_type(meta) components=meta['components'] require(all(components[k].get('available') for k in ('rgb','depth','mano','keypoints_xyz','intrinsic','extrinsic')),'required modality absent') require(not components['segment']['available'] and not components['relations']['available'],'unexpected synthesized component') rgb_sources=[];depth_sources=[];rgb_count=depth_count=0 with (view/'camera/frames.jsonl').open() as inp: count=0 for index,line in enumerate(inp): f=json.loads(line) require(f['frame_index']==index and f['source_frame_id']==index,'source frame index') require(f['sync_id']==f'{seq.replace("_","/")}:{index}','synchronization ID') sources=f['component_sources'] for kind,loc in sources.items(): require(re.fullmatch('[0-9a-f]{64}',loc.get('sha256','')) is not None,f'source SHA256: {kind}') require(f'/{cam}/' in loc.get('member',''),'wrong source camera') rgb_sources.append('rgb' in sources);depth_sources.append('depth' in sources) rgb_count+=rgb_sources[-1];depth_count+=depth_sources[-1];count+=1 require(count==n,'frames.jsonl length') numeric=0 object_names=[] for key,c in components.items(): if not c['available']:continue for field in ('data_ref','valid_ref','mapping_ref'): if c.get(field): path=safe_member(view,c[field]) require(path.is_file() and path.stat().st_size>0,f'missing/empty {c[field]}') schema=SCHEMA['components'][c['schema_id']] if c.get('valid_policy'):check_valid_policy(c,n) valid=load(view/c['valid_ref']) if c.get('valid_ref','').endswith('.pt') else None if valid is not None: shape=schema.get('valid_shape') require(valid.dtype==np.bool_ and valid.shape[0]==n,f'{key}: validity dtype/timeline') if shape:require(len(shape)==valid.ndim and all(not isinstance(s,int) or valid.shape[j]==s for j,s in enumerate(shape)),f'{key}: validity shape') if key=='rgb':require(np.array_equal(valid,np.asarray(rgb_sources)), 'RGB existence validity mismatch') if c['data_ref'].endswith('.pt'): arr=load(view/c['data_ref']);numeric+=1 require(arr.dtype==np.float32 and arr.shape[0]==n,f'{key}: dtype/timeline') shape=schema.get('shape') if shape:require(len(shape)==arr.ndim and all(not isinstance(s,int) or arr.shape[j]==s for j,s in enumerate(shape)),f'{key}: tensor shape') if valid is not None: require(arr.shape[:valid.ndim]==valid.shape and np.isfinite(arr[valid]).all() and np.isnan(arr[~valid]).all(),f'{key}: finite/NaN validity semantics') if c['schema_id'] in ('transform/se3/v1','object/rigid/v1'):check_transform(arr[valid]) if key=='intrinsic':require(np.allclose(arr[:,2],[0,0,1]) and (arr[:,0,0]>0).all() and (arr[:,1,1]>0).all(),'camera intrinsics') if key.startswith('mesh_'):object_names.append(key.removeprefix('mesh_')) proof=receipt['views'][cam] require(not proof['unresolved'],'unresolved QC components') media={} for p in proof['validation']: if p.get('profile')==components['rgb']['storage']['profile'] and p.get('all_frames_exact') is True:media['rgb']=p elif p.get('component') in ('depth','depth_valid'):media[p['component']]=p require(set(media)=={'rgb','depth','depth_valid'},'media roundtrip proof missing') for key,p in media.items(): require(p.get('all_frames_exact') is True and re.fullmatch('[0-9a-f]{64}',p.get('decoded_sha256','')) is not None,f'{key}: failed original roundtrip proof') require((view/'observation'/f'{key}.mkv').stat().st_size==p['bytes'],f'{key}: encoded file size changed since conversion') result.append({'sequence_id':seq,'camera':cam,'frames':n,'numeric_components':numeric, 'rgb_source_frames':rgb_count,'depth_source_frames':depth_count,'objects':sorted(object_names)}) return resultwith ThreadPoolExecutor(max_workers=4) as pool: jobs={pool.submit(check_sequence,seq):seq for seq in sorted(expected)} for job in as_completed(jobs): seq=jobs[job] try:rows.extend(job.result()) except Exception as exc:failures.append({'sequence':seq,'error':repr(exc)}) if len(rows)%100==0:print('STRUCTURAL_VIEWS',len(rows),'FAILURES',len(failures),flush=True)print('STRUCTURAL_COMPLETE',len(rows),'FAILURES',failures,flush=True)# Balance subjects while covering all eight source object classes; include matching exo views.objects=('book','espresso','lotion','spray','milk','cocoa','chips','cappuccino')selected=[]for j,name in enumerate(objects): subject=f'subject{j%4+1}_' candidates=[r for r in rows if r['camera']=='cam4' and name in r['objects']] require(candidates,f'no output for object {name}') own=[r for r in candidates if r['sequence_id'].startswith(subject)] r=min(own or candidates,key=lambda x:(x['frames'],x['sequence_id'])) selected.append((r['sequence_id'],'cam4',name)) selected.append((r['sequence_id'],'cam0',name))samples=[]def full_sample(item): seq,cam,name=item view=folders[seq]/cam destination=out/f'{seq}_{cam}' page=render(view,destination) # Reuse persisted contract QC, depth semantics, frame snapshots, native mesh preview. return {'sequence_id':seq,'camera':cam,'object':name,'frames':expected[seq], 'passed':True,'html':str(page.relative_to(out))}with ThreadPoolExecutor(max_workers=4) as pool: jobs={pool.submit(full_sample,item):item for item in selected} for job in as_completed(jobs): item=jobs[job] try:samples.append(job.result());print('SAMPLE_PASS',item,flush=True) except Exception as exc:failures.append({'sample':item,'error':repr(exc)});print('SAMPLE_FAIL',item,repr(exc),flush=True)report={'time':datetime.datetime.now(ZoneInfo('Asia/Shanghai')).isoformat(),'elapsed_seconds':time.monotonic()-started, 'release':str(release),'passed':not failures,'scope':'All sequence/camera coverage, frame/source manifests, all numeric tensors and original media receipts; 16 representative full persisted-view QC checks and offline previews. Not a new all-video source-pixel comparison.', 'expected_sequences':len(expected),'expected_sync_frames':sum(expected.values()), 'checked_sequences':len(rows)//5,'checked_views':len(rows),'checked_view_frames':sum(r['frames'] for r in rows), 'rgb_source_frames':sum(r['rgb_source_frames'] for r in rows),'depth_source_frames':sum(r['depth_source_frames'] for r in rows), 'numeric_components':sum(r['numeric_components'] for r in rows),'samples':samples,'failures':failures, 'next_step':'Human inspection of representative offline HTML; automatic QC is not proof of source geometric accuracy.'}(out/'QUICK_VALIDATION.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')(out/'index.html').write_text('<!doctype html><html lang="zh"><meta charset="utf-8"><title>H2O 全量后抽样验收</title><h1>H2O 全量后抽样验收</h1><p>自动检查通过不等于源几何标注正确;以下为四个 subject、八类物体、ego/exo 的源数据预览。</p><ul>'+''.join('<li><a href="'+html.escape(x['html'],quote=True)+'">'+html.escape(x['sequence_id']+' '+x['camera']+' '+x['object'])+'</a></li>' for x in sorted(samples,key=lambda x:(x['object'],x['camera'])))+'</ul><pre>'+html.escape(json.dumps({k:v for k,v in report.items() if k not in ('samples',)},ensure_ascii=False,indent=2))+'</pre></html>')print('FINAL_REPORT',json.dumps({k:v for k,v in report.items() if k!='samples'},ensure_ascii=False),flush=True)raise SystemExit(0 if report['passed'] else 1)1PASS: RGB full/prefix hashes, source depth frames, depth/valid/segment bits and missing-frame rejection123456789101112#!/usr/bin/env bashset -euo pipefailcd /home/xuzhefeng/Projects/uni-hoi-datasettest "$(cat /tmp/h2o-process-final-tests.exit)" = 0test "$(cat /tmp/h2o-shared-final-tests.exit)" = 0test "$(cat /tmp/h2o-pipeline-process-benchmark.exit)" = 0test ! -e /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipeold=/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10printf '\nRECONFIGURE=%s REASON=process16_camera_pipeline_ram32_streaming\n' "$(date -Is)" >> "$old/full.status"systemctl --user stop h2o-full-d10-20260930.scope.venv/bin/python /tmp/h2o-prepare-process-full.pysystemd-run --user --scope --unit=h2o-full-process16-20260930 -p CPUAccounting=yes /bin/bash /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe/run-full.sh1234567891011121314151617181920212223242526272829303132333435363738"""Measure the whole process tree only after conversion FFmpeg is active; no CPU-fill work."""import datetime,json,os,timefrom pathlib import Pathunit='h2o-full-process16-20260930.scope'cg=Path(f'/sys/fs/cgroup/user.slice/user-{os.getuid()}.slice/user@{os.getuid()}.service/app.slice/{unit}')root=Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-process16-pipe')report=root/'H2O/shared-v1.0/doc/validation/STEADY_CPU_5MIN.json'start_wait=time.monotonic()while time.monotonic()-start_wait<7200: if not (cg/'cgroup.procs').exists(): print('Scope exited before a steady conversion sample',flush=True);raise SystemExit(1) ffmpeg=False for pid in (cg/'cgroup.procs').read_text().split(): try:ffmpeg |= Path('/proc',pid,'comm').read_text().strip()=='ffmpeg' except FileNotFoundError:pass if ffmpeg:break time.sleep(5)else: print('No conversion FFmpeg within two hours; no steady CPU claim made',flush=True);raise SystemExit(2)def sample(): values=dict(line.split() for line in (cg/'cpu.stat').read_text().splitlines()) return time.monotonic(),int(values['usage_usec'])begin=datetime.datetime.now().astimezone().isoformat()samples=[sample()]for _ in range(60): time.sleep(5) try:samples.append(sample()) except FileNotFoundError: print('Scope exited during sample; inspect full.status',flush=True);raise SystemExit(1)cpus=os.cpu_count()intervals=[(b[1]-a[1])/(b[0]-a[0])/1e6/cpus*100 for a,b in zip(samples,samples[1:])]result={'start':begin,'end':datetime.datetime.now().astimezone().isoformat(),'logical_cpus':cpus, 'whole_scope_cpu_percent_machine':(samples[-1][1]-samples[0][1])/(samples[-1][0]-samples[0][0])/1e6/cpus*100, 'highest_5sec_cpu_percent_machine':max(intervals),'lowest_5sec_cpu_percent_machine':min(intervals), 'target_percent':80,'intervals_percent_machine':intervals,'samples':samples, 'scope':unit,'includes':'All scope threads and child processes, including children already exited'}report.write_text(json.dumps(result,indent=2)+'\n')print(json.dumps({k:v for k,v in result.items() if k not in ('samples','intervals_percent_machine')}),flush=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457# 手物数据仓库统一约定 v1.0
格式版本:`hand-warehouse/1.0`。存储约定:`lossless-video-2026-09-18`。
范围限于手物交互重建。按本任务纳入的源模态转换,不要求每个数据集填满所有组件。缺失模态、尚未下载、语义未核实分别报告,不能互相替代。
本文定义各字段的含义与使用规则,机器可读注册表见 [schema.json](schema.json)。两者互相补充;如有冲突,应先核实并统一定义。
## 1. 目录
```text
hand-datasets/
<dataset_name>/
raw/
doc/ # 官方说明、来源与校验记录
script/ # 官方下载脚本、必要包装脚本
data/ # 保留原始包,不原地解压或改写
<dataset_version>/
doc/ # 发布说明、schema、来源清单
script/ # 转换、校验脚本及运行配置
data/
<sequence_id>/
<camera_id>/
metainfo.json
observation/
rgb.mkv
rgb_valid.pt
depth.mkv # float32 深度的可逆视频编码
depth_valid.mkv # 逐像素 bool 的无损视频编码
camera/
frames.jsonl
intrinsic.pt
intrinsic_valid.pt
extrinsic.pt
extrinsic_valid.pt
annotation/
mano/
motion.pt
motion_valid.pt
visibility.pt
keypoints/
uv.pt
uv_valid.pt
xyz.pt
xyz_valid.pt
visibility.pt # 源数据有时提供
object/
<object_id>/
assets/ # 该物体的网格、材质、纹理及部件资产
<mesh_id>.obj
pose.pt
pose_valid.pt
visibility.pt
metainfo.json # 物体身份、类别、mesh、尺寸与部件引用
articulation.json
keypoints/
vertex_part_ids.pt
joint_state.pt
joint_state_valid.pt
parts/<part_id>/pose.pt
parts/<part_id>/pose_valid.pt
segment/
mask.mkv
mask_valid.pt
instances.jsonl
contact/
relations.jsonl
<subject_id>__<object_id>/ # 对应实体间的距离/接触区域
```
目录展示可能存在的组件,不要求填满。具体文件、字段和缺省规则分别见后续对应小节。原始包的解压发生在临时工作区,raw 内原始包保持不变。
## 2. 相机视图的 metainfo.json
### 2.1 顶层字段与发布信息
每个相机视图必须有 `metainfo.json`。以下字段除另行说明外均为必填:
| 字段 | 填写内容 |
|---|---|
| schema_version | 结构版本,本版为 `hand-warehouse/1.0` |
| dataset_id | 数据集的逻辑标识 |
| release_id | 本次数据发布版本,对应目录中的 dataset_version |
| sequence_id | 所属序列或独立图片样本的标识 |
| camera_id | 当前相机视图标识 |
| sample_type | `image` 或 `video`,规则见 2.2 |
| num_frames | 当前视图帧数 T,所有随帧组件按同一时间轴组织 |
| hand_slots | 固定为 `["left", "right"]`;解剖学左右的使用规则见 5.1 |
| sampling | 采样类型、源 FPS、帧索引引用及选择策略,见 2.2 |
| camera | 当前相机模型与图像尺寸,见 2.3 |
| components | 实际提供的组件及其文件、schema、有效性和来源,见 2.5 |
| split | `train/val/test/unknown`,划分协议见 2.4 |
| view_type | 可选,`ego/exo/unknown` |
`dataset_version` 是数据发布版本;`schema_version` 是结构版本,两者独立。原始包校验摘要、官方来源和转换配置应记录在发布清单中。解压发生在临时工作区,原始包保持不变。
### 2.2 图片、视频与 sampling
`sample_type=image`:允许单图 T=1、`sampling.type=single`,也允许将独立图片批量装入一个视频容器,T>1 时 `sampling.type=independent`、`source_fps=null`。分片大小按数据集选择;FreiHAND 默认每片最多 4096 张,训练与评估分开,尾片不补帧。该数量不是其他数据集的强制要求;同批分辨率、相机模型类型及划分协议一致。每行 frames 必须有稳定且唯一的 `sample_id`、原始文件定位;内参、手形状等仍逐帧保留,不能因打包而共享错误的标定或身份。`sequence_id` 在这里仅是批次标识,不代表真实序列;不得按相邻帧推断跟踪、同步或接触延续。源 camera_id、image_variant、split 等随样本变化时放在 frames 的对应字段中。真实采集时间未知则 timestamp_ns=null。合成背景变体不视为真实多相机。
`sample_type=video`:`sampling.type=dense/sparse`;`source_fps` 是真实采集 FPS,未知为 null。非连续取样必须保留源帧号和已知源时间,不可用采样后索引除以 FPS 冒充源时间。可另记采样策略与步长。
shared 可以仅存所选 RGB 帧对应的数据。OakInk2 图像/动捕不同采样率时用 annotation_matches 明确映射;不要求将未采样动捕点硬塞进 T。多视角身份和源同步关系要保留;选择了哪些帧/相机及原因写在 sampling 中。
`sampling.frames_ref` 指向 `camera/frames.jsonl`。帧号、逐帧时间、同步与标注匹配记录的结构见 4.1;MKV 封装时间的约定见 3.1。
### 2.3 camera 模型声明
`camera` 至少包含 `model`、`schema_id`、`image_size:[W,H]`。模型未知使用 `unknown` 和 `null`,不猜成针孔。实际内参、畸变及外参数组放在 `camera/`,各模型的固定结构见第 4 节。
### 2.4 split 与划分协议
保留上游划分,不将同一采集序列的相邻帧随意拆到不同集合。
有官方划分时必填 split_scheme 和 split_source_locator,split_scheme 区分如 Dex-YCB s0/s1、ARCTIC P1/P2 等选定协议;不知道时 split=unknown 并给理由,不凭空分配。每发布可选择一种协议;存在逐帧差异时 frames 中的 split 覆盖视图默认值,并登记其来源。
### 2.5 components 组件登记
组件表的键是本发布内唯一名称,例如 `rgb`、`depth`、`mano`、`keypoints_uv`。每个已提供组件声明以下信息;模态特有参数在第 3–5 节对应小节中定义。
| 字段 | 约定 |
|---|---|
| available | 本发布是否提供该组件;缺省也表示未提供 |
| schema_id | 已登记的具体存储与语义类型,不得临时创造未登记名称 |
| data_ref | 数据文件路径,相对当前相机视图根目录,使用 POSIX 路径 |
| axes | 数组各维度的含义 |
| valid_ref / valid_axes | 有效性文件及其维度;语义由所属组件规定 |
| storage / valid_storage | 视频数据/视频有效性的存储配置;包含已登记 profile、实际 codec、pixel_format、encoded_size,见 3.1;非视频组件按原数组规则 |
| provenance | source / format_conversion / derived,以及转换或生成方法 |
| source_locator | 原文件、压缩包成员和记录/帧的定位信息 |
不存在的组件允许缺省或写作 `{ "available": false, "reason": "..." }`,不用引用不存在的文件。静态网格可声明标量有效性;具体见 5.4。观测的 valid 见第 3 节,标注的 valid 与 visibility 区分见 5.1。
`provenance.kind` 使用 source/format_conversion/derived,`method` 说明转换或生成方法;发布清单补充脚本版本、参数、输入摘要。`source_locator` 定位到原始文件/压缩包成员和记录、帧号;允许引用有完整溯源清单的前一发布,但链条最终应能回到 raw。不得仅写一个无法定位记录的数据集名字。
`.pt` 仅保存 CPU Tensor,不保存 Python 自定义对象;浮点默认 float32,有效性为 bool,浮点无效位置填 NaN。所有随帧数组保留首维 T,单帧也不 squeeze;静态资产按其 schema 单独声明。单位、坐标及固定形状见各组件小节。
机器注册表 `schema.json` 中,`components` 固定解码后的数据类型、形状、单位和语义;`storage_profiles` 固定视频内的编码/还原方式。不得临时创造未登记的 schema_id 或 storage.profile。同一语义允许选择其登记的不同无损存储 profile。
## 3. observation 观测数据
### 3.1 rgb.mkv 与 rgb_valid.pt
RGB、深度和栅格 mask 在 shared 中统一使用 MKV 视频容器,不展开为逐帧图片或图像 tar。MANO、关键点、位姿等数值标注仍用数组;分割的重叠多边形仍用 JSONL,不为了视频化而有损栅格化。单图可为一帧视频,独立图批量封装规则见 2.2。
**无损指共享层不增加信息损失。** 源 JPEG/H.264 等本身可能已是有损编码,原样保留并不恢复已丢失信息;不得重新以有损 JPEG、H.264、H.265、AV1 参数编码。源视频/图片的色彩、位深、分辨率和几何关系不得被静默改变。RGB schema `rgb/uint8/v1` 的统一读取结果是 `[T,H,W,3] uint8`、RGB 通道,有效性仍为 `rgb_valid.pt [T] bool`。超出该 schema 的高位深或 HDR 源必须报告并扩展定义,不能降到 8 位冒充无损。
#### 3.1.1 允许的 RGB 存储 profile
| storage.profile | 编码方式 | 适用规则 |
|---|---|---|
| mkv/mjpeg_copy/v1 | 源 JPEG 压缩帧直接封装成 MJPEG/MKV | 不解码重编码;保持每张 JPEG 码流字节;普通 8 位 JPEG 且 MKV/解码器支持时使用 |
| mkv/source_copy/v1 | 已有视频的 RGB 对应码流直接封装为 MKV | 仅源编码能被 MKV 和选定解码器支持时使用,不伪造帧;需维持正确的呈现顺序与依赖帧 |
| mkv/h264_rgb_lossless/v1 | libx264rgb 的真正无损模式 | 必须 RGB 路径、CRF=0,并通过全帧 RGB 字节比较;不能替换成默认 libx264 YUV420 路径 |
| mkv/ffv1_rgb/v1 | FFV1 的 RGB 可逆编码路径 | 作为通用候选;解码回 RGB 后必须逐字节相同,不做色度降采样 |
优先尝试源码流直接封装;不能封装或需要选择稀疏帧时,比较 FFV1 与无损 RGB H.264。对完整待发布片段,只在通过无损验收的候选中选择文件较小者,不假设某个编码器总最小;编码时间和随机读取代价记入构建记录。中间候选不作为 shared 多份常驻。H.264 跨帧压缩允许较长 GOP,必须记录 GOP/关键帧间隔,随机取帧需从前一关键帧正确解码,不能把 seek 返回的近似帧当目标帧。
普通源视频可以保留它已有的有损码流,但不允许新增有损重编码。源是 VRS 等记录容器时,先查明图像流实际编码:已有兼容 JPEG/视频包可直接提取封装,否则解码后使用真正无损编码;不把整个 VRS 改后缀当 MKV。PNG 不要求直接塞进 MKV,可选上表两种无损重编码方式。
#### 3.1.2 视频配置与校验
每个视频组件在 metainfo 中登记 `storage`,至少包含:
| 字段 | 内容 |
|---|---|
| profile | 上述登记的存储 profile;语义仍由组件 schema_id 指定 |
| codec | 文件中实际 codec,例如 mjpeg、h264、ffv1;source_copy 必须写实际 codec |
| pixel_format | 实际编码像素格式;不得仅凭编码器参数猜测 |
| encoded_size | 视频物理像素尺寸 `[width,height]`;深度可能不同于逻辑尺寸,见 3.2 |
| decoder | 解码器名称、版本,以及颜色矩阵/范围/旋转处理等实际像素解释配置;未知的源色彩声明 unknown,不擅自称为 sRGB |
| encoder_parameters | 重编码时的编码器、版本、无损模式和 GOP 等参数;直接封装时记录 stream_copy |
| source_lossy | 源是否已有损:true / false / unknown;不是共享层再有损编码的许可 |
无损重新编码的 RGB 必须使用同一固定解码配置,比较**全部帧**的统一 RGB 字节、数量及顺序。MJPEG-copy 不重新编码,生产校验采用 `jpeg-packets-all-rgb-sample16/v1`:从 MKV 逐包取回,对全部源 JPEG 的 SHA256、数量、顺序和图像尺寸进行精确核对;每视图另用同一固定解码配置比较最多 16 帧的源与目标 RGB 字节(含首尾与四分位位置,其余由固定种子抽取)。记录策略、实际索引、种子与结果;不足 16 帧时全查。试点与最终完整序列随机抽查,对选中视图的全部帧复核解码 RGB。历史已做全帧像素检查的证明继续保留。
逐包一致与像素抽查的范围必须分别声明,不能将抽查写成全量像素检查。不能用 PSNR 高、视觉相似、编码器参数称为 lossless 等替代精确检查。同时保留源编码的色彩标记和必要元数据;原图有 EXIF/色彩/方向等元数据时保留 raw 和必要来源信息;不能静默自动旋转图像而不更新像素对应与标定。以上加速策略仅适用于原 JPEG 码流直接封装,不适用于深度、标签或重新编码的 RGB。
所有共享视频的呈现帧顺序与统一 frame_index 一一对应,每个栅格组件恰好 T 帧。MKV 的 `storage_fps` 只服务封装,声明 `timebase_role=index_only`;source_copy 可以保留源 PTS 以避免改坏码流,但真实时间与标注对齐仍以 frames 为准。未知真实时间保留 null。缺失某帧组件时保留索引位置并使用该组件的无效占位/valid 标识,不删帧;不能以重复相邻图像冒充已知观测。
### 3.2 depth.mkv 与 depth_valid.mkv
深度语义仍是 `depth/z_float32/v1`:统一读取结果 `[T,H,W] float32`,米制相机 Z 分量,`depth_type=z`。有效深度有限且大于 0,无效位置为 NaN。`depth_origin=measured/rendered/unknown` 必填,来源不明时 unknown。默认与 RGB 共用像素网格及相机参考系,不处理未注册 RGB-D。射线距离必须依据源定义转换成 z,不能只改声明。
#### 3.2.1 float32 的可逆视频编码
采用 `mkv/depth_float32_bits/v1`:**不是把深度量化成 uint16**,而是将规范化后每个 IEEE-754 float32 的完整 32 位拆成两个 uint16,使用 FFV1 gray16le 保存。视频物理尺寸为 `[2W,H]`:每行前 W 列存原 float32 位串的低 16 位,后 W 列存高 16 位。读取时先合并为 uint32 位串,再按 float32 重新解释,不能数值 cast 成 float32。
```text
u = reinterpret_uint32(depth_float32)
encoded[:, :, :W] = uint16(u & 65535)
encoded[:, :, W:] = uint16(u >> 16)
u_restored = uint32(low) | (uint32(high) << 16)
depth_float32 = reinterpret_float32(u_restored)
```
统一采用 little-endian 原始字节接口。`camera.image_size` 始终是逻辑 RGB 尺寸 `[W,H]`,不能改成编���视频的 2W;`storage.encoded_size=[2W,H]`。包括 NaN 在内的 float32 位串必须全帧完全恢复,不允许改成 float16、整数毫米、归一化灰度或 RGB 伪彩色。这里的无损验收基准是完成既定米制/坐标转换后的标准 float32 数组,不声称消除 float64→float32 等原约定转换本身的舍入。
#### 3.2.2 逐像素有效性
`depth_valid.mkv` 使用 `mkv/bool_ffv1/v1`,FFV1 gray8(FFmpeg pixel_format=`gray`),物理尺寸 `[W,H]`。像素只能为 0 或 1,统一解码为 `[T,H,W] bool`,逐像素含义不变。这样不再把庞大的 bool 数组保存为未压缩 `.pt`;标注的帧级/手级 valid 仍保留原有小数组。
登记示例(W、H 以下取 640、480;decoder/encoder_parameters 的实际版本由转换器填写):
```json
{
"available": true,
"schema_id": "depth/z_float32/v1",
"data_ref": "observation/depth.mkv",
"axes": ["T", "height", "width"],
"valid_ref": "observation/depth_valid.mkv",
"valid_axes": ["T", "height", "width"],
"unit": "m",
"depth_type": "z",
"depth_origin": "measured",
"invalid_value": "NaN",
"storage": {
"profile": "mkv/depth_float32_bits/v1",
"codec": "ffv1",
"pixel_format": "gray16le",
"encoded_size": [1280, 480],
"source_lossy": false,
"decoder": {"name": "ffmpeg", "version": "填写实际版本"},
"encoder_parameters": {"name": "ffv1", "level": 3, "version": "填写实际版本"}
},
"valid_storage": {
"profile": "mkv/bool_ffv1/v1",
"codec": "ffv1",
"pixel_format": "gray",
"encoded_size": [640, 480],
"source_lossy": false,
"decoder": {"name": "ffmpeg", "version": "填写实际版本"},
"encoder_parameters": {"name": "ffv1", "version": "填写实际版本"}
},
"provenance": {"kind": "format_conversion", "method": "源深度转米制 z float32;逐位打包为 FFV1"},
"source_locator": {"file": "raw/data/depth.zip", "member": "depth/0001.png"}
}
```
深度和有效性视频都必须逐帧解码验收:float32 位串相同、bool 相同、T 相同,并检查 valid=true 的正有限值和 valid=false 的 NaN。读取器必须按 profile 还原,不能把 depth.mkv 的编码像素直接当深度值。
## 4. camera 相机、帧索引与标定
### 4.1 frames.jsonl:索引、时间与对应关系
`camera/frames.jsonl` 每行对应统一帧号 `frame_index=0..T-1`,是所有组件的唯一行索引。至少包含 `frame_index`、`timestamp_ns`、`clock_domain`、`source_locator`;原始帧号/文件名保存在 `source_frame_id`,不能被新帧号替代。每行还可有 `annotation_matches`,按组件键保存 `source_frame_id`、`source_timestamp_ns`、`clock_domain`、`match_method` 和 `delta_ns`;方法为 exact/index_map/nearest/interpolated,索引映射无时间依据时 delta_ns=null。nearest 必须记录允许误差;interpolated 必须记录两端源标识和权重。delta_ns 仅在同一时间域中计算为源标注时间减图像时间。多相机共享 `sequence_id`;已知同步关系必须用 `sync_id` 或明确的源帧/时间映射表达,不能仅凭相同数组索引认定同步。
每个视图必须提供此文件。源时间使用整数纳秒及 `clock_domain`,未知写 JSON `null`;不同时间域不能直接比较。逐帧 split 可以覆盖 metainfo 的视图默认划分,并保留来源,见 2.4。
### 4.2 坐标系与标定通则
| 项目 | 统一约定 |
|---|---|
| 相机坐标 | 右手系,X 向右、Y 向下、Z 向前,长度单位米 |
| 齐次变换 | 列向量,`p_target = T_target_from_source @ p_source` |
| 图像坐标 | `(u,v)`;左上像素中心为 `(0,0)`,u 向右、v 向下,单位 pixel |
| 固定标定 | 本版展开为 T 份,同一 schema 不混用静态与动态形状 |
| 分辨率或模型变化 | 分开存储为视图/片段,不在同一组件中混装 |
| 未知标定 | 相机内外参允许缺省,不填单位阵冒充已知标定 |
### 4.3 intrinsic.pt 与畸变参数
| model / schema_id | intrinsic.pt 的固定结构 |
|---|---|
| pinhole / camera/pinhole/v1 | `[T,3,3]`,标准 K,最后一行为 `[0,0,1]`;限无畸变或已校正图像 |
| fisheye624 / camera/fisheye624/v1 | `[T,15]`,`[f,cx,cy,k0,k1,k2,k3,k4,k5,p0,p1,s0,s1,s2,s3]`,采用 Project Aria Fisheye624 投影定义 |
| opencv_fisheye4 / camera/opencv_fisheye4/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件 `distortion_ref` 指向 `[T,4]`,顺序 `[k1,k2,k3,k4]`,使用 OpenCV fisheye 等距角度多项式;已由 ReInterHand 实际原始相机参数验证 |
| rational8 / camera/rational8/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件必需 `distortion_ref` 指向 `[T,8]`,顺序 `[k1,k2,p1,p2,k3,k4,k5,k6]` |
| unknown / null | 不提供可用 intrinsic,不声称可以投影 |
有畸变的其他模型必须注册新 schema,固定参数名、顺序和投影公式;不能塞进针孔 K 后遗失畸变项。`metainfo.camera.schema_id` 必须与 intrinsic 组件一致。同一模型的别名不可隐式改变参数布局。
`opencv_fisheye4`:对前方点令 `x=X/Z, y=Y/Z, r=sqrt(x²+y²), theta=atan(r)`,`theta_d=theta*(1+k1*theta²+k2*theta⁴+k3*theta⁶+k4*theta⁸)`;`u=fx*x*theta_d/r+cx, v=fy*y*theta_d/r+cy`。光轴 r=0 时使用连续极限 `theta_d/r=1`。四系数不能按普通径向畸变解释,也不能补零冒充 Fisheye624。
rational8 对归一化坐标 x=X/Z、y=Y/Z,令 r²=x²+y²,径向项为 `(1+k1*r²+k2*r⁴+k3*r⁶)/(1+k4*r²+k5*r⁴+k6*r⁶)`;再加 p1/p2 切向项并经 K 得到像素。`distortion_ref` 与 intrinsic 共用 `[T]` valid,保存到 camera/distortion.pt。不得把这种畸变三维坐标当作真实相机系 xyz 保存。
内参有效性为 `intrinsic_valid.pt [T] bool`;有畸变时使用对应 `distortion_ref`。同一模型的参数名和顺序固定。
### 4.4 extrinsic.pt 与 extrinsic_valid.pt
`extrinsic.pt` 为 `[T,4,4]`,schema `transform/se3/v1`,方向固定 `T_camera_from_world`,有效性 `[T]`。世界坐标含义及源坐标转换记录在 provenance 中;只有相机坐标标注不要求虚构世界坐标。旋转块须正交且 determinant≈1。
## 5. annotation 标注数据
### 5.1 标注通则:手槽、valid 与 visibility
手槽固定为 0=left、1=right,指解剖学左右,不按画面位置或可见性重排。本阶段只处理左右手两槽,不处理更多手。实体引用使用 `hand_left`、`hand_right`;手槽不证明跨采集片段的个人身份。
#### 5.1.1 valid:标注是否可用于监督
标注的 `valid=true` 表示:有对应实际标注、通过本 schema 数值检查,且通过来源明确提供并适用于该组件的有效性/QA 条件。`valid=false` 可由缺标注、无法建立帧对应、源无效占位或官方 QA 不通过导致;不等于画面没有手或手不可见。各组件独立判断,MANO 按 `[T,2]` 标记左右手,关键点按 `[T,2,K]` 标记。
**2026-09-20 将标注 valid 从“仅表示存在”修订为“可用于监督”,字段形状不变。** 公式为 `source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass`。没有官方 QA 时省略最后一项,不伪造 QA;不能把未知当成已通过已存在的 QA。适配器在组件 `valid_policy` 中记录具体规则、来源、聚合/广播作用域。缺失官方必需 QA 的记录须明确处理为未知或暂停验收,不能静默通过。无效浮点项仍填 NaN,原始数据保留在 raw;被排除原值可用于 doc 中明确标识的诊断渲染,不能冒充 shared 有效监督。
本地筛选须依据明确的规则,并在 `valid_policy.local_excluded_frame_indices`、排除原因和正式报告中记录。单个可疑投影作为问题记录,不直接硬编码排除该帧。已确认的曝光异常须明确作用范围,不能把一个序列的“前两帧有问题”套到所有序列。RGB 编码完好与几何监督可用是两件事,允许保留原图及帧索引而屏蔽对应标注;未发现问题不等于完成全部人工审核,试点待确认时不能作为已验收发布使用。
源字段必须按官方语义映射,不能直接按名字复制:
| 来源 | 官方含义 | 映射原则 |
|---|---|---|
| [H2O](https://github.com/taeinkwon/h2odataset) 的手标注首位 | 0 未标注、1 已标注 | 可作为对应手标注存在性的依据,不推断未标注原因 |
| [HOT3D](https://github.com/facebookresearch/hot3d#using-mask-files) 的 pose_available、visible、mask_qa_pass | 分别表达姿态存在、可见性、对画面中可见手物位姿的人工 QA | 逐手/物体记录决定存在性,再 AND 当前相机当前帧 QA;QA 是整帧聚合判定,保守排除该帧全部手物几何监督,不声称每个实体均有错误;源可见性基于位姿推导时,其自身 valid 同样受 QA 约束 || [Dex-YCB](https://github.com/NVlabs/dex-ycb-toolkit#loading-dataset-and-visualizing-samples) 的全零 pose_m、全 -1 joints | 不可见的手或缺标注共用占位表示 | 对应组件 valid=false;不能从该值判定 visibility=false,也不能声称原因是动捕缺失 |
| [ARCTIC](https://github.com/zc-alexfan/arctic/blob/master/docs/data/data_doc.md) 的 is_valid/left_valid/right_valid | 是否有效用于官方评估 | 核实每项筛选依据;不把可见性/评估选择直接等同 QA。本次原始 mano.npy 不含这些派生评估标记,按原记录与数值检查生成 valid,并声明没有额外官方 QA 输入 |
源 valid=false 若代表评估筛选或其他条件,应检查实际标注和源约定后映射;不能一律清空坐标。反之,占位零或 -1 只有在源官方明确规定时才判为缺失,不泛化成所有数据的判断规则。
`valid=true` 的标注应通过其 schema 的数值与形状检查;检查失败必须报告或修复,不能静默隐藏。QA 不通过应报告排除数量与原因,并保留可追溯信息;不能把这类无效称为缺标注。RGB、深度等观测有效性仍按各自 schema;手物 QA 不自动否定 RGB、静态相机内参或物体资产。相机外参是否过滤须依据其自身来源规则;HOT3D 本次保留源外参用于溯源和诊断,不能用其存在性证明 QA 失败帧的几何监督正确。
#### 5.1.2 visibility:可见性属性
附加质量属性只保留 `visibility`,存放在对应模态或标注集内,不设 quality 目录。同一份可见性仅存一次;uv 与 xyz 共用时引用同一个文件。
visibility 通过所属组件 attributes 登记 data_ref、axes、dtype、visibility_type、meaning、provenance、source_locator;未知值通过属性 valid_ref 标识,全已知可声明 valid=true。比例与布尔值不相互强转,也不按任意阈值二值化。没有 MANO 时,整手可见性挂在 keypoints 组件,使用独立的 whole_hand_visibility.pt,明确 meaning=whole_hand,不与逐关键点可见性混用。
`valid` 回答“这项标注能否用于监督”,`visibility` 回答“在当前图像中是否可见(或可见多少)”。不可见的手或关键点仍可有有效标注;不能因 visibility=0 就清空坐标。源没有 visibility 时缺省或标为未知,不由 valid 推断。
| 情况 | 手标注 valid | visibility |
|---|---|---|
| RGB 已开始录制,动捕尚未开始,没有其他对应手标注 | false | 以独立源可见性标注为准;没有则未知 |
| 手被遮挡,但源有标注且通过适用有效性检查 | true | 若源声明不可见,则 false 或源可见比例 || 手可见且有对应标注,通过适用 QA | true | 若源有此信息,则 true 或源可见比例 || 手可见,但该帧漏标或动捕中断 | false | 可以为 true,但必须有独立来源依据 || 有手部参数,但官方 QA 明确不通过 | false | 不据此断言不可见;源可见比例若基于不可靠位姿,其属性 valid 也为 false |
visibility 自己的 valid_ref 表示该可见性标注是否可用,不复用 MANO 或关键点坐标的 valid_ref;明确记录源存在性及适用的 QA 条件。上述例子不要求凭图像自动生成可见性。
不设 quality 组件或目录,不另存拟合误差、曝光、截断比例等通用质量数组。适用的官方 QA 合并进对应 valid,在 `valid_policy` 记录来源与规则;正式校验报告保留原始 QA 时间区间及排除统计。原始 QA 文件仍在 raw,官方 split 保留。
### 5.2 mano:参数与整手可见性
MANO schema `mano/axis_angle61/v1`:`motion.pt [T,2,61]`,顺序为完整 16 关节 axis-angle 48、shape betas 10、全局平移 3。姿态使用弧度,平移米,位于当前相机系。有效性 `[T,2]`;缺少一侧整槽 NaN。PCA 必须先按对应模型展开,不能将 PCA 系数直接填入 axis-angle。
`model_profile` 必须固定 MANO 版本、`flat_hand_mean=true`、左手 shapedirs 修正状态。平移表示模型输出顶点所加的全局平移,不是某个腕关节的坐标;源语义不同须转换。shape 无量纲。模型权重不作为共享数据附带上传。
`mano/visibility.pt [T,2]` 保存源整手可见比例时使用 float32 [0,1],`visibility_type=ratio`;只有实际采用 0–100 的百分比才除以100,不能只凭表头判断。HOT3D 的 `visibility_ratio[%]` 实值已经是0–1,官方读取器原样读取,必须保留原值。通过 MANO 组件 attributes 登记,使用独立有效性,不复用 motion_valid。
手部共享表示仅保留 MANO 参数与选定关键点,不发布独立手表面几何。需要渲染或接触计算时由 MANO 参数生成,几何引用使用固定 MANO 模型配置与顶点顺序;不影响 object 下的物体模型和材质资产。
### 5.3 keypoints:二维点、三维点与逐点可见性
关键点独立于 MANO 参数存在;没有 motion 也可有关键点。`uv.pt [T,2,K,2]` 与 `xyz.pt [T,2,K,3]`,有效性 `[T,2,K]`,分别采用 `keypoints/uv/v1` 和 `keypoints/xyz/v1`。K 由 `keypoint_schema` 固定,不能在同一数组中逐帧变化;同体系统一顺序。数值使用像素坐标或米制相机系。
| keypoint_schema | K 与固定索引 |
|---|---|
| mano21/v1 | 21;wrist 后依次 thumb/index/middle/ring/little,每指由近端至指尖 |
| rhd21/v1 | 21;保持 wrist,然后五指由近端至指尖;原始每指 tip→palm 反序。只统一顺序,不宣称解剖学位置等价于 MANO |
具体名称与源索引映射见 `schema.json`。当前只登记 MANO21 与 RHD21;不登记 MediaPipe、ReInterHand capture21 或 fit24 中间关键点。
每个发布中的每个视图只提供一套标准手关键点,直接放在 keypoints 下,不设 annotation_set_id 字段或目录。uv 与 xyz 是这套关键点的二维与三维表示,不是两套标注。provenance 分别记录二者来自原始标注还是计算结果;不要求已有 2D 必须由当前 xyz 重新投影覆盖。
ReInterHand 的 Original keypoints���Original fits keypoints 及带前臂关键点不纳入 shared;如需手关键点,从选定 MANO 参数生成 MANO21 并记录模型/指尖回归约定。其他数据集默认使用选定的官方关键点,不额外生成平行的 MANO 派生集合。后续主动更换生成方法或结果时发布新的 dataset_version,不在同一版本内增设方法分支。
manual/projection/fitting 只记录在 provenance,不作为目录或类型分支。不得通过坐标为零、是否出画或 visibility 判断标注是否存在。派生标注仅在实际生成并通过数值检查后声明 valid=true;没有生成的项为 false,不伪造坐标。
`keypoints/visibility.pt [T,2,K]` 保存源逐点可见性,布尔表示使用 `visibility_type=boolean`。uv 与 xyz 共用时引用同一份文件。整手比例属性没有 MANO 可挂载时使用 `whole_hand_visibility.pt [T,2]`,`meaning=whole_hand`;它与逐点可见性分开,通用登记规则见 5.1。
不使用 annotation_set_id;ReInterHand 中间关键点集合不进入 shared,raw 保留来源文件。
### 5.4 object:身份、资产、位姿与几何
#### 5.4.1 metainfo.json:物体身份与跟踪作用域
手用 `hand_left`、`hand_right` 及槽位 0、1 表示,不再另存 entities.json。物体身份登记在 `annotation/object/<object_id>/metainfo.json`,必填 `object_id`、`identity_scope`、`scope_id`、`source_locator`;可含 `category_id`、`source_object_id`、`mesh_ref`、`has_model`、部件引用。即使只有分割、没有 pose/mesh,也可只有这份物体元信息。
`identity_scope` 为 frame/subsequence/sequence,`scope_id` 指定具体作用域;跨相机共享身份只在已有源对应证据时使用。VISOR 按官方 subsequence 与实体名关联时记录 `association_basis=official_subsequence_entity_name`,不能声称这是全视频物理实例跟踪。无需与 object_id 一一对应的标准 track_id;官方独立轨迹标识存在时保留为 source_track_id,并声明作用域。手槽不证明跨采集片段的个人身份。
#### 5.4.2 assets:网格、材质与纹理
资产属于物体,统一存放在 `annotation/object/<object_id>/` 内,可用 `assets/` 子目录组织网格、材质、纹理和部件资产。序列层不设共享 assets。所有引用采用视图根目录为基准;其中物体资产组件的 `data_ref` 与部件的 `mesh_ref` 采用相对于当前视图目录的 POSIX 路径,例如 `annotation/object/cup_01/assets/cup.obj`,且必须指向所属物体目录内的资产。OBJ 内部的材质、纹理引用遵循文件格式自身的相对路径规则,依赖文件一并保留。不同相机视图允许各自保存物体资产,不要求跨视图去重;下载物体时包含其资产依赖。
网格 schema 为 `mesh/obj/v1`,顶点米制,静态有效性可直接声明标量 `valid`,或通过 `valid_ref` 指向标量 bool Tensor;不按 T 重复静态资产。由物体/部件通过引用关联,不仅凭文件名猜测。
#### 5.4.3 pose.pt、pose_valid.pt 与 visibility.pt
刚体 schema 为 `object/rigid/v1`,`pose.pt [T,4,4]` 固定为 `T_camera_from_object`,平移米制,有效性 `[T]`。物体坐标原点、轴向必须与 mesh 一致;旋转块为正交矩阵且 determinant≈1。
`object/<id>/visibility.pt [T]` 保存源物体可见比例,float32 [0,1],`visibility_type=ratio`。通过所属物体组件 attributes 登记,独立表达其有效性。
#### 5.4.4 articulation.json、部件位姿与 joint_state.pt
关节物体:schema `object/articulated/v1`,`articulation.json` 登记 `parts` 与 `joints`。每个 part 有 `part_id`、`parent_id`(根为 null)、`has_model`、`mesh_ref`;has_model=false 时 mesh_ref=null,结构节点允许没有网格。父链不得成环。每个 joint 有唯一 `joint_id`、`parent_part`、`child_part`、`type`;fixed 单位 null、revolute 弧度、prismatic 米。有源限位时保存 `limits:[lower,upper]`;没有时 null,不伪造上下限。部件姿态统一为 `T_camera_from_part [T,4,4]`,不与父局部变换混装。
若提供 `joint_state.pt [T,J]`,必须登记固定 joint_order、轴在父部件系的表达、零位变换与正方向,valid 为 `[T,J]`;缺少这些运动学定义时只发布部件位姿与已有来源信息,不伪造可驱动的关节模型。关节值与部件位姿同时存在时需验证一致性。
部件层级应声明语义:纯语义包含树允许 `joints=[]`,不将包含关系推断为机械关节。关节状态 schema 为 `object/joint_state/v1`;转动用弧度、移动用米,混合类型按 joint_order 对应的关节定义解释。
#### 5.4.5 dimensions、几何关键点与顶点部件标签
`dimensions.pt [T,3]` 采用 `object/dimensions/v1`,有效性为 `[T]`。
物体/部件 `dimensions` 为 `[length,width,height]` 米,轴顺序与该 mesh 的局部坐标关联,登记 `dimensions_semantics` 和来源。HOI4D dimensions 与 mesh 的具体尺度关���未验证前标为 source_unspecified,保留源值并暂停依赖该关系的几何验收,不能默认为待施加缩放。需要施加缩放时明确 scale_applied_to_mesh,禁止重复应用。
源物体关键点放 `object/<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。每个发布选择一套源几何点并记录选择,不另建方法分支。
`vertex_part_ids.pt [V] int64` 绑定 `mesh_ref` 与 topology_id,登记整数到 part_id 的映射;未知用 -1。ARCTIC 不同拓扑的资产分别绑定,不能共用未经转换的顶点标签。部件层级中 is_instance/has_model 等源属性保留,几何文件仍全部归 object。
### 5.5 segment:分割类别、编码与覆盖范围
每个发布选择一套任务使用的分割表示,不建立方法/标注集分支。没有分割就不创建 segment 目录,不为其他模态创建空的实体表。
| schema_id | 文件与数值语义 |
|---|---|
| segment/uint16_labels/v1 | mask.mkv;整数区域编号,通过 instances.jsonl 解释 |
| segment/instance_polygons/v1 | polygons.jsonl;实例多边形,可重叠;当前不支持孔洞拓扑 |
| segment/foreground_intensity/v1 | mask.mkv;0–255 前景强度,不是区域编号或经过校准的概率 |
#### 5.5.1 uint16 标签图与 instances.jsonl
组件声明 `segmentation_type=semantic/instance/part`;同一组件固定一种类型。`mask.mkv` 解码为 `[T,H,W] uint16`,schema `segment/uint16_labels/v1`,使用 `mkv/uint16_ffv1/v1`,FFV1 gray16le 无损;只有所有区域编码均 ≤255 时允许 gray8(pixel_format=gray),读取后转 uint16,数值不变。禁止调色板和有损编码。有效性 `[T]`,表示该帧有可用分割标注。数值 0 固定为 unassigned,65535 固定为 ignore,1–65534 为区域编码,不能直接等同 entity_id。
`instances.jsonl` 每帧一行,包含 `frame_index` 与 `labels`。每条标签包含 `mask_value`、`category_id`、`entity_id`、`part_id`;无意义或未知字段为 null。semantic 允许 entity_id=null;instance 必须引用 hand_left/hand_right 或登记的 object_id;part 还须关联登记部件。源实例 ID 和其他属性分别保存在 `source_instance_id`、`source_attributes`。mask 中每个非保留编码必须有且仅有一个映射。
FreiHAND 的试点按本任务需要,统一到手/背景类别,保留每个原生区域编码;不要求给原生细分区域猜测手指名称。需要细部件监督时,尚未核实的部件名称必须保持未知,不能因粗粒度手类别已核实便声称部件语义也已统一。
#### 5.5.2 重叠实例多边形
每发布选择一套任务使用的分割表示,不建立方法/标注集分支。VISOR 的实际试点存在重叠实例多边形,单层标签图不能无损表达。对此补充 `segment/instance_polygons/v1`:`segment/polygons.jsonl` 每帧包含 `frame_index` 和 `instances`,每实例包含 `mask_value` 与 `polygons`(列表,每个多边形为源图像像素坐标顶点序列,保留原始精度)。身份和类别仍由同一 `instances.jsonl` 映射,有效性仍为 `[T]`,通过 schema 区分物理编码。允许多实例重叠,不采用后画覆盖前画。消费者按需栅格化为独立实例二值 mask;不能声称合并的单层 mask 无损。
#### 5.5.3 灰度前景强度
ReInterHand 的官方渲染 mask 为双手合并的灰度前景掩码,实测存在 0–255 的中间值,不是左右手实例编号。登记 `segment/foreground_intensity/v1`:仍存 `segment/mask.mkv`,解码为 `[T,H,W] uint16`,使用 `mkv/uint16_ffv1/v1`,此类数据优先编码为 FFV1 gray8(pixel_format=gray),读取后转 uint16。有效值范围 0–255,归一化值为 `float32(value)/255`;0 为背景端点、255 为前景端点。组件声明 `foreground_category=hand`、`entity_id=null` 和双手合并语义,不使用区域编号映射。这里保留原始渲染 mask 强度,不把它称为经过校准的概率。若任务需要二值 mask,阈值化属于任务层派生操作,记录阈值;共享层不丢弃中间灰度。不同 schema 的数值含义不同,不能将该文件按整数类别图解码。
FreiHAND 训练集的 JPEG mask 使用 `segment/foreground_intensity/v1`,逐像素保留 JPEG 解码后的灰度,`entity_id=hand_right`。该 schema 不限定双手合并:单手或合并范围由 `entity_id` 与 `coverage` 明确声明。评估集整数区域图仍用 `segment/uint16_labels/v1`,两者不能仅凭文件名使用同一种解码语义。
#### 5.5.4 coverage 与有效性
`coverage.kind=full/selected_entities/partial/unknown`。full 指声明���标注范围完整;selected_entities 还应列出目标范围。无论哪种,0 本身不自动成为背景;背景要有明确类别映射,未标注区域不能用于构造负样本。保留源逐类/逐实例 exhaustive 信息,未知不可改写为完整。
三种表示的帧级有效性均为 `[T]`,表示该帧是否提供此分割标注;对应 valid_ref 在组件中登记,仍用小型 bool `.pt` 数组。栅格 mask 必须登记 storage,格式见 3.1.2,所有帧的整数编码或强度逐值完全相同。编码语义由 schema_id 决定,读取器不能仅依据 mask.mkv 文件名选择解码方式。
### 5.6 contact:接触、抓取、区域与距离
#### 5.6.1 relations.jsonl 与 relations_valid.pt
`annotation/contact/relations.jsonl`,schema contact/relations/v1,每帧一行含 frame_index、relations。每条记录含 relation_type(contact/grasp)、subject_id(手槽或登记实体)、object_id、status、source_locator、provenance。status 固定为 positive/negative/unknown/target_unannotated:positive 必须有可解析目标,negative 表示源明确否定该关系,unknown 为不确定,target_unannotated 为确有接触但目标未标注。非 positive 的 object_id 可 null,不能用 null 冒充“不接触”。稀疏源无记录的帧不自动补 negative。
VISOR 的对象 mask ID 必须先按同帧 source_instance_id 解析成 object_id;hand-not-in-contact、none-of-the-above、inconclusive 分别映射 negative、target_unannotated、unknown,保留原始字符串。Dex ycb_grasp_ind 通过 ycb_ids 映射到登记物体,以 relation_type=grasp 保存;不得当作逐顶点接触。
relations 组件的 valid_ref 指向 `relations_valid.pt [T] bool`,表示该帧是否有可用源关系标注。有效帧中可以存在 status=unknown 的明确不确定标注;无源标注的帧为 valid=false、relations=[]。组件仍声明 available/provenance/source_locator。
#### 5.6.2 实体对的顶点区域与距离
已发布的接触区域/距离按参与关系的 subject_id 与 object_id 组织,每对实体保留选定的一套结果,以精确 geometry_ref/topology_id 关联到手或物体/部件;不要求每套数据都有。顶点区域 schema contact/vertex_region/v1:bool `[T,V]` 加同形 valid;顶点距离 schema contact/vertex_distance/v1:float32 `[T,V]`、米、同形 valid,声明 source/target geometry_ref、distance_definition(signed/unsigned、测量到点集或表面等明确源定义)。geometry_ref 必须指向已登记 mesh 或由固定 MANO 模型配置确定的拓扑;拓扑/顶点数变化时按拓扑拆分片段。其他源区域表示只有在实际接入并登记 schema 后才可转换,不能随意栅格化宣称等价。
顶点区域/距离已有存储定义,但尚未完成真实输入试点;接入时必须提供源语义与几何验收证据,不因已经登记 schema 就视为通过。
## 附录:任务范围
不强制收录 2D bbox、完整高频动捕、动作程序、身体 SMPL-X、点云或网络特征。范围内的接触、visibility、选定手关键点、物体几何不能因不便处理而静默丢弃。分割采用的物理编码由第 5.5 节决定,存在重叠时不能以单层标签图声称无损。
不设置 entities_ref/segment/entities.json,不要求与 object_id 重复的 track_id。MediaPipe 不在当前关键点定义中;旧版本迁移必须保留可追溯关系,不能直接删表。手部共享表示不含独立 hand_mesh。
schema.json 是普通注册表,不是 JSON Schema 文档或可执行验收器;定义存在不代表真实数据已验证。验收须保留实测范围与未决项。
本存储约定只更新标准,不代表既有 FFV1/depth.pt 试点已迁移。新发布必须显式写 storage 配置;旧产物按其旧定义读取,不能只改文件后缀或版本标识伪装为合规。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# H2O raw → shared-v1.0
## 范围与来源
本版本仅转换 `raw/data/subject{1,2,3,4}_v1_1.tar.gz` 的真实五视角 (`cam0`–`cam4`) 序列;`h2o_CASA.tar` 是单独的扩展,不与标准序列混合。每个原始序列存于 `data/subjectN_<scene>_<sequence>/cam{0..4}/`。源压缩包保持不变,不合成源不存在的标注。输出仅在本地制作;完整序列试点及人工检查通过、更新全量预估之前,不启动全量。
| 源包/字段 | shared 文件/处理 || --- | --- || `subjectN_v1_1.tar.gz`: `camX/rgb/<frame>.png` | `observation/rgb.mkv`:逐帧源 RGB 解码为 RGB24,FFV1 直接编码;输出**每帧**解码与源 RGB 字节摘要完全一致。`rgb_valid.pt` 记录存在性,源帧号和每组件的包成员及 SHA256 写入 `camera/frames.jsonl`。不再额外编码未采用的 H.264 RGB 候选;FFV1 编码器进程失败时才尝试 H.264。 || 同包 `camX/depth/<frame>.png` | `observation/depth.mkv` 和 `depth_valid.mkv`;按源毫米单位除以 1000 转米,保留无效深度与全帧时间轴,深度位串以 FFV1 保真封装并逐帧校验。既不做 3 米裁剪也不造出缺失的深度。 || `camX/cam_intrinsics.txt`、`camX/cam_pose/<frame>.txt` | `camera/intrinsic.pt`、`extrinsic.pt`:保留源内参;逐帧源 `T_world_from_camera` 求逆后存 `T_camera_from_world`;声明变换约定与有效性。 || `camX/hand_pose_mano/<frame>.txt` | `annotation/mano/motion.pt`、`motion_valid.pt`:源左/右手标志各自判断有效性;姿态与平移保持源数值,声明 MANO 模型配置,缺模型则明确标依赖缺失,不伪造网格或掩码。 || `camX/hand_pose/<frame>.txt` | `annotation/keypoints/xyz.pt`、`xyz_valid.pt`:源双手 21 点,相机坐标系米制,与 MANO 有效性彼此独立。HTML 中的投影仅用于人工预览,不写回训练数据。 || `camX/obj_pose/<frame>.txt`、`obj_pose_rt/<frame>.txt` | `annotation/object/<name>/keypoints/xyz.pt`、`pose.pt`:按源类号关联 21 个物体点及物体→相机位姿;仅源存在时登记组件及有效性。 || `object.zip` | `annotation/object/<name>/assets/` 与源 OBJ、MTL、纹理;静态形状预览不等于所有帧网格位姿的投影证明。 || `label_split.zip` 的 `action_{train,val,test}.txt` | 序列元数据的官方划分及来源;未知映射明确记 `unknown`,不自行编排。 |
`cam4` 是 ego,`cam0`–`cam3` 是 exo。真实时间/FPS 缺乏可靠来源时使用 null,不把 MKV 封装帧率冒充采集时钟。源 `action_label`、`verb_label`、pose 任务帧列表和 `manolabel_v1.1.tar.gz` 保留在 raw;当前契约没有相应动作组件,本发布不宣称它们已转换。源没有像素分割,本版本不投影网格生成替代分割。
## 源资产文件名修复
源 `object/cocoa/cocoa.obj` 引用 `ovomaltine.mtl`,材质内写的是 `map_Kd cocoa.png`,但原 ZIP 只提供 `ovomaltine.png`。仅在临时解压目录为该已确认的纹理增加**字节相同**的 `cocoa.png` 别名,保留原 PNG、OBJ、MTL 不变;在网格 `source_locator.texture_aliases` 中记录别名、原始包成员和 SHA256。别名与已保留的旧 cocoa 资产一致,不替换图像、标注或网格。全部八类物体的材质依赖在读取大 subject 包之前预检,其他缺失/越界依赖仍报错。
## 加速与验收
四个互不依赖的 subject 压缩包可由 `--workers 1..4` 并行顺序读取,各 worker 一次只处理一个序列。数值库保持单线程;FFV1 编码支持 `--codec-threads 1|2|4|8|10`,当前全量按用户要求使用 10;`--decode-threads 10` 通过现有 `HAND_WAREHOUSE_FFMPEG_THREADS` 控制源 RGB PNG→RGB24、完整视频解码摘要、深度/有效性语义校验与 RGB 索引抽取的解码线程,完整校验仍保留。深度 PNG 使用 `--depth-threads 4` 有序分批读取,每批最多读取 4 帧,避免缓存整条序列,缺帧仍按原时间轴写 NaN;不并行改写姿态、标注或原始包。并发数由相同输入实测吞吐量决定,记录 OS 线程峰值和磁盘占用,不以 CPU 线程数本身作为提速证据。RGB 源为 PNG,不适用 ARCTIC/HOT3D 的 JPEG 包直封和 16 帧抽查:RGB、深度、有效性与数值模态仍逐帧精确校验。临时文件在 `/data` 上隔离放置,历史 62 条目录不复用、不覆盖;调整并发时,在新的运行目录复用本次全量已经原子发布的完整序列,并从源重新核对帧号及逐组件 SHA256;已发布视图只读源包并核对摘要,不再把源 PNG/标注写入临时目录,待转换视图才正常暂存。未完成的临时序列不复用,原运行的脚本、配置及 QC 保留用于溯源。
先运行不截帧的代表性完整序列试点,保存自动 QC、真实耗时和 `doc/validation/index.html`(RGB、深度、源 3D 关键点投影、原生物体网格和全组件数值/有效性)。试点由人工核查之后再决定全量;全量后再次抽样人工核查。报告须区分数据完整性、源未提供的模态与仅供人工判断的几何对齐。
2026-09-29 完整序列试点已获人工确认,用户已授权本地全量。2026-09-30 用户取消 CPU 使用量上限,指定 4 个独立压缩包 worker、每个 FFV1 编码器 10 线程、每个校验解码器 10 线程、每 worker 深度 PNG 读取 4 线程;Python worker、读取及校验子进程不计入这最多 40 个编码线程,因此总线程数不固定为 40。该配置不代表已证明加速倍数。源包和旧产物保留;代码变化使用独立运行目录,已完成序列保留原始构建记录及生产脚本快照。
## 多线程解码测速(2026-09-30)
在 101 上以真实 `subject4/h1/0/cam0` 的完整 RGB、深度和有效性视频,以及源头 100 帧 PNG 测试;采用 1、10、10、1 的解码线程顺序,源深度 PNG 另比较 1/2/4 线程。逐字节摘要和输出长度必须相同,测速脚本、全部轮次及结果保存在 `script/provenance/operations/` 和 `doc/validation/`。测速期间旧全量任务仍运行,磁盘负载和缓存会影响结果;不得将阶段加速比冒充整套转换加速比。四个 gzip 包已经独立并行读取,暂不引入多进程重构或增加数值库线程;小矩阵及标注处理没有已测得的进一步并行收益。
本次同输入结果(解码后长度和 SHA256 全部相同):
| 阶段 | 1 线程(秒) | 新配置(秒) | 范围 || --- | ---: | ---: | --- || FFV1 RGB 解码与摘要 | 39.46 | 8.70(10 线程) | 完整 501 帧,中位数 || FFV1 深度位串解码与摘要 | 34.91 | 11.56(10 线程) | 完整 501 帧,中位数 || 有效性视频解码与摘要 | 2.24 | 2.27(10 线程) | 完整 501 帧;未获提速 || 源 RGB PNG 解码 | 2.67 | 1.49(10 线程) | 100 帧,1 线程使用热缓存轮次,不使用冷缓存较慢轮次来夸大提速 || 源深度 PNG 读取及毫米→米 | 4.67 | 2.61(4 线程) | 100 帧,中位数;帧序与数值相同 |
这些结果只代表相应阶段;全流程还包括顺序 gzip 扫描、文件创建、源 SHA256、资产复制和磁盘读写,实际全量 ETA 待稳定吞吐后再更新。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869{
"schema_version": "hand-warehouse/1.0", "validity_revision": "usable-annotation-2026-09-20", "annotation_validity": { "meaning": "annotation usable for supervision, not merely record presence", "formula": "source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass AND NOT explicitly_reviewed_local_exclusion", "without_official_qa": "omit QA term; declare source rules; do not fabricate QA", "policy_field": "components.<name>.valid_policy", "visibility_is_independent": true, "invalid_float_value": "NaN", "hot3d": "broadcast per-camera frame manual QA conservatively to hand/object labels and pose-derived visibility; retain RGB and source calibration; keep native QA in raw and review report", "hot3d_visibility": "native visibility_ratio[%] already ranges from 0 to 1; do not divide by 100" }, "hand_slots": [
"left",
"right"
],
"keypoints": {
"mano21/v1": {
"count": 21,
"names": [
"wrist",
"thumb_1",
"thumb_2",
"thumb_3",
"thumb_4",
"index_1",
"index_2",
"index_3",
"index_4",
"middle_1",
"middle_2",
"middle_3",
"middle_4",
"ring_1",
"ring_2",
"ring_3",
"ring_4",
"little_1",
"little_2",
"little_3",
"little_4"
],
"source_index_map": null,
"note": "adapter maps official MANO joint and fingertip convention"
},
"rhd21/v1": {
"count": 21,
"names": [
"wrist",
"thumb_1",
"thumb_2",
"thumb_3",
"thumb_4",
"index_1",
"index_2",
"index_3",
"index_4",
"middle_1",
"middle_2",
"middle_3",
"middle_4",
"ring_1",
"ring_2",
"ring_3",
"ring_4",
"little_1",
"little_2",
"little_3",
"little_4"
],
"source_index_map_per_hand": [
0,
4,
3,
2,
1,
8,
7,
6,
5,
12,
11,
10,
9,
16,
15,
14,
13,
20,
19,
18,
17
]
}
},
"camera": {
"opencv_fisheye4": {
"K": [
3,
3
],
"distortion": [
"k1",
"k2",
"k3",
"k4"
],
"projection": "theta=atan(r); theta_d=theta*(1+k1*theta^2+k2*theta^4+k3*theta^6+k4*theta^8); source ReInterHand"
},
"pinhole": {
"K": [
3,
3
]
},
"fisheye624": {
"parameters": [
"f",
"cx",
"cy",
"k0",
"k1",
"k2",
"k3",
"k4",
"k5",
"p0",
"p1",
"s0",
"s1",
"s2",
"s3"
]
},
"rational8": {
"K": [
3,
3
],
"distortion": [
"k1",
"k2",
"p1",
"p2",
"k3",
"k4",
"k5",
"k6"
]
}
},
"segmentation": {
"segment/uint16_labels/v1": {
"storage": "mask.mkv",
"dtype": "uint16",
"mapping": "instances.jsonl",
"valid_shape": [
"T"
],
"required_metadata": [
"segmentation_type",
"coverage",
"mapping_ref",
"storage"
],
"shape": [
"T",
"H",
"W"
],
"reserved_codes": {
"0": "unassigned",
"65535": "ignore"
},
"region_codes": [
1,
65534
],
"allowed_storage_profiles": [
"mkv/uint16_ffv1/v1"
]
},
"segment/instance_polygons/v1": {
"storage": "polygons.jsonl",
"mapping": "instances.jsonl",
"frame_keys": [
"frame_index",
"instances"
],
"instance_keys": [
"mask_value",
"polygons"
],
"coordinate_unit": "pixel",
"overlap_allowed": true,
"valid_shape": [
"T"
],
"required_metadata": [
"segmentation_type",
"coverage",
"mapping_ref"
],
"polygon_shape": [
"N",
2
],
"holes_supported": false
},
"segment/foreground_intensity/v1": {
"storage": "mask.mkv",
"dtype": "uint16",
"value_range": [
0,
255
],
"normalization_scale": 0.00392156862745098,
"axes": [
"T",
"height",
"width"
],
"meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability",
"zero": "background",
"full_scale": "foreground",
"mapping": "foreground_category in component metadata",
"valid_shape": [
"T"
],
"required_metadata": [
"segmentation_type",
"coverage",
"value_range",
"normalization_scale",
"foreground_category",
"entity_id",
"storage"
],
"shape": [
"T",
"H",
"W"
],
"allowed_storage_profiles": [
"mkv/uint16_ffv1/v1"
]
}
},
"note": "Registry for hand-warehouse/1.0. Read CONTRACT.md for field semantics. This is not a JSON Schema document or executable validator.",
"components": {
"mano/axis_angle61/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
2,
61
],
"valid_shape": [
"T",
2
],
"unit": "m",
"angle_unit": "rad",
"coordinate_frame": "camera",
"layout": {
"pose_axis_angle": [
0,
48
],
"shape": [
48,
58
],
"translation": [
58,
61
]
}
},
"keypoints/uv/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
2,
21,
2
],
"valid_shape": [
"T",
2,
21
],
"unit": "pixel",
"required_metadata": [
"keypoint_schema"
]
},
"keypoints/xyz/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
2,
21,
3
],
"valid_shape": [
"T",
2,
21
],
"unit": "m",
"required_metadata": [
"keypoint_schema"
]
},
"depth/z_float32/v1": {
"storage": "mkv",
"dtype": "float32",
"shape": [
"T",
"H",
"W"
],
"valid_shape": [
"T",
"H",
"W"
],
"unit": "m",
"depth_type": "z",
"pixel_grid": "current_rgb",
"coordinate_frame": "current_rgb_camera",
"valid_storage": "mkv",
"allowed_storage_profiles": [
"mkv/depth_float32_bits/v1"
],
"allowed_valid_storage_profiles": [
"mkv/bool_ffv1/v1"
],
"required_metadata": [
"storage",
"valid_storage",
"depth_origin"
],
"depth_origin_values": [
"measured",
"rendered",
"unknown"
]
},
"transform/se3/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
4,
4
],
"valid_shape": [
"T"
],
"unit": "m",
"required_metadata": [
"convention"
]
},
"object/rigid/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
4,
4
],
"valid_shape": [
"T"
],
"unit": "m",
"required_metadata": [
"convention"
]
},
"camera/pinhole/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
3,
3
],
"valid_shape": [
"T"
]
},
"camera/rational8/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
3,
3
],
"valid_shape": [
"T"
]
},
"camera/opencv_fisheye4/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
3,
3
],
"valid_shape": [
"T"
]
},
"camera/fisheye624/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
15
],
"valid_shape": [
"T"
]
},
"camera/distortion8/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
8
],
"valid_shape": [
"T"
]
},
"camera/fisheye4_distortion/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
4
],
"valid_shape": [
"T"
]
},
"object/joint_state/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
"J"
],
"valid_shape": [
"T",
"J"
],
"required_metadata": [
"joint_order"
],
"unit_rule": "revolute radians; prismatic metres; mixed types declared per joint"
},
"object_keypoints/camera/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
"K",
3
],
"valid_shape": [
"T",
"K"
],
"unit": "m",
"coordinate_frame": "camera",
"required_metadata": [
"keypoint_schema"
]
},
"object/dimensions/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
3
],
"valid_shape": [
"T"
],
"unit": "m",
"required_metadata": [
"dimensions_semantics"
],
"axis_order": [
"length",
"width",
"height"
],
"scale_rule": "do not apply to mesh without source-supported size/scale relation"
},
"object_keypoints/template/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"K",
3
],
"valid_shape": [
"K"
],
"unit": "m",
"coordinate_frame": "object",
"static": true,
"required_metadata": [
"keypoint_schema"
]
},
"mesh/obj/v1": {
"storage": "obj",
"unit": "m",
"static": true,
"valid_shape": [],
"dependencies": "MTL and textures retained under owning object"
},
"rgb/uint8/v1": {
"storage": "mkv",
"dtype": "uint8",
"shape": [
"T",
"H",
"W",
3
],
"valid_shape": [
"T"
],
"color_order": "RGB",
"allowed_storage_profiles": [
"mkv/mjpeg_copy/v1",
"mkv/source_copy/v1",
"mkv/h264_rgb_lossless/v1",
"mkv/ffv1_rgb/v1"
],
"required_metadata": [
"storage"
]
},
"contact/relations/v1": {
"storage": "jsonl",
"valid_shape": [
"T"
],
"frame_keys": [
"frame_index",
"relations"
],
"absence_semantics": "no record is not a negative contact annotation"
},
"contact/vertex_region/v1": {
"storage": "pt",
"dtype": "bool",
"shape": [
"T",
"V"
],
"valid_shape": [
"T",
"V"
],
"required_metadata": [
"source_geometry_ref",
"target_geometry_ref",
"topology_id"
],
"pilot_status": "defined_not_empirically_validated"
},
"contact/vertex_distance/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
"V"
],
"valid_shape": [
"T",
"V"
],
"unit": "m",
"required_metadata": [
"source_geometry_ref",
"target_geometry_ref",
"topology_id",
"distance_definition"
],
"pilot_status": "defined_not_empirically_validated"
},
"object/articulated/v1": {
"storage": "json",
"required_keys": [
"parts",
"joints"
],
"part_keys": [
"part_id",
"parent_id",
"has_model",
"mesh_ref"
],
"hierarchy_semantics": "declare mechanical articulation or semantic containment; containment alone does not imply joints",
"acyclic": true
},
"segment/uint16_labels/v1": {
"storage": "mkv",
"dtype": "uint16",
"mapping": "instances.jsonl",
"valid_shape": [
"T"
],
"required_metadata": [
"segmentation_type",
"coverage",
"mapping_ref",
"storage"
],
"shape": [
"T",
"H",
"W"
],
"reserved_codes": {
"0": "unassigned",
"65535": "ignore"
},
"region_codes": [
1,
65534
],
"allowed_storage_profiles": [
"mkv/uint16_ffv1/v1"
]
},
"segment/instance_polygons/v1": {
"storage": "jsonl",
"mapping": "instances.jsonl",
"frame_keys": [
"frame_index",
"instances"
],
"instance_keys": [
"mask_value",
"polygons"
],
"coordinate_unit": "pixel",
"overlap_allowed": true,
"valid_shape": [
"T"
],
"required_metadata": [
"segmentation_type",
"coverage",
"mapping_ref"
],
"polygon_shape": [
"N",
2
],
"holes_supported": false
},
"segment/foreground_intensity/v1": {
"storage": "mkv",
"dtype": "uint16",
"value_range": [
0,
255
],
"normalization_scale": 0.00392156862745098,
"axes": [
"T",
"height",
"width"
],
"meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability",
"zero": "background",
"full_scale": "foreground",
"mapping": "foreground_category in component metadata",
"valid_shape": [
"T"
],
"required_metadata": [
"segmentation_type",
"coverage",
"value_range",
"normalization_scale",
"foreground_category",
"entity_id",
"storage"
],
"shape": [
"T",
"H",
"W"
],
"allowed_storage_profiles": [
"mkv/uint16_ffv1/v1"
]
}
},
"storage_revision": "lossless-video-2026-09-18",
"sampling": {
"image": {
"single": {
"T": 1
},
"independent": {
"T": ">=2",
"required_frame_fields": [
"sample_id",
"source_locator"
],
"temporal_relationship": false
},
"source_fps": null
},
"video": {
"sampling_types": [
"dense",
"sparse"
]
}
},
"storage_profiles": {
"mkv/mjpeg_copy/v1": {
"container": "matroska",
"codec": "mjpeg",
"method": "stream_copy_from_source_jpeg",
"logical_dtype": "uint8",
"decoded_pixel_format": "rgb24",
"validation": [ "source_jpeg_packet_sha256_exact", "all_packet_count_order_and_dimensions_exact", "deterministic_decoded_rgb_sample_exact", "pilot_and_final_selected_whole_sequences_decoded_rgb_exact" ], "validation_policy": { "id": "jpeg-packets-all-rgb-sample16/v1", "sample_count_per_view": 16, "short_views": "all_frames_if_T_less_than_16", "fixed_indices": "0,T-1,T//4,T//2,3*T//4, deduplicated", "remaining_indices": "sample without replacement to min(T,16) using Python random.Random(seed)", "seed": "first 8 bytes of SHA256(sequence_id/camera_id/20260920), big-endian integer", "report": "policy, exact selected frame indices, seed, separate packet and pixel coverage", "legacy_all_frame_pixel_proofs": "still accepted; preserve historical evidence" } },
"mkv/source_copy/v1": {
"container": "matroska",
"codec": "source_codec_declared_in_metadata",
"method": "stream_copy_only",
"logical_dtype": "uint8",
"decoded_pixel_format": "rgb24",
"validation": [
"no_reencoding",
"all_decoded_rgb_frames_exact",
"presentation_frame_order_exact"
]
},
"mkv/h264_rgb_lossless/v1": {
"container": "matroska",
"codec": "h264",
"encoder": "libx264rgb",
"crf": 0,
"decoded_pixel_format": "rgb24",
"logical_dtype": "uint8",
"gop": "declared_in_encoder_parameters",
"validation": [
"all_decoded_rgb_frames_exact"
],
"forbidden": [
"lossy_rate_control",
"rgb_to_yuv420_subsampling"
]
},
"mkv/ffv1_rgb/v1": {
"container": "matroska",
"codec": "ffv1",
"decoded_pixel_format": "rgb24",
"logical_dtype": "uint8",
"validation": [
"all_decoded_rgb_frames_exact"
]
},
"mkv/depth_float32_bits/v1": {
"container": "matroska",
"codec": "ffv1",
"pixel_format": "gray16le",
"logical_dtype": "float32",
"logical_shape": [
"T",
"H",
"W"
],
"encoded_shape": [
"T",
"H",
"2*W"
],
"packing": "IEEE754 little-endian float32 bits; low uint16 in first W columns, high uint16 in last W columns",
"decode": "reinterpret_float32(uint32(low) | (uint32(high) << 16))",
"validation": [
"all_float32_bits_exact_including_nan"
]
},
"mkv/bool_ffv1/v1": {
"container": "matroska",
"codec": "ffv1",
"pixel_format": "gray",
"logical_dtype": "bool",
"stored_values": [
0,
1
],
"validation": [
"all_bool_values_exact"
]
},
"mkv/uint16_ffv1/v1": {
"container": "matroska",
"codec": "ffv1",
"pixel_formats": [
"gray",
"gray16le"
],
"logical_dtype": "uint16",
"gray_condition": "all values <=255; decode by exact uint8-to-uint16 promotion",
"validation": [
"all_integer_values_exact"
]
}
},
"video_metadata": {
"required": [
"profile",
"codec",
"pixel_format",
"encoded_size",
"decoder",
"encoder_parameters",
"source_lossy"
],
"source_lossy_values": [
true,
false,
"unknown"
],
"timebase_role": "index_only",
"lossless_reference": "source compressed packets or fixed-decoder source pixels; depth uses normalized standard float32 bits",
"selection": "choose smaller complete candidate only after exact roundtrip validation"
}
}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061Verified existing subject1/h1/0Verified existing subject4/h1/0Verified existing subject3/h1/0Verified existing subject1/h1/6Verified existing subject2/h1/0Verified existing subject1/h1/3Verified existing subject2/h1/6Verified existing subject1/h1/7Converted subject3/h1/6Converted subject4/h1/6Verified existing subject1/h1/4Verified existing subject1/h1/2Verified existing subject2/h1/3Verified existing subject1/h1/1Verified existing subject1/h1/5Verified existing subject1/o1/0Converted subject3/h1/3Verified existing subject2/h1/7Verified existing subject1/o1/6Converted subject4/h1/3Verified existing subject1/o1/3Verified existing subject2/h1/4Verified existing subject1/o1/7Verified existing subject1/o1/4Verified existing subject2/h1/2Verified existing subject1/o1/2Converted subject3/h1/7Converted subject4/h1/7Verified existing subject1/o1/1Verified existing subject2/h1/1Verified existing subject1/o1/5Verified existing subject1/o2/0Converted subject3/h1/4Verified existing subject2/h1/5Verified existing subject1/o2/6Verified existing subject1/o2/3Verified existing subject2/o1/0Converted subject4/h1/4Verified existing subject1/o2/7Verified existing subject1/o2/4Converted subject3/h1/2Verified existing subject2/o1/6Converted subject4/h1/2Verified existing subject1/o2/2Verified existing subject2/o1/3Converted subject3/h1/1Verified existing subject1/o2/1Verified existing subject1/o2/5Verified existing subject1/k1/0Verified existing subject1/k1/6Verified existing subject2/o1/4Verified existing subject1/k1/3Converted subject3/h1/5Converted subject4/h1/1Verified existing subject1/k1/7Verified existing subject2/o1/2Converted subject4/h1/5Converted subject3/o1/0Converted subject1/k1/4Converted subject4/o1/0Verified existing subject2/o1/11234567START=2026-09-30T11:03:05+08:00WORKERS=4 CODEC_THREADS=10 DECODE_THREADS=10 DEPTH_THREADS=4 SUBJECTS=1,2,3,4 CASA=falseCPU_LIMIT=noneCGROUP=/user.slice/user-25044.slice/user@25044.service/app.slice/h2o-full-d10-20260930.scopeCPU_MAX=max controller_disabled
RECONFIGURE=2026-09-30T15:47:55+08:00 REASON=process16_camera_pipeline_ram32_streaming1234567891011121314151617181920212223242526#!/usr/bin/env bashset -ubase="$HOME/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10"raw="$HOME/Datasets/Hand-Datasets-Raw/H2O"cd "$HOME/Projects/uni-hoi-dataset" || exit 1mkdir -p "$base/scratch"export TMPDIR="$base/scratch" PYTHONUNBUFFERED=1for n in 1 2 3 4; do test -s "$raw/raw/data/subject${n}_v1_1.tar.gz" || exit 2; donetest ! -e "$base/full.status" || exit 3cg=$(awk -F: '$1=="0" {print $3}' /proc/self/cgroup)if [[ -f "/sys/fs/cgroup$cg/cpu.max" ]]; then read -r quota period < "/sys/fs/cgroup$cg/cpu.max"else quota=max period=controller_disabledfiprintf 'START=%s\nWORKERS=4 CODEC_THREADS=10 DECODE_THREADS=10 DEPTH_THREADS=4 SUBJECTS=1,2,3,4 CASA=false\nCPU_LIMIT=none\nCGROUP=%s\nCPU_MAX=%s %s\n' "$(date -Is)" "$cg" "$quota" "$period" > "$base/full.status"if [[ "$quota" != max ]]; then printf 'EXIT=4 ERROR=UNEXPECTED_CPU_QUOTA\n' >> "$base/full.status" exit 4fi/usr/bin/time -v .venv/bin/python "$base/frozen-code/scripts/convert_h2o_v1.0.py" --root "$raw" --out "$base" --release-id shared-v1.0 --workers 4 --codec-threads 10 --decode-threads 10 --depth-threads 4 --mano-dir "$HOME/Projects/WiLoR/mano_data" > "$base/full.log" 2>&1code=$?printf 'EXIT=%s END=%s\n' "$code" "$(date -Is)" >> "$base/full.status"if [[ -f "/sys/fs/cgroup$cg/cpu.stat" ]]; then cat "/sys/fs/cgroup$cg/cpu.stat" >> "$base/full.status"; fiexit "$code"12345678910111213141516171819202122232425262728293031#!/usr/bin/env python3"""Check saved Dex-YCB source 3D joints against saved source 2D joints in sampled views."""import jsonfrom pathlib import Pathimport sys
import numpy as npimport torch
root = Path(sys.argv[1])report = json.loads((root / 'doc/validation/STRUCTURAL_AUDIT.json').read_text())checks = []for name in report['sampled_views']: view = root / name load = lambda path: torch.load(view / path, weights_only=True, map_location='cpu').numpy() k = load('camera/intrinsic.pt') xyz = load('annotation/keypoints/xyz.pt') uv = load('annotation/keypoints/uv.pt') valid = load('annotation/keypoints/xyz_valid.pt') & load('annotation/keypoints/uv_valid.pt') z = xyz[..., 2] valid &= np.isfinite(xyz).all(axis=-1) & np.isfinite(uv).all(axis=-1) & (z > 0) z = np.where(valid, z, 1) pred = np.stack((k[:, 0, 0, None, None] * xyz[..., 0] / z + k[:, 0, 2, None, None], k[:, 1, 1, None, None] * xyz[..., 1] / z + k[:, 1, 2, None, None]), axis=-1) errors = np.linalg.norm(pred[valid] - uv[valid], axis=-1) checks.append(dict(view=name, points=int(errors.size), median_px=float(np.median(errors)) if errors.size else None, p95_px=float(np.percentile(errors, 95)) if errors.size else None))(root / 'doc/validation/KEYPOINT_PROJECTION_QC.json').write_text(json.dumps({ 'scope': 'Saved source 3D joints projected with saved color intrinsics vs saved source 2D joints; independent of hand mesh rendering.', 'views': checks}, ensure_ascii=False, indent=2) + '\n')print(json.dumps(checks, ensure_ascii=False), flush=True)1234567891011121314151617{ "root": "/home/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O", "out": "/home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10", "release_id": "shared-v1.0", "limit": null, "max_frames": null, "mano_dir": "/home/xuzhefeng/Projects/WiLoR/mano_data", "views": null, "jpeg_full_check": false, "workers": 4, "codec_threads": 10, "decode_threads": 10, "depth_threads": 4, "subjects": null, "include_casa": false, "archive": null}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349#!/usr/bin/env python3"""Dex-YCB source annotations → CONTRACT.md v1.0. No derived annotations."""import ioimport reimport shutilimport tarfileimport tempfilefrom pathlib import Path
import numpy as npfrom PIL import Imageimport yaml
from warehouse_v1_0 import (View, build_record, find_file, locator, mano_models, mesh_asset, model_profile, parser, pca_to_axis_angle, release, roots, safe_member, sequence_dir)
IMG_W, IMG_H = 640, 480
class _Loader(yaml.SafeLoader): pass
_Loader.add_constructor("tag:yaml.org,2002:python/tuple", lambda l, n: tuple(l.construct_sequence(n)))
def yaml_load_bytes(data: bytes): return yaml.load(io.BytesIO(data), Loader=_Loader)
class Calibration: def __init__(self, dexycb_root: Path): self.intrinsics = {} # serial -> {fx,fy,cx,cy,w,h} self.extrinsics = {} # group -> {serial: [12] 行优先 3×4 cam→world} self.betas = {} # mano_calib_name -> [10] calib_dir = dexycb_root / "calibration" if calib_dir.is_dir(): self._load((p.as_posix(), p.read_bytes()) for p in sorted(calib_dir.rglob("*")) if p.is_file()) else: tar_path = dexycb_root / "calibration.tar.gz" if not tar_path.exists(): raise FileNotFoundError(f"no calibration/ nor calibration.tar.gz in {dexycb_root}") with tarfile.open(tar_path, "r:gz") as tf: self._load((m.name, tf.extractfile(m).read()) for m in tf if m.isfile())
_RE_INTR = re.compile(r"(?:^|/)intrinsics/(\d+)_\d+x\d+\.yml$") _RE_EXTRA = re.compile(r"(?:^|/)extrinsics_(\d{8}_\d{6})/extrinsics\.yml$") _RE_MANO = re.compile(r"(?:^|/)mano_(\d{8}_\d{6}_subject-\d{2}_right)/mano\.yml$")
def _load(self, files): for rel, data in files: m = self._RE_INTR.search(rel) if m: c = yaml_load_bytes(data)["color"] self.intrinsics[m.group(1)] = {"fx": float(c["fx"]), "fy": float(c["fy"]), "cx": float(c["ppx"]), "cy": float(c["ppy"]), "w": IMG_W, "h": IMG_H} continue m = self._RE_EXTRA.search(rel) if m: raw = yaml_load_bytes(data)["extrinsics"] self.extrinsics[m.group(1)] = { str(s): [float(x) for x in np.asarray(v).ravel()] for s, v in raw.items()} continue m = self._RE_MANO.search(rel) if m: self.betas[m.group(1)] = [float(b) for b in yaml_load_bytes(data)["betas"]]
def calibration_locator(path, member, **extra): if path.is_dir(): return locator(path / member.removeprefix('calibration/'), **extra) return locator(path, member, **extra)
def prepare_models(root, destination): archive = find_file(root, 'models.tar.gz') if archive is None: return {}, None pattern = re.compile(r'^models/(\d{3}_[a-z0-9_]+)/(textured_simple\.obj(?:\.mtl)?|texture_map\.png)$') names = set() with tarfile.open(archive, 'r|gz') as tf: for member in tf: match = pattern.fullmatch(member.name) if member.isfile() and match: names.add(match[1]) path = safe_member(destination, '/'.join(match.groups())) path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(tf.extractfile(member).read()) if len(names) != 21: raise ValueError('expected all 21 source YCB model directories') return {i: destination / name for i, name in enumerate(sorted(names), 1)}, archive
def convert_view(path, args, seq, serial, frames, meta, meta_loc, calib, calib_path, models, assets, asset_archive): total = int(meta.get('num_frames', max(frames) + 1)) ids = list(range(min(total, args.max_frames) if args.max_frames else total)) for f in ids: frames.setdefault(f, {}) if not ids: raise ValueError('no RGB frames') source_rows = [] for f in ids: row = frames[f] source_rows.append(dict(source_frame_id=f, sync_id=f'{seq}:{f}', source_locator=row['color'][1] if 'color' in row else (meta_loc | {'source_frame_id': f, 'missing_rgb': True}), annotation_matches={ 'labels': {'source_frame_id': f, 'source_timestamp_ns': None, 'clock_domain': None, 'match_method': 'index_map', 'delta_ns': None, 'source_locator': row['labels'][1]} for _ in [0] if 'labels' in row}, component_sources={k: v[1] for k, v in row.items()})) view = View(path, 'dex-ycb', args.release_id, seq, serial, source_rows, sampling='dense' if ids == list(range(ids[0], ids[-1] + 1)) else 'sparse') view.valid_rules = { 'mano': 'Source pose_m present and not all zero; side model/calibration available', 'keypoints': 'Corresponding joint_2d/joint_3d present; whole-hand all -1 is missing, broadcast to its 21 points', 'pose': 'Source pose_y for this ycb_ids slot present and not an all-zero matrix', 'segment': 'Source seg array provided for this frame; region codes and entity references validated', 'relations': 'Source sequence ycb_grasp_ind resolves through ycb_ids; broadcast sequence grasp to selected frames', } view.full_jpeg = getattr(args, 'jpeg_full_check', False) view.meta['view_type'] = 'exo' view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} subject = re.search(r'subject-(\d+)', seq) if subject and 1 <= int(subject[1]) <= 10: index = int(subject[1]) view.meta.update(split='val' if index == 7 else 'test' if index in (8, 9) else 'train', split_scheme='Dex-YCB/s1', split_source_locator={ 'url': 'https://github.com/NVlabs/dex-ycb-toolkit/blob/master/dex_ycb_toolkit/dex_ycb.py', 'rule': 's1 unseen-subject: 01-06/10 train, 07 val, 08-09 test'}) view.meta.pop('split_reason', None) view.rgb([frames[f]['color'][0] if 'color' in frames[f] else None for f in ids], {'frames_ref': 'camera/frames.jsonl'}) n = len(ids) intr = calib.intrinsics.get(serial) K = None if intr is None else np.array([[intr['fx'], 0, intr['cx']], [0, intr['fy'], intr['cy']], [0, 0, 1]]) ext = calib.extrinsics.get(str(meta['extrinsics']), {}).get(serial) E = None if ext is not None: E = np.eye(4) E[:3] = np.asarray(ext).reshape(3, 4) E = np.linalg.inv(E) view.camera(K, calibration_locator(calib_path, f'calibration/intrinsics/{serial}_640x480.yml'), E, calibration_locator(calib_path, f'calibration/extrinsics_{meta["extrinsics"]}/extrinsics.yml', conversion='inverse of source T_world_from_camera')) sides = meta.get('mano_sides') if sides not in (['left'], ['right']): raise ValueError(f'expected exactly one anatomical source hand: {sides}') side = sides[0] slot = ['left', 'right'].index(side) cal_name = meta['mano_calib'][0] if isinstance(meta['mano_calib'], list) else meta['mano_calib'] labels = [dict(np.load(frames[f]['labels'][0])) if 'labels' in frames[f] else {} for f in ids] label_loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources.labels'} motion = np.full((n, 2, 61), np.nan, np.float32) mv = np.zeros((n, 2), bool) if side in models and any('pose_m' in lab for lab in labels): for i, lab in enumerate(labels): if 'pose_m' not in lab: continue pose = np.asarray(lab['pose_m']).reshape(51) if not np.any(pose): # Official Dex-YCB missing-pose sentinel, independent of joints/seg. continue motion[i, slot] = np.r_[pose[:3], pca_to_axis_angle(pose[3:48], models[side]), calib.betas[cal_name], pose[48:51]] mv[i, slot] = True view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, ['T', 'hand', 'parameter'], label_loc, model_profile=model_profile(models), calibration_source=calibration_locator(calib_path, f'calibration/mano_{cal_name}/mano.yml'), provenance={'kind': 'format_conversion', 'method': 'source PCA @ hands_components + hands_mean; explicit axis-angle consumed with flat_hand_mean=true'}) elif any('pose_m' in lab for lab in labels): view.absent('mano', 'Source PCA exists; provide --mano-dir to expand it', 'dependency_missing') else: view.absent('mano', 'No source pose_m field') for source_key, key, dim, unit in [('joint_2d', 'uv', 2, 'pixel'), ('joint_3d', 'xyz', 3, 'm')]: if not any(source_key in x for x in labels): view.absent('keypoints_' + key, 'No source ' + source_key) continue points = np.full((n, 2, 21, dim), np.nan, np.float32) valid = np.zeros((n, 2, 21), bool) for i, lab in enumerate(labels): if source_key not in lab: continue p = np.asarray(lab[source_key]).reshape(21, dim) points[i, slot] = p valid[i, slot] = not np.all(p == -1) # Official sentinel covers the whole source hand. # An individual off-image point (-1, -1) is not evidence of missing annotation. view.tensor('keypoints_' + key, f'keypoints/{key}/v1', f'annotation/keypoints/{key}.pt', points, valid, ['T', 'hand', 'keypoint', 'coordinate'], label_loc, keypoint_schema='mano21/v1', unit=unit) ycb_ids = [int(x) for x in meta['ycb_ids']] for j, oid in enumerate(ycb_ids): entity = f'ycb_{oid:02d}' view.object(entity, meta_loc, source_object_id=oid, category_id=oid) poses = np.full((n, 4, 4), np.nan, np.float32) valid = np.zeros(n, bool) for i, lab in enumerate(labels): if 'pose_y' in lab: pose = np.asarray(lab['pose_y']) if pose.shape != (len(ycb_ids), 3, 4): raise ValueError('pose_y shape differs from ycb_ids') if np.any(pose[j]): # Official all-zero missing object pose sentinel. poses[i] = np.eye(4) poses[i, :3] = pose[j] valid[i] = True if any('pose_y' in lab for lab in labels): view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', poses, valid, ['T', 'row', 'column'], label_loc, convention='T_camera_from_object', unit='m') else: view.absent('pose_' + entity, 'No source pose_y field') if oid in assets: mesh_asset(view, entity, assets[oid], assets[oid] / 'textured_simple.obj', locator(asset_archive, f'models/{assets[oid].name}/textured_simple.obj')) else: view.absent('mesh_' + entity, 'models.tar.gz unavailable', 'not_downloaded') if any('seg' in lab for lab in labels): mask_rows = [] width, height = view.meta['camera']['image_size'] for i, lab in enumerate(labels): values = np.unique(lab.get('seg', np.zeros((height, width), np.uint8))) mappings = [] for value in values: value = int(value) if value == 0: continue if value != 255 and value not in ycb_ids: raise ValueError(f'unknown Dex-YCB region value {value}') mappings.append(dict(mask_value=value, category_id='hand' if value == 255 else value, entity_id='hand_' + side if value == 255 else f'ycb_{value:02d}', part_id=None, source_instance_id=value)) mask_rows.append(dict(frame_index=i, labels=mappings)) view.raster('segment', (lab.get('seg', np.zeros((height, width), np.uint16)) for lab in labels), ['seg' in lab for lab in labels], label_loc, mask_rows) view.meta['components']['segment'].update(coverage={'kind': 'selected_entities', 'entities': ['hand_' + side] + [f'ycb_{o:02d}' for o in ycb_ids]}, source_zero_meaning='background') else: view.absent('segment', 'No source seg field') if any('aligned_depth_to_color' in frames[f] for f in ids): def depths(): width, height = view.meta['camera']['image_size'] for f in ids: item = frames[f].get('aligned_depth_to_color') if item is None: yield np.full((height, width), np.nan, np.float32) else: with Image.open(item[0]) as im: yield np.asarray(im).astype(np.float32) / 1000.0 view.raster('depth', depths(), None, {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources.aligned_depth_to_color', 'conversion': 'millimetres to metres'}) else: view.absent('depth', 'No source aligned_depth_to_color frames') grasp = meta.get('ycb_grasp_ind') if grasp is not None: if not 0 <= int(grasp) < len(ycb_ids): raise ValueError('invalid ycb_grasp_ind') relation = dict(relation_type='grasp', subject_id='hand_' + side, object_id=f'ycb_{ycb_ids[int(grasp)]:02d}', status='positive', source_locator=meta_loc, provenance={'kind': 'source', 'method': 'sequence ycb_grasp_ind resolved through ycb_ids; not per-frame contact'}) view.relations([{'frame_index': i, 'relations': [relation]} for i in range(n)], np.ones(n, bool), meta_loc) else: view.absent('relations', 'No source grasp/contact relation') return view.finish()
MEMBER = re.compile(r'^([^/]+)/(\d{8}_\d{6})/(meta\.yml|(\d{12})/(color|labels|aligned_depth_to_color)_(\d+)\.(jpg|npz|png))$')
def convert_archive(archive, args, out, calib, calib_path, models, assets, asset_archive): selected_views = set(args.views.split(',')) if args.views else None done = 0 current, meta, meta_loc, rows = None, None, None, {} with tempfile.TemporaryDirectory(prefix='dex-source-') as wd: work = Path(wd) def flush(): nonlocal done if not rows: return seq = archive.name.split('.tar')[0] + '_' + current reports = {} with sequence_dir(out, seq) as target: for serial, frames in sorted(rows.items()): reports[serial] = convert_view(target / serial, args, seq, serial, frames, meta, meta_loc, calib, calib_path, models, assets, asset_archive) build_record(out, seq, reports) for staged in list(work.iterdir()): if staged.is_dir(): shutil.rmtree(staged) else: staged.unlink() done += 1 print(f'Converted {seq}', flush=True) with tarfile.open(archive, 'r|gz') as tf: for member in tf: match = MEMBER.fullmatch(member.name) if not member.isfile() or not match: continue seq = match[2] if seq != current: flush() if args.limit and done >= args.limit: break current, meta, meta_loc, rows = seq, None, None, {} data_kind = match[3] if data_kind == 'meta.yml': data = tf.extractfile(member).read() meta = yaml_load_bytes(data) meta_loc = locator(archive, member.name, data) continue serial, kind, f = match[4], match[5], int(match[6]) if selected_views and serial not in selected_views or args.max_frames and f >= args.max_frames: continue data = tf.extractfile(member).read() dest = safe_member(work, member.name) dest.parent.mkdir(parents=True, exist_ok=True) dest.write_bytes(data) row = rows.setdefault(serial, {}).setdefault(f, {}) if kind in row: raise ValueError('duplicate archive frame') row[kind] = (dest, locator(archive, member.name, data)) else: flush() return done
def main(argv=None): p = parser('dex-ycb', __doc__) p.add_argument('--subjects') args = p.parse_args(argv) archives = sorted({a for r in roots(args.root) for a in r.glob('*-subject-*.tar.gz')}) if args.subjects: subjects = {s.strip().zfill(2) for s in args.subjects.split(',')} archives = [a for a in archives if re.search(r'subject-(\d+)', a.name)[1] in subjects] if not archives: p.error('no Dex-YCB subject archives found') cp = find_file(args.root, 'calibration.tar.gz') or find_file(args.root, 'calibration') if cp is None: p.error('calibration source missing') calib = Calibration(cp.parent) models = mano_models(args.mano_dir) out = release(args, 'dex-ycb') with tempfile.TemporaryDirectory(prefix='dex-models-') as wd: assets, asset_archive = prepare_models(args.root, Path(wd)) for archive in archives: convert_archive(archive, args, out, calib, cp, models, assets, asset_archive) return 0
if __name__ == '__main__': raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545#!/usr/bin/env python3"""H2O native RGB-D, MANO, joints and objects → CONTRACT.md v1.0 (no rendered masks)."""from concurrent.futures import ThreadPoolExecutorimport jsonimport osimport reimport shutilimport tarfileimport tempfilefrom pathlib import Pathimport zipfile
# Bound native libraries before loading NumPy/Torch; each worker still uses independent FFmpeg processes.for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): os.environ[key] = '1'
import numpy as npfrom PIL import Imageimport torch
from warehouse_v1_0 import (View, build_record, check_mesh, find_file, locator, mano_models, mesh_asset, model_profile, parser, release, roots, safe_member, sequence_dir, sha256)
OBJECTS = {1: 'book', 2: 'espresso', 3: 'lotion', 4: 'spray', 5: 'milk', 6: 'cocoa', 7: 'chips', 8: 'cappuccino'}MEMBER = re.compile(r'^(?:h2o_CASA/)?(subject\d+)/([^/]+)/(\d+)/(cam\d)/(.+)$')FRAME = re.compile(r'(rgb|depth|cam_pose|hand_pose|hand_pose_mano|obj_pose|obj_pose_rt)/(\d+)\.(png|jpg|txt)$')
def load_splits(root): archive = find_file(root, 'label_split.zip') result = {} if archive is not None: with zipfile.ZipFile(archive) as z: for split in ('train', 'val', 'test'): member = f'label_split/action_{split}.txt' for line_no, line in enumerate(z.read(member).decode().splitlines(), 1): fields = line.split() if len(fields) < 2 or fields[1] == 'path': continue key = fields[1] if key in result and result[key][0] != split: raise ValueError('conflicting official splits') result[key] = (split, locator(archive, member, record=line_no)) return result
def load_assets(root, work): archive = find_file(root, 'object.zip') if archive is None: return {}, None with zipfile.ZipFile(archive) as z: for member in z.infolist(): if member.is_dir(): continue path = safe_member(work, member.filename) path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(z.read(member)) result = {} for oid, name in OBJECTS.items(): directory = work / 'object' / name aliases = [] # Source cocoa.obj -> ovomaltine.mtl -> cocoa.png, but the ZIP names the # supplied texture ovomaltine.png. Keep all originals and add a byte-identical alias. if name == 'cocoa' and not (directory / 'cocoa.png').exists(): mtl = directory / 'ovomaltine.mtl' if mtl.is_file() and 'map_Kd cocoa.png' in mtl.read_text().splitlines(): texture = directory / 'ovomaltine.png' shutil.copyfile(texture, directory / 'cocoa.png') aliases.append({'file': 'cocoa.png', 'sha256': sha256(texture), 'source': locator(archive, 'object/cocoa/ovomaltine.png')}) candidates = list(directory.glob('*.obj')) if len(candidates) != 1: raise ValueError(f'expected one source OBJ for {name}') check_mesh(candidates[0], directory) # Fail before decoding any large subject archive. result[oid] = (directory, candidates[0], aliases) return result, archive
def convert_view(path, args, seq, cam, rows, intr, splits, models, assets, asset_archive): codec_threads = getattr(args, 'codec_threads', 1) ids = list(range(min(rows), max(rows) + 1)) for f in ids: rows.setdefault(f, {}) n = len(ids) if not n: raise ValueError('no RGB frames') split, split_loc = splits.get(seq, ('unknown', None)) frame_rows = [dict(source_frame_id=f, sync_id=f'{seq}:{f}', source_locator=rows[f]['rgb'][1] if 'rgb' in rows[f] else {'sequence': seq, 'camera': cam, 'source_frame_id': f, 'missing_rgb': True}, component_sources={k: item[1] for k, item in rows[f].items()}, annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, clock_domain=None, match_method='index_map', delta_ns=None) for k in rows[f] if k != 'rgb'}) for f in ids] view = View(path, 'H2O', args.release_id, seq.replace('/', '_'), cam, frame_rows, split=split) view.valid_rules = { 'mano': 'Per-hand hand_pose_mano flag equals 1; corresponding side model available', 'keypoints': "Per-hand hand_pose flag equals 1, broadcast to that hand's 21 source points independently of MANO", 'pose': 'Source obj_pose_rt class equals this nonzero object class', 'points': 'Source obj_pose class equals this nonzero object class, broadcast to its 21 points', } view.full_jpeg = getattr(args, 'jpeg_full_check', False) view.meta['view_type'] = 'ego' if cam == 'cam4' else 'exo' if cam in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown' view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} if split_loc: view.meta.update(split_scheme='official_action_split', split_source_locator=split_loc) # In the measured 275 H2O views, exact FFV1 was always smaller than exact H.264. view.rgb([rows[f]['rgb'][0] if 'rgb' in rows[f] else None for f in ids], {'frames_ref': 'camera/frames.jsonl'}, ffv1_first=True, codec_threads=codec_threads) loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} if intr is not None: fx, fy, cx, cy, width, height = np.loadtxt(intr[0]).ravel() if [int(width), int(height)] != view.meta['camera']['image_size']: raise ValueError('source intrinsics resolution mismatch') K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) view.camera(K, intr[1]) camps = np.full((n, 4, 4), np.nan, np.float32) cv = np.zeros(n, bool) data = [] for i, f in enumerate(ids): lab = {k: np.loadtxt(item[0]).ravel() for k, item in rows[f].items() if k not in ('rgb', 'depth')} data.append(lab) if 'cam_pose' in lab: camps[i] = np.linalg.inv(lab['cam_pose'].reshape(4, 4)) cv[i] = True if cv.any(): view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', camps, cv, ['T', 'row', 'column'], loc, convention='T_camera_from_world', source_convention='T_world_from_camera') motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) points, pv = np.full((n, 2, 21, 3), np.nan, np.float32), np.zeros((n, 2, 21), bool) object_ids = set() for i, lab in enumerate(data): if 'hand_pose_mano' in lab: hands = lab['hand_pose_mano'].reshape(2, 62) for side, row in enumerate(hands): if row[0] not in (0, 1): raise ValueError('unexpected H2O MANO presence flag') if row[0] == 1: motion[i, side] = np.r_[row[4:52], row[52:62], row[1:4]] mv[i, side] = True if 'hand_pose' in lab: hands = lab['hand_pose'].reshape(2, 64) for side, row in enumerate(hands): if row[0] not in (0, 1): raise ValueError('unexpected H2O keypoint presence flag') if row[0] == 1: points[i, side] = row[1:].reshape(21, 3) pv[i, side] = True for key in ('obj_pose', 'obj_pose_rt'): if key in lab and lab[key][0] != 0: object_ids.add(int(lab[key][0])) if any('hand_pose_mano' in lab for lab in data): if len(models) == 2: view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) else: view.absent('mano', 'Source parameters exist; --mano-dir must identify both model profiles', 'dependency_missing') if any('hand_pose' in lab for lab in data): view.tensor('keypoints_xyz', 'keypoints/xyz/v1', 'annotation/keypoints/xyz.pt', points, pv, ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='m') for oid in sorted(object_ids): if oid not in OBJECTS: raise ValueError(f'unknown H2O object class {oid}') entity = OBJECTS[oid] view.object(entity, loc, category_id=oid, source_object_id=oid) poses, ov = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) pts, kv = np.full((n, 21, 3), np.nan, np.float32), np.zeros((n, 21), bool) for i, lab in enumerate(data): if 'obj_pose_rt' in lab and lab['obj_pose_rt'][0] == oid: poses[i] = lab['obj_pose_rt'][1:].reshape(4, 4) ov[i] = True if 'obj_pose' in lab and lab['obj_pose'][0] == oid: pts[i] = lab['obj_pose'][1:].reshape(21, 3) kv[i] = True if ov.any(): view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', poses, ov, ['T', 'row', 'column'], loc, convention='T_camera_from_object', unit='m') if kv.any(): view.tensor('points_' + entity, 'object_keypoints/camera/v1', f'annotation/object/{entity}/keypoints/xyz.pt', pts, kv, ['T', 'keypoint', 'coordinate'], loc, keypoint_schema='H2O_official_object21', keypoint_names=['center'] + [f'corner_{i}' for i in range(8)] + [f'edge_midpoint_{i}' for i in range(12)], source_order='official obj_point_order.jpg: center, 8 corners, 12 edge midpoints', unit='m') if oid in assets: directory, obj, aliases = assets[oid] asset_loc = locator(asset_archive, f'object/{entity}/{obj.name}') if aliases: asset_loc['texture_aliases'] = aliases mesh_asset(view, entity, directory, obj, asset_loc) else: view.absent('mesh_' + entity, 'Source object.zip unavailable', 'not_downloaded') if any('depth' in rows[f] for f in ids): width, height = view.meta['camera']['image_size'] depth_threads = getattr(args, 'depth_threads', 1) def read_depth(f): item = rows[f].get('depth') if item: with Image.open(item[0]) as im: return np.asarray(im).astype(np.float32) / 1000.0 return np.full((height, width), np.nan, np.float32) def depths(): if depth_threads == 1: yield from map(read_depth, ids) else: with ThreadPoolExecutor(max_workers=depth_threads) as pool: # Ordered batches bound decoded arrays to depth_threads frames per view. for start in range(0, len(ids), depth_threads): yield from pool.map(read_depth, ids[start:start + depth_threads]) view.raster('depth', depths(), None, loc | {'source_field': 'component_sources.depth', 'definition': 'https://github.com/taeinkwon/h2oplayer/blob/main/utils.py', 'conversion': 'registered millimetre camera-Z to metres; no viewer range clipping'}, codec_threads=codec_threads) else: view.absent('depth', 'No source depth frames') view.absent('segment', 'H2O provides no native segmentation; rendering deferred to v2.0') view.absent('relations', 'No source contact/grasp annotation') return view.finish()
def convert_archive(archive, args, out, splits, models, assets, asset_archive): selected_views = set(args.views.split(',')) if args.views else None subjects = {'subject' + s.strip() for s in args.subjects.split(',')} if args.subjects else None current, rows, intrinsics, done = None, {}, {}, 0 published_views = set() with tempfile.TemporaryDirectory(prefix='h2o-source-') as wd: work = Path(wd) def flush(): nonlocal done if not rows: return seq = '/'.join(current) reports, pending = {}, {} for cam, frames in sorted(rows.items()): existing = out / 'data' / seq.replace('/', '_') / cam if (existing / 'metainfo.json').is_file(): old_frames = [json.loads(line) for line in (existing / 'camera/frames.jsonl').read_text().splitlines()] if [f['source_frame_id'] for f in old_frames] != list(range(min(frames), max(frames) + 1)): raise ValueError('existing view has different sampling; choose a new release-id') for frame in old_frames: incoming = frames.get(frame['source_frame_id'], {}) previous = frame.get('component_sources', {}) if set(previous) != set(incoming) or any(previous[k].get('sha256') != v[1].get('sha256') for k, v in incoming.items()): raise ValueError('duplicate H2O view differs from the published source; choose a new release-id') else: pending[cam] = frames if pending: with sequence_dir(out, seq.replace('/', '_')) as target: for cam, frames in pending.items(): reports[cam] = convert_view(target / cam, args, seq, cam, frames, intrinsics.get(cam), splits, models, assets, asset_archive) build_record(out, seq.replace('/', '_'), reports) for staged in list(work.iterdir()): if staged.is_dir(): shutil.rmtree(staged) else: staged.unlink() done += 1 print(f'{"Converted" if pending else "Verified existing"} {seq}', flush=True) # Uncompressed CASA supports seeking over large frames; gzip is single-pass. mode = 'r:' if archive.suffix == '.tar' else 'r|gz' with tarfile.open(archive, mode) as tf: for member in tf: match = MEMBER.fullmatch(member.name) if not member.isfile() or not match: continue subj, scene, seq, cam, tail = match.groups() if subjects and subj not in subjects: continue key = (subj, scene, seq) if key != current: flush() if args.limit and done >= args.limit: break current, rows, intrinsics = key, {}, {} published_views = {view.name for view in (out / 'data' / '_'.join(key)).glob('cam*') if (view / 'metainfo.json').is_file()} if selected_views and cam not in selected_views: continue frame = FRAME.fullmatch(tail) if tail != 'cam_intrinsics.txt' and not frame: continue if frame and args.max_frames and int(frame[2]) >= args.max_frames: continue data = tf.extractfile(member).read() dest = safe_member(work, member.name) if cam not in published_views: dest.parent.mkdir(parents=True, exist_ok=True) dest.write_bytes(data) # Published views still verify source bytes, but never read their staging paths. item = (dest, locator(archive, member.name, data)) if tail == 'cam_intrinsics.txt': intrinsics[cam] = item else: kind, f = frame[1], int(frame[2]) row = rows.setdefault(cam, {}).setdefault(f, {}) if kind in row: raise ValueError('duplicate H2O frame') row[kind] = item else: flush() return done
def main(argv=None): p = parser('H2O', __doc__) p.set_defaults(release_id='shared-v1.0') p.add_argument('--workers', type=int, choices=range(1, 5), default=1, help='Independent subject archives in parallel, 1..4; benchmark before using >2') p.add_argument('--codec-threads', type=int, choices=(1, 2, 4, 8, 10), default=4, help='FFV1 slice threads per encode; default 4, use 10 for the current full run') p.add_argument('--decode-threads', type=int, choices=(1, 2, 4, 8, 10), default=1, help='FFmpeg threads for source RGB decoding and decoded-media checks') p.add_argument('--depth-threads', type=int, choices=(1, 2, 4), default=1, help='Bounded ordered source depth PNG loading per worker') p.add_argument('--subjects') p.add_argument('--include-casa', action='store_true') p.add_argument('--archive', type=Path, help='Convert one explicit source archive') args = p.parse_args(argv) os.environ['HAND_WAREHOUSE_FFMPEG_THREADS'] = str(args.decode_threads) if args.include_casa and args.workers != 1: p.error('CASA can share sequence IDs with subject archives; convert it sequentially in a separate release') archives = [args.archive.expanduser()] if args.archive else sorted( {a for root in roots(args.root) for a in root.glob('subject*_v1_1.tar.gz')}) if args.subjects and not args.archive: requested = {'subject' + s.strip() for s in args.subjects.split(',')} archives = [arc for arc in archives if arc.name.split('_', 1)[0] in requested] if args.include_casa: casa = find_file(args.root, 'h2o_CASA.tar') if casa: archives.append(casa) if not archives: p.error('no H2O archives found') out = release(args, 'H2O') source_mapping = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/h2o-RAW_TO_SHARED.md', Path(__file__).resolve().parents[1] / 'doc/RAW_TO_SHARED.md', out / 'doc/RAW_TO_SHARED.md') if p.is_file()) mapping = out / 'doc/RAW_TO_SHARED.md' if mapping.exists() and mapping.read_bytes() != source_mapping.read_bytes(): raise ValueError('RAW_TO_SHARED.md changed; choose a new release-id') if not mapping.exists(): shutil.copyfile(source_mapping, mapping) torch.set_num_threads(1) models, splits = mano_models(args.mano_dir), load_splits(args.root) with tempfile.TemporaryDirectory(prefix='h2o-assets-') as wd: assets, asset_archive = load_assets(args.root, Path(wd)) def convert_one(archive): return convert_archive(archive, args, out, splits, models, assets, asset_archive) if args.workers == 1: for archive in archives: convert_one(archive) else: with ThreadPoolExecutor(max_workers=args.workers) as pool: for archive, count in zip(archives, pool.map(convert_one, archives), strict=True): print(f'Archive {archive.name}: {count} sequences', flush=True) return 0
if __name__ == '__main__': raise SystemExit(main())
# TODO(v2.0): 以下旧 MANO 网格和渲染分割代码仅保留备查;v1.0 不生成标注。# def load_mano_model(path: Path):# """MPI MANO pkl → numpy 字典。shapedirs 在 pkl 内为 chumpy Select(对 (778,3,20) 基# 底 flat 选取前 10 个 shape 分量;idxs 已核实等价于 base[:,:,:10])。"""# with open(path, "rb") as f:# d = _ManoUnpickler(f, encoding="latin1").load()# sd = d["shapedirs"]# base = np.asarray(sd.a.x, np.float64) # (778, 3, 20)# shapedirs = base.reshape(-1)[np.asarray(sd.idxs)].reshape(base.shape[0], 3, -1)# jreg = d["J_regressor"]# jreg = np.asarray(jreg.todense()) if hasattr(jreg, "todense") else np.asarray(jreg)# return {"v_template": np.asarray(d["v_template"], np.float64),# "shapedirs": shapedirs,# "posedirs": np.asarray(d["posedirs"], np.float64),# "weights": np.asarray(d["weights"], np.float64),# "J_regressor": np.asarray(jreg, np.float64),# "kintree": np.asarray(d["kintree_table"], np.int64),# "faces": np.asarray(d["f"], np.int64)}### def rodrigues(r):# """axis-angle (N,3) → 旋转矩阵 (N,3,3)。公式 I + sinθ·K + (1−cosθ)·K²(已对 scipy 核验)。"""# r = np.asarray(r, np.float64).reshape(-1, 3)# th = np.linalg.norm(r, axis=1)# R = np.zeros((len(r), 3, 3))# nz = th > 1e-12# R[~nz] = np.eye(3)# k = r[nz] / th[nz, None]# K = np.zeros((len(k), 3, 3))# K[:, 0, 1], K[:, 0, 2], K[:, 1, 2] = -k[:, 2], k[:, 1], -k[:, 0]# K[:, 1, 0], K[:, 2, 0], K[:, 2, 1] = k[:, 2], -k[:, 1], k[:, 0]# s, c = np.sin(th[nz])[:, None, None], np.cos(th[nz])[:, None, None]# R[nz] = np.eye(3) + s * K + (1 - c) * (K @ K)# return R### def _mano_chain(model, betas, pose):# """返回 (v_shaped, J, Rs, G):G 为 16 个关节的全局变换(平移列 = 关节位置)。"""# v = model["v_template"] + np.einsum("nkc,c->nk", model["shapedirs"], betas)# J = model["J_regressor"] @ v# Rs = rodrigues(np.asarray(pose, np.float64).reshape(16, 3))# kt = model["kintree"]# G = np.zeros((16, 4, 4))# for j in range(16):# p = kt[0, j] if j else -1# loc = np.eye(4)# loc[:3, :3] = Rs[j]# loc[:3, 3] = J[j] - (J[p] if j else 0.0)# G[j] = loc if not j else G[p] @ loc# return v, J, Rs, G### def mano_forward(model, betas, pose, transl):# """MANO LBS 前向(经典蒙皮 M_j = G_j·G0_j⁻¹;对 hand_pose 21 关节实证 0.0 mm)。# pose: 48 axis-angle([0:3] 全局);返回相机系米顶点 (778,3)。"""# v, J, Rs, G = _mano_chain(model, betas, pose)# lrot = (Rs[1:] - np.eye(3)).ravel()# v_posed = v + np.einsum("nkc,c->nk", model["posedirs"], lrot)# kt = model["kintree"]# G0 = np.zeros((16, 4, 4))# for j in range(16):# p = kt[0, j] if j else -1# loc = np.eye(4)# loc[:3, 3] = J[j] - (J[p] if j else 0.0)# G0[j] = loc if not j else G0[p] @ loc# M = np.einsum("nj,jab->nab", model["weights"], G @ np.linalg.inv(G0))# out = np.einsum("nab,nb->na", M[:, :3, :3], v_posed) + M[:, :3, 3]# return out + np.asarray(transl, np.float64)### def mano_chain_joints(model, betas, pose, transl):# """16 个关节位置(相机系米)= 链平移列;自检用。"""# _, _, _, G = _mano_chain(model, betas, pose)# return G[:, :3, 3] + np.asarray(transl, np.float64)### def rasterize(verts_cam, faces, labels, W, H, fx, fy, cx, cy):# z = verts_cam[:, 2]# P = faces# ok = (z[P] > 0.02).all(1) # 任一顶点在相机后 → 丢弃该三角形# P, labels = P[ok], labels[ok]# if len(P) == 0:# return np.zeros((H, W), np.uint16), np.zeros(0, np.int64)# x = verts_cam[:, 0] / z * fx + cx# y = verts_cam[:, 1] / z * fy + cy# xa = np.maximum(0, np.minimum(np.floor(x[P[:, 0]]), np.minimum(# np.floor(x[P[:, 1]]), np.floor(x[P[:, 2]]))).astype(np.int64))# xb = np.minimum(W - 1, np.maximum(np.ceil(x[P[:, 0]]), np.maximum(# np.ceil(x[P[:, 1]]), np.ceil(x[P[:, 2]]))).astype(np.int64))# ya = np.maximum(0, np.minimum(np.floor(y[P[:, 0]]), np.minimum(# np.floor(y[P[:, 1]]), np.floor(y[P[:, 2]]))).astype(np.int64))# yb = np.minimum(H - 1, np.maximum(np.ceil(y[P[:, 0]]), np.maximum(# np.ceil(y[P[:, 1]]), np.ceil(y[P[:, 2]]))).astype(np.int64))# xa, ya = np.minimum(xa, xb), np.minimum(ya, yb) # 完全出画的三角形 → 空 bbox# wdt, hgt = xb - xa + 1, yb - ya + 1# cnt = wdt * hgt# tot = int(cnt.sum())# tri = np.repeat(np.arange(len(P)), cnt)# k = np.arange(tot) - (np.cumsum(cnt) - cnt)[tri]# px = xa[tri] + k % wdt[tri] + 0.5# py = ya[tri] + k // wdt[tri] + 0.5# ax, ay = x[P[tri, 0]], y[P[tri, 0]]# bx, by = x[P[tri, 1]], y[P[tri, 1]]# cx_, cy_ = x[P[tri, 2]], y[P[tri, 2]]# area = ((x[P[:, 1]] - x[P[:, 0]]) * (y[P[:, 2]] - y[P[:, 0]])# - (y[P[:, 1]] - y[P[:, 0]]) * (x[P[:, 2]] - x[P[:, 0]]))# areat = area[tri]# e0 = (bx - ax) * (py - ay) - (by - ay) * (px - ax)# e1 = (cx_ - bx) * (py - by) - (cy_ - by) * (px - bx)# e2 = (ax - cx_) * (py - cy_) - (ay - cy_) * (px - cx_)# s = np.sign(areat)# inside = (np.abs(areat) > 1e-9) & ((e0 * s >= 0) & (e1 * s >= 0) & (e2 * s >= 0))# px, py, tri = px[inside], py[inside], tri[inside]# at = areat[inside]# w0, w1, w2 = e1[inside] / at, e2[inside] / at, e0[inside] / at# zz = w0 * z[P[tri, 0]] + w1 * z[P[tri, 1]] + w2 * z[P[tri, 2]]# pix = py.astype(np.int64) * W + px.astype(np.int64)# order = np.lexsort((zz, pix)) # 同像素按深度升序 → 首条即最近# pix, tri = pix[order], tri[order]# first = np.unique(pix, return_index=True)[1]# mask = np.zeros(H * W, np.uint16)# win = tri[first]# mask[pix[first]] = labels[win] + 1 # 临时标签 +1(0=背景)# return mask.reshape(H, W), np.bincount(labels[win] + 1)### # ============================================================================# # ffmpeg 写出与核验(与 convert_dexycb.py 同构)# # ============================================================================# verts, faces_all, labels = [], [], []# for ti, (tid, kind) in enumerate(tracks):# if kind == "hand_left" and b["mano"][0] > 0.5:# verts.append(mano_forward(mano_models["left"], b["mano"][52:62],# b["mano"][4:52], b["mano"][1:4]))# faces_all.append(mano_models["left"]["faces"])# elif kind == "hand_right" and b["mano"][62] > 0.5:# verts.append(mano_forward(mano_models["right"], b["mano"][114:124],# b["mano"][66:114], b["mano"][63:66]))# faces_all.append(mano_models["right"]["faces"])# elif isinstance(kind, tuple) and int(b["objp"][0]) == kind[1]:# M = np.asarray(b["objrt"][1:17], np.float64).reshape(4, 4)# V0, F0 = meshes[kind[1]]# verts.append(V0 @ M[:3, :3].T + M[:3, 3])# faces_all.append(F0)# else:# continue# labels.append(np.full(len(faces_all[-1]), ti))# if verts:# V = np.concatenate(verts)# offs = np.cumsum([0] + [len(v) for v in verts[:-1]])# F = np.concatenate([fa + o for fa, o in zip(faces_all, offs)])# mask, counts = rasterize(V, F, np.concatenate(labels),# IMG_W, IMG_H, fx, fy, cx, cy)# else:# mask, counts = np.zeros((IMG_H, IMG_W), np.uint16), np.zeros(0, np.int64)# lut = np.zeros(n_tracks + 1, np.uint16)# for ti in range(n_tracks):# present = ti + 1 < len(counts) and counts[ti + 1] > 0# if present:# presence[tracks[ti][0]][f] = True# if active_id[ti] is None:# pid = next(i for i in range(1, 65535) if i not in used)# used.add(pid)# active_id[ti], seg_start[ti] = pid, f# frame_maps[ti].append({"id": pid})# lut[ti + 1] = active_id[ti]# elif active_id[ti] is not None:# frame_maps[ti][-1]["frames"] = [seg_start[ti], f - 1]# segments[ti].append([seg_start[ti], f - 1])# used.discard(active_id[ti])# active_id[ti] = None# mw.write(lut[mask])
# TODO(v2.0): 旧物体尺寸派生代码;v1.0 仅保留源物体关键点。# pts = np.asarray(b["objp"][1:64], np.float64).reshape(21, 3)# half = np.abs((pts[1:9] - pts[0]) @ M[:3, :3]).max(0)# obj_recs.append({# "track_id": f"o{classes.index(c)}", "frame": f,# "mesh_ref": f"h2o/{OBJ_CLASSES[c]}.obj",# "pose": {"quat": rotmat_to_quat_wxyz(M[:3, :3])[0].tolist(),# "trans": M[:3, 3].tolist()},# "bbox_center3d": pts[0].tolist(),# "bbox_size": (2 * half).tolist()})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595#!/usr/bin/env python3"""HOI4D native observations and annotations → CONTRACT.md v1.0."""from collections import Counterfrom concurrent.futures import ThreadPoolExecutorfrom contextlib import ExitStackfrom functools import lru_cacheimport gzipimport ioimport jsonimport osfrom pathlib import Pathimport pickleimport reimport shutilimport shleximport posixpathimport subprocessimport tempfileimport tarfileimport threadingimport zipfile
# Each worker owns one Python thread; prevent native libraries spawning CPU pools.for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): os.environ[key] = '1'
import numpy as npfrom PIL import Imagefrom scipy.spatial.transform import Rotation
import torch
from warehouse_v1_0 import (View, build_record, check_mesh, decode_args, find_file, json_write, locator, mano_models, model_profile, parser, probe, release, run, safe_member, sequence_dir)
CATEGORIES = { 1: dict(cad="rigid/ToyCar", groups=[("main", [1], "Toy Car", 1)], hands={2: "right"}, objmap={"Toycar": "main"}), 2: dict(cad="rigid/Mug", groups=[("a", [1], "Mug", 2), ("b", [3], "Mug", 2)], hands={2: "right"}, objmap={"Watercup": "a"}), 3: dict(cad="articulated/Laptop", groups=[("main", [1, 3], "Laptop", 3)], hands={2: "right"}, objmap={"Laptopdisplay": "main", "Laptopkeyboard": "main"}), 4: dict(cad="articulated/StorageFurniture", groups=[("main", [1, 3, 4], "Storage Furniture", 4), ("bottle", [5], "Bottle", 5)], hands={2: "right"}, objmap={"Lockerbody": "main", "Lockersldingdoor": "main", "Lockerdrawer": "main", "Safebox": "main"}), 5: dict(cad="rigid/Bottle", groups=[("main", [1], "Bottle", 5), ("mug", [3], "Mug", 2)], hands={2: "right"}, objmap={"bottleddrinks": "main"}), 6: dict(cad="articulated/Safe", groups=[("main", [1, 3], "Safe", 6), ("bottle", [4], "Bottle", 5)], hands={2: "right"}, objmap={"Safebox": "main", "Safedoor": "main"}), 7: dict(cad="rigid/Bowl", groups=[("main", [1], "Bowl", 7), ("ball", [3], "Ball", None)], hands={2: "right"}, objmap={"bowl": "main"}), 8: dict(cad="articulated/Bucket", groups=[("a", [1, 3], "Bucket", 8), ("b", [4, 5], "Bucket", 8)], hands={2: "right", 6: "left"}, objmap={"bucket": "a", "Buckethandle": "a"}), 9: dict(cad="articulated/Scissors", groups=[("main", [1, 3], "Scissors", 9)], hands={2: "right"}, objmap={"scissors": "main", "scissors2": None}), # scissors2:场景道具,无掩码 11: dict(cad="articulated/Pliers", groups=[("main", [1, 3], "Pliers", 11)], hands={2: "right"}, objmap={"Pliersleft": "main", "Pliersright": "main"}), 12: dict(cad="rigid/Kettle", groups=[("main", [1], "Kettle", 12), ("mug", [3], "Mug", 2)], hands={2: "right"}, objmap={"kettle": "main"}), 13: dict(cad="rigid/Knife", groups=[("main", [1], "Knife", 13), ("apple", [3], "Apple", None)], hands={2: "right"}, objmap={"knife": "main"}), 14: dict(cad="articulated/TrashCan", groups=[("main", [1, 3], "Trash Can", 14), ("bottle", [4], "Bottle", 5)], hands={2: "right"}, objmap={"Dustbinbase": "main", "Dustbincover": "main"}), 17: dict(cad="articulated/Lamp", groups=[("main", [1, 3, 4, 5], "Lamp", 17)], hands={2: "right", 6: "left"}, objmap={"Lampbase": "main", "Tablelampfirstjoint": "main", "Tablelampsecondjoint": "main", "Thirdjointoftablelamp": "main"}), 18: dict(cad="articulated/Stapler", groups=[("main", [1, 3, 4], "Stapler", 18), ("paper", [5], "Paper", None)], hands={2: "right", 6: "left"}, # 6=左手:官方 label.csv 缺列,实测修正 objmap={"Staplerbase": "main", "Staplercover": "main"}), 20: dict(cad="rigid/Chair", groups=[("main", [1], "Chair", 20)], hands={2: "right", 3: "left"}, objmap={"chair": "main"}),}
# Official HOI4D definitions/motion segmentation/label.csv; no spatial side inference.REGION_NAMES = {1: {1: 'Toy Car', 2: 'Right Hand'}, 2: {1: 'Mug', 2: 'Right Hand', 3: 'Mug'}, 3: {1: 'Screen', 2: 'Right Hand', 3: 'Keyboard'}, 4: {1: 'Door', 2: 'Right Hand', 3: 'Body of the Cabinet', 4: 'Drawer', 5: 'Bottle'}, 5: {1: 'Bottle', 2: 'Right Hand', 3: 'Mug'}, 6: {1: 'Body of the Safe', 2: 'Right Hand', 3: 'Door', 4: 'Bottle'}, 7: {1: 'Bowl', 2: 'Right Hand', 3: 'Ball'}, 8: {1: 'Body of the Bucket', 2: 'Right Hand', 3: 'Handle', 4: 'Body of the Bucket', 5: 'Handle', 6: 'Left Hand'}, 9: {1: 'Left Part of the Scissors', 2: 'Right Hand', 3: 'Right Part of the Scissors'}, 11: {1: 'Left Part of the Pliers', 2: 'Right Hand', 3: 'Right Part of the Pliers'}, 12: {1: 'Kettle', 2: 'Right Hand', 3: 'Mug'}, 13: {1: 'Knife', 2: 'Right Hand', 3: 'Apple'}, 14: {1: 'Body of the Trash Can', 2: 'Right Hand', 3: 'Lid', 4: 'Bottle'}, 17: {1: 'Base', 2: 'Right Hand', 3: 'Tube', 4: 'Top Link', 5: 'Bottom Link', 6: 'Left Hand'}, 18: {1: 'Base', 2: 'Right Hand', 3: 'Slot', 4: 'Lid', 5: 'Paper'}, 20: {1: 'Chair', 2: 'Right Hand', 3: 'Left Hand'}}
class SplitFiles(io.RawIOBase): """Read concatenated source gzip parts without concatenating 119 GB on disk.""" def __init__(self, paths): self.paths = iter(paths) self.current = None
def readable(self): return True
def readinto(self, buffer): while True: if self.current is None: path = next(self.paths, None) if path is None: return 0 self.current = path.open('rb') n = self.current.readinto(buffer) if n: return n self.current.close() self.current = None
def close(self): if self.current is not None: self.current.close() super().close()
def extract_depths(root, sequences, work): directory = find_file(root, 'DEPTH') if directory is None: return {}, [] parts = sorted(directory.glob('HOI4D_depth_video.tar.gz*'), key=lambda p: int(p.name.split('.gz')[1] or 0)) if not parts: return {}, [] wanted = {f'HOI4D_depth_video/{seq}/align_depth/depth_video.avi': seq for seq in sequences} found = {} with SplitFiles(parts) as joined, io.BufferedReader(joined) as inp, gzip.GzipFile(fileobj=inp) as gz: with tarfile.open(fileobj=gz, mode='r|') as tf: for member in tf: if member.isfile() and member.name in wanted: seq = wanted[member.name] dest = work / (seq.replace('/', '_') + '.avi') with tf.extractfile(member) as src, dest.open('wb') as dst: shutil.copyfileobj(src, dst) found[seq] = (dest, {'files': [str(p.resolve()) for p in parts], 'member': member.name}) if len(found) == len(wanted): break return found, parts
def palette_mask(data): with Image.open(io.BytesIO(data)) as im: arr = np.asarray(im) if arr.ndim == 2: return arr.astype(np.uint16) if arr.shape[-1] != 3: raise ValueError('unsupported HOI4D mask representation') # VOC's 256-color palette interleaves eight label bits into the high RGB bits. # Invert it directly instead of sorting every pixel with np.unique. if np.any(arr & np.array([31, 31, 63], dtype=np.uint8)): raise ValueError('source mask has colors outside official VOC palette') mask = np.zeros(arr.shape[:2], dtype=np.uint16) for bit in range(8): mask |= ((arr[..., bit % 3] >> (7 - bit // 3)) & 1).astype(np.uint16) << bit return mask
# Four workers each reuse annotation and hand indices instead of rebuilding the ZIP directory.@lru_cache(maxsize=8)def index_frames(z): index = {} for name in z.namelist(): parent, _, filename = name.rpartition('/') stem, dot, suffix = filename.rpartition('.') if not dot or not stem.isdigit() or suffix not in ('png', 'json', 'pickle'): continue entries = index.setdefault((parent + '/', '.' + suffix), {}) f = int(stem) if f in entries: raise ValueError(f'duplicate frame number under {parent}') entries[f] = name return index
def frame_members(z, prefix, suffix): return index_frames(z).get((prefix, suffix), {})
def convert_sequence(seq, args, target, rgbz, annz, hpz, calz, cadz, paths, models, depth): # ponytail: cache only one sequence's encoded annotation bytes; no decoded masks or CAD cache. @lru_cache(maxsize=None) def read_annotation(archive, name): return archive.read(name)
category = int(re.search(r'/C(\d+)/', seq)[1]) definition = CATEGORIES.get(category) if definition is None: raise ValueError(f'category mapping unavailable: {category}') prefix = f'HOI4D_annotations/{seq}' mask_members = frame_members(annz, prefix + '/2Dseg/mask/', '.png') shifted = frame_members(annz, prefix + '/2Dseg/shift_mask/', '.png') if not mask_members: mask_members = shifted pose_members = frame_members(annz, prefix + '/objpose/', '.json') hand_members = {side: frame_members(hpz, f'Hand_pose/handpose_{side}_hand/{seq}/', '.pickle') for side in ('left', 'right')} if hpz else {'left': {}, 'right': {}} with tempfile.TemporaryDirectory(prefix='hoi4d-source-') as wd: work = Path(wd) member = f'HOI4D_release/{seq}/align_rgb/image.mp4' video = work / 'rgb.mp4' with rgbz.open(member) as src, video.open('wb') as dst: shutil.copyfileobj(src, dst) info = probe(video) if 'nb_frames' not in info: info['nb_frames'] = json.loads(run(['ffprobe', '-v', 'error', '-count_frames', '-select_streams', 'v:0', '-show_entries', 'stream=nb_read_frames', '-of', 'json', str(video)], stdout=subprocess.PIPE).stdout)['streams'][0]['nb_read_frames'] n = int(info['nb_frames']) if args.max_frames: n = min(n, args.max_frames) if shifted and mask_members != shifted and any(f not in mask_members and f in shifted for f in range(n)): raise ValueError('shift_mask has frames absent from mask; correspondence unverified') frames = [] for f in range(n): sources = {} if f in mask_members: sources['segment'] = locator(paths['annotations'], mask_members[f], read_annotation(annz, mask_members[f])) if f in pose_members: sources['object'] = locator(paths['annotations'], pose_members[f], read_annotation(annz, pose_members[f])) for side in ('left', 'right'): if f in hand_members[side]: sources['hand_' + side] = locator(paths['hand'], hand_members[side][f], read_annotation(hpz, hand_members[side][f])) frames.append(dict(source_frame_id=f, source_locator=locator(paths['release'], member, frame=f), component_sources=sources, annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, clock_domain=None, match_method='index_map', delta_ns=None) for k in sources})) view = View(target, 'HOI4D', args.release_id, seq.replace('/', '_'), 'ego', frames) view.valid_rules = { 'mano': 'Matched side pickle contains poseCoeff, beta, trans and corresponding model available; zero angles are not missing', 'keypoints': 'Matched side pickle contains kps2D; independently provided source points, no visibility gate', 'pose': 'Matched source object record contains rotation and center; record identity retained', 'dimensions': 'Matched source object record contains dimensions; size/mesh relation remains source_unspecified', 'segment': 'Source mask or shift_mask present with verified palette codes and entity/part mapping', } view.full_jpeg = getattr(args, 'jpeg_full_check', False) view.meta['view_type'] = 'ego' view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'source_sequence': seq} view.rgb([], locator(paths['release'], member), video=video, count=n) intr_name = f'camera_params/{seq.split("/")[0]}/intrin.npy' if calz and intr_name in calz.namelist(): view.camera(np.load(io.BytesIO(calz.read(intr_name))), locator(paths['camera'], intr_name)) extr_name = prefix + '/3Dseg/output.log' if extr_name in annz.NameToInfo: lines = [line for line in annz.read(extr_name).decode().splitlines() if line.strip()] if len(lines) % 5: raise ValueError('invalid Open3D camera trajectory') extr, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) for i in range(0, len(lines), 5): idx = int(lines[i].split()[0]) if idx < n: if valid[idx]: raise ValueError('duplicate trajectory index') extr[idx] = np.linalg.inv(np.loadtxt(io.StringIO('\n'.join(lines[i + 1:i + 5])))) valid[idx] = True view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', extr, valid, ['T', 'row', 'column'], locator(paths['annotations'], extr_name), convention='T_camera_from_world', source_convention='Open3D LOG camera-to-world; inverted') loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) points, pv = np.full((n, 2, 21, 2), np.nan, np.float32), np.zeros((n, 2, 21), bool) for slot, side in enumerate(('left', 'right')): for f, name in hand_members[side].items(): if f >= n: continue data = pickle.loads(read_annotation(hpz, name), encoding='latin1') if all(k in data for k in ('poseCoeff', 'beta', 'trans')): motion[f, slot] = np.r_[np.asarray(data['poseCoeff']).reshape(48), np.asarray(data['beta']).reshape(10), np.asarray(data['trans']).reshape(3)] mv[f, slot] = True # Zero angles are a valid pose, not a missing sentinel. if 'kps2D' in data: points[f, slot] = np.asarray(data['kps2D']).reshape(21, 2) pv[f, slot] = True if mv.any(): if all(side in models for slot, side in enumerate(('left', 'right')) if mv[:, slot].any()): view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) else: view.absent('mano', 'Source MANO exists; provide --mano-dir to fix model identity', 'dependency_missing') if pv.any(): view.tensor('keypoints_uv', 'keypoints/uv/v1', 'annotation/keypoints/uv.pt', points, pv, ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='pixel', source_method='Upstream fitted MANO projection already present in kps2D') objects = {} groups = {key: (vals, name, cls) for key, vals, name, cls in definition['groups']} def ensure_object(key, source_loc, category_id=None, frame=None, source_id=None): if key not in objects: view.object(key, source_loc, scope='frame' if frame is not None else 'sequence', scope_id=f'{seq}:{frame}' if frame is not None else None, category_id=category_id, source_object_id=source_id) objects[key] = {} mappings = [] mask_valid = [f in mask_members for f in range(n)] if any(mask_valid): width, height = view.meta['camera']['image_size'] def masks(): for f in range(n): labels = [] if f in mask_members: mask = palette_mask(read_annotation(annz, mask_members[f])) for value in np.unique(mask): value = int(value) if value in (0, 255): if value == 255: raise ValueError('HOI4D 255 region semantics unverified') continue if REGION_NAMES[category].get(value) in ('Left Hand', 'Right Hand'): entity, part, cls = 'hand_' + REGION_NAMES[category][value].split()[0].lower(), None, 'hand' else: group = next((k for k, (vals, _, _) in groups.items() if value in vals), None) entity = group or f'unknown_region_{value}' cls = groups[group][2] if group else None part = f'region_{value}' if group and len(groups[group][0]) > 1 else None ensure_object(entity, frames[f]['component_sources']['segment'], cls) if part: objects[entity].setdefault('parts', {})[part] = {'part_id': part, 'parent_id': None, 'has_model': False, 'mesh_ref': None, 'source_region_code': value, 'name': REGION_NAMES[category].get(value)} labels.append(dict(mask_value=value, category_id=cls, entity_id=entity, part_id=part, source_instance_id=value, source_attributes={'region_name': REGION_NAMES[category].get(value)})) else: mask = np.zeros((height, width), np.uint16) mappings.append(dict(frame_index=f, labels=labels)) yield mask view.raster('segment', masks(), mask_valid, loc, mappings) view.meta['components']['segment']['coverage'] = {'kind': 'unknown'} if any(label['part_id'] for row in mappings for label in row['labels']): view.meta['components']['segment']['segmentation_type'] = 'part' else: view.absent('segment', 'No native segmentation for this source sequence') records = {} for f, name in pose_members.items(): if f >= n: continue data = json.loads(read_annotation(annz, name)) # isEffective is not used to erase existing numerical annotations. source_records = data.get('dataList', data.get('objects')) if source_records is None: raise ValueError('unrecognized source object annotation structure') if category == 2 and source_records and (len(source_records) != 1 or source_records[0].get('id') != 1 or source_records[0].get('label') != 'Watercup'): raise ValueError('C2 native pose differs from the verified one-object target; cannot map to mask region 1') label_counts = Counter(record['label'] for record in source_records) per_frame = set() for record_index, record in enumerate(source_records): label = record['label'] group = definition['objmap'].get(label) # Pinned official ObjTracking reads dataList[0] with segmentation label 1. source_primary = category == 2 and record_index == 0 and record.get('id') == 1 and group == 'a' ambiguous = group is not None and sum(g[2] == groups[group][2] for g in groups.values()) > 1 and not source_primary ambiguous = ambiguous or (label_counts[label] > 1 and not source_primary) or group is None entity = f'pose_frame_{f}_{record_index}' if ambiguous else group ensure_object(entity, locator(paths['annotations'], name, record=record_index), groups[group][2] if group else None, frame=f if ambiguous else None, source_id=record.get('id')) if ambiguous: view.build['unresolved'].append({'component': entity, 'status': 'source_semantics_unverified', 'reason': 'Source pose retained with frame identity; no guessed association to same-class mask instances'}) label_key = (entity, label) if label_key in per_frame: raise ValueError(f'ambiguous repeated object label {label}; source identity must be resolved') per_frame.add(label_key) records.setdefault(label_key, {})[f] = (record, locator(paths['annotations'], name, record=record.get('id'))) if category == 2 and any(entity == 'a' for entity, _ in records): view.build['validation'].append({'component': 'C2_source_pose_mask_identity', 'rule': 'Official ObjTracking process_data.py reads dataList[0] with semantic mask label 1', 'source_revision': 'afa7bf37b02b7e33cf245acd08b98c207ccc175c', 'source_pose_id': 1, 'mask_value': 1, 'matched_frames': sum(len(by_frame) for (entity, _), by_frame in records.items() if entity == 'a')}) for (entity, label), by_frame in records.items(): part_labels = [k[1] for k in records if k[0] == entity] articulated = definition['cad'].startswith('articulated/') and entity == definition['groups'][0][0] part = 'pose_' + re.sub(r'[^a-zA-Z0-9_]', '_', label) if articulated or len(part_labels) > 1 else None base = f'annotation/object/{entity}' if part: base += '/parts/' + part objects[entity].setdefault('parts', {})[part] = dict(part_id=part, parent_id=None, has_model=False, mesh_ref=None, source_label=label) poses, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) dimensions = np.full((n, 3), np.nan, np.float32) dv = np.zeros(n, bool) for f, (record, _) in by_frame.items(): if all(k in record for k in ('rotation', 'center')): poses[f] = np.eye(4) poses[f, :3, :3] = Rotation.from_euler('XYZ', [record['rotation'][k] for k in ('x', 'y', 'z')]).as_matrix() poses[f, :3, 3] = [record['center'][k] for k in ('x', 'y', 'z')] valid[f] = True if 'dimensions' in record: dimensions[f] = [record['dimensions'][k] for k in ('length', 'width', 'height')] dv[f] = True key = entity + ('_' + part if part else '') view.tensor('pose_' + key, 'transform/se3/v1' if part else 'object/rigid/v1', base + '/pose.pt', poses, valid, ['T', 'row', 'column'], loc, convention='T_camera_from_part' if part else 'T_camera_from_object', unit='m', source_label=label, source_euler_order='XYZ', definition='https://github.com/hoi4d/ObjTracking/blob/main/process_data.py') if dv.any(): view.tensor('dimensions_' + key, 'object/dimensions/v1', base + '/dimensions.pt', dimensions, dv, ['T', 'dimension'], loc, dimensions_semantics='source_unspecified', unit='m', scale_applied_to_mesh=False) if cadz: primary = definition['groups'][0][0] if category != 2 and sum(g[2] == category for g in groups.values()) > 1: primary = 'source_cad_instance' instance = int(re.search(r'/N(\d+)/', seq)[1]) mesh_prefix = f'HOI4D_CAD_Model_for_release/{definition["cad"]}/{instance:03d}' candidates = [name for name in cadz.namelist() if not name.endswith('/') and (name == mesh_prefix + '.obj' or name.startswith(mesh_prefix + '/'))] if candidates: # Retain OBJ material/texture dependencies beside their original names. queue = list(candidates) for name in queue: if Path(name).suffix.lower() not in ('.obj', '.mtl'): continue for line in cadz.read(name).decode().splitlines(): fields = shlex.split(line, comments=True) if not fields: continue refs = fields[1:] if fields[0] == 'mtllib' else ([fields[-1]] if fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal') else []) for ref in refs: dependency = posixpath.normpath(posixpath.join(posixpath.dirname(name), ref)) if dependency not in cadz.NameToInfo: raise ValueError(f'missing CAD dependency: {dependency}') if dependency not in candidates: candidates.append(dependency) queue.append(dependency) ensure_object(primary, locator(paths['cad'], mesh_prefix), category) asset_dir = view.path / f'annotation/object/{primary}/assets' asset_refs = [] for name in candidates: relative = posixpath.relpath(name, mesh_prefix if definition['cad'].startswith('articulated/') else posixpath.dirname(mesh_prefix)) dest = safe_member(asset_dir, relative) dest.parent.mkdir(parents=True, exist_ok=True) dest.write_bytes(cadz.read(name)) ref = dest.relative_to(view.path).as_posix() if dest.suffix.lower() == '.obj': asset_key = re.sub(r'[^a-zA-Z0-9_]', '_', relative) view.component('mesh_' + primary + '_' + asset_key, 'mesh/obj/v1', ref, ['vertex'], locator(paths['cad'], name), unit='m', valid=True, scale_applied_to_mesh=False, dimensions_semantics='source_unspecified') asset_refs.append(ref) if definition['cad'].startswith('articulated/'): part_id = 'asset_' + asset_key objects[primary].setdefault('parts', {})[part_id] = dict(part_id=part_id, parent_id=None, has_model=True, mesh_ref=ref, source_asset=relative, note='Source asset; correspondence to motion part labels remains unverified') for asset_ref in asset_refs: mesh_check = check_mesh(view.path / asset_ref, asset_dir) view.build['validation'].append({'component': asset_ref, **mesh_check, 'unit_basis': 'official ObjTracking loads source canonical CAD without scaling in metre camera coordinates', 'geometric_acceptance': 'physical dimensions-to-mesh relation remains source_unspecified'}) metadata_path = view.path / f'annotation/object/{primary}/metainfo.json' metadata = json.loads(metadata_path.read_text()) metadata.update(has_model=bool(asset_refs), asset_refs=asset_refs) if definition['cad'].startswith('rigid/') and len(asset_refs) == 1: metadata['mesh_ref'] = asset_refs[0] json_write(metadata_path, metadata) if definition['cad'].startswith('articulated/'): view.build['unresolved'].append({'component': 'object_part_asset_association', 'status': 'source_semantics_unverified', 'reason': 'All source assets and motion labels retained, but no guessed correspondence or joint_state'}) for entity, info in objects.items(): if 'parts' in info: ref = f'annotation/object/{entity}/articulation.json' json_write(view.path / ref, {'parts': list(info['parts'].values()), 'joints': [], 'hierarchy_semantics': 'semantic_containment', 'note': 'Unassociated source region, motion and asset nodes; original CAD trees retained in assets'}) view.component('articulation_' + entity, 'object/articulated/v1', ref, [], loc) meta_path = view.path / f'annotation/object/{entity}/metainfo.json' metadata = json.loads(meta_path.read_text()) metadata['articulation_ref'] = ref json_write(meta_path, metadata) if depth is not None: dpath, dloc = depth dmeta = probe(dpath) if [dmeta['width'], dmeta['height']] != view.meta['camera']['image_size']: raise ValueError('HOI4D depth grid differs from RGB') if dmeta['pix_fmt'] != 'gray16le': raise ValueError('unexpected HOI4D depth pixel format') width, height = view.meta['camera']['image_size'] raw = work / 'depth.raw' limits = ['-frames:v', str(n)] if args.max_frames else [] run(decode_args(dpath, 'gray16le') + limits + ['-y', str(raw)]) if raw.stat().st_size != n * width * height * 2: raise ValueError('depth/RGB frame count or grid mismatch') def depths(): with raw.open('rb') as inp: for _ in range(n): yield np.frombuffer(inp.read(width * height * 2), '<u2').reshape(height, width).astype(np.float32) / 1000 view.raster('depth', depths(), None, dloc | {'conversion': 'registered millimetre camera-Z to metres'}) else: if find_file(args.root, 'DEPTH'): raise ValueError('DEPTH source exists, but no matching depth video was found') view.absent('depth', 'Depth source not downloaded', 'not_downloaded') return view.finish()
def main(argv=None): p = parser('HOI4D', __doc__) p.set_defaults(release_id='shared-v1.0') # Four workers reached 21 observed OS threads including timing; stay below the 24-thread budget. p.add_argument('--workers', type=int, choices=range(1, 5), default=1, help='Independent views in parallel, 1..4; codec/BLAS threads fixed at 1') p.add_argument('--tasks', help='Comma-separated substrings of source sequence paths') p.add_argument('--sessions', help='Comma-separated sessions') p.add_argument('--categories', help='Comma-separated category numbers') args = p.parse_args(argv) if args.views and args.views != 'ego': p.error('HOI4D source camera ID is ego') paths = {key: find_file(args.root, name) for key, name in { 'release': 'HOI4D_release.zip', 'annotations': 'HOI4D_annotations.zip', 'hand': 'HOI4D_Hand_pose.zip', 'camera': 'camera_params.zip', 'cad': 'HOI4D_CAD_Model_for_release.zip'}.items()} if not paths['release'] or not paths['annotations']: p.error('HOI4D release and annotation ZIPs are required') out = release(args, 'HOI4D') mapping = Path(__file__).resolve().parent.parent / 'docs/hoi4d-RAW_TO_SHARED.md' published_mapping = out / 'doc/RAW_TO_SHARED.md' if published_mapping.exists() and published_mapping.read_bytes() != mapping.read_bytes(): raise ValueError('RAW_TO_SHARED.md changed; choose a new release-id') if not published_mapping.exists(): shutil.copyfile(mapping, published_mapping) torch.set_num_threads(1) models = mano_models(args.mano_dir) with ExitStack() as stack, tempfile.TemporaryDirectory(prefix='hoi4d-depth-') as wd: archives = {key: stack.enter_context(zipfile.ZipFile(path)) if path else None for key, path in paths.items()} sequences = sorted(name.removeprefix('HOI4D_release/').removesuffix('/align_rgb/image.mp4') for name in archives['release'].namelist() if name.endswith('/align_rgb/image.mp4')) if args.tasks: sequences = [s for s in sequences if any(token in s for token in args.tasks.split(','))] if args.sessions: sequences = [s for s in sequences if s.split('/')[0] in args.sessions.split(',')] if args.categories: sequences = [s for s in sequences if re.search(r'/C(\d+)/', s)[1] in args.categories.split(',')] if args.limit: sequences = sequences[:args.limit] if not sequences: p.error('no matching source sequences') depths, _ = extract_depths(args.root, sequences, Path(wd)) worker = threading.local() worker_stacks = [] def init_worker(): owned = ExitStack() try: # ZipFile.read mutates a shared seek position: never share a handle across workers. worker.archives = {key: owned.enter_context(zipfile.ZipFile(path)) if path else None for key, path in paths.items()} index_frames(worker.archives['annotations']) if worker.archives['hand']: index_frames(worker.archives['hand']) except BaseException: owned.close() raise worker_stacks.append(owned) def convert_one(seq): source = archives if args.workers == 1 else worker.archives name = seq.replace('/', '_') with sequence_dir(out, name) as target: report = convert_sequence(seq, args, target / 'ego', source['release'], source['annotations'], source['hand'], source['camera'], source['cad'], paths, models, depths.get(seq)) build_record(out, name, {'ego': report}) return seq if args.workers == 1: for seq in map(convert_one, sequences): print(f'Converted {seq}', flush=True) else: try: with ThreadPoolExecutor(max_workers=args.workers, initializer=init_worker) as pool: for seq in pool.map(convert_one, sequences): print(f'Converted {seq}', flush=True) finally: for owned in worker_stacks: owned.close() return 0
if __name__ == '__main__': raise SystemExit(main())
# TODO(v2.0): 旧 bbox IoU 实例重分配属于推断,注释保留,不在 v1.0 执行。# # 同类多实例(C8 双桶 / C2 双杯):2dBox 可用时按 IoU 复核归属# cls = next(x[3] for x in cat["groups"] if x[0] == gk)# sibs = [g for g in cat["groups"]# if g[0] != gk and cls is not None and g[3] == cls]# box = (d.get("2dBox") or {}).get("camera1")# box = (box[0][0], box[0][1], box[1][0], box[1][1]) \# if box and len(box) == 2 else None# if box is not None and sibs:# gvals = next(x[1] for x in cat["groups"] if x[0] == gk)# best, best_iou = gk, box_iou(box, bbox_of(mask, gvals))# for s in sibs:# if ("obj", s[0]) not in tid_of_group:# continue# i = box_iou(box, bbox_of(mask, s[1]))# if i > best_iou + 0.1 and i > 0.15:# best, best_iou = s[0], i# if best != gk:# gk, iou_fixups = best, iou_fixups + 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271#!/usr/bin/env python3"""VISOR source polygons and contact → CONTRACT.md v1.0, without rasterization or side inference."""from collections import Counterimport hashlibimport jsonimport reimport shutilimport tempfilefrom pathlib import Pathimport zipfile
import numpy as npimport torch
from warehouse_v1_0 import (View, build_record, find_file, jsonl_write, locator, parser, release, roots, sequence_dir, source)
FRAME = re.compile(r'frame_(\d+)')HAND = {300: 'left', 301: 'right'}GLOVE = {303: 'left', 304: 'right'}STATES = {'hand-not-in-contact': 'negative', 'glove-not-in-contact': 'negative', 'none-of-the-above': 'target_unannotated', 'inconclusive': 'unknown'}
def hand_side(ann): if ann['class_id'] in HAND: return HAND[ann['class_id']] if ann['class_id'] not in (60, 303, 304): return None raw = ann.get('on_which_hand') raw = raw if isinstance(raw, list) else [raw] sides = set() for item in raw: if item == 'left hand': sides.add('left') if item in ('right hand', 'rigth hand'): sides.add('right') if len(sides) == 1: return next(iter(sides)) if not sides and ann['class_id'] in GLOVE: return GLOVE[ann['class_id']] return None
def convert_video(video, split, annotation, ann_loc, rgb_zip, rgb_loc, mapping, args, target): indexed = sorted(enumerate(annotation['video_annotations']), key=lambda row: int(FRAME.search(row[1]['image']['name'])[1])) if args.max_frames: indexed = indexed[:args.max_frames] if len({row['image']['name'] for _, row in indexed}) != len(indexed): raise ValueError('duplicate VISOR frame') keys = lambda row, ann: (row['image']['subsequence'], ann['class_id'], ann['name']) collisions = set() for _, row in indexed: collisions.update(key for key, number in Counter(keys(row, a) for a in row['annotations']).items() if number > 1) frames, paths = [], [] with tempfile.TemporaryDirectory(prefix='visor-rgb-') as wd, zipfile.ZipFile(rgb_zip) as z: work = Path(wd) for original_index, row in indexed: name = row['image']['name'] data = z.read(name) path = work / Path(name).name path.write_bytes(data) paths.append(path) loc = rgb_loc | {'nested_member': name, 'sha256': hashlib.sha256(data).hexdigest()} frames.append(dict(source_frame_id=int(FRAME.search(name)[1]), source_locator=loc, source_image=row['image'], original_frame_name=mapping.get(name), annotation_matches={'segment': dict(source_frame_id=name, source_timestamp_ns=None, clock_domain=None, match_method='index_map', delta_ns=None, source_locator=ann_loc | {'record': f'video_annotations[{original_index}]'})})) view = View(target, 'EPIC-KITCHENS-VISOR', args.release_id, video, 'ego', frames, sampling='sparse', split=split) view.valid_rules = { 'segment': 'Selected sparse annotation frame present; all source polygons finite with at least three vertices and entity mapping valid', 'relations': 'At least one source in_contact_object value present; positive targets resolve in the same frame; unknown is an explicit usable status', } view.full_jpeg = getattr(args, 'jpeg_full_check', False) view.meta.update(view_type='ego', split_scheme='VISOR_GroundTruth_SparseAnnotations', split_source_locator=ann_loc) view.meta['sampling']['selection'] = {'representation': 'official sparse annotations', 'max_frames': args.max_frames} view.rgb(paths, rgb_loc) entities = {} polygons, mappings, relations, relation_valid = [], [], [], [] for f, (original_index, row) in enumerate(indexed): frame_loc = ann_loc | {'record': f'video_annotations[{original_index}]'} id_map, labels, polys = {}, [], [] for code, ann in enumerate(row['annotations'], 1): if code >= 65535: raise ValueError('too many source instances') sid = ann['id'] if sid in id_map: raise ValueError('duplicate source instance ID within a frame') side = hand_side(ann) if side is not None: entity = 'hand_' + side else: key = keys(row, ann) identity = key + (sid, row['image']['name']) if key in collisions else key entity = 'object_' + hashlib.sha256(json.dumps(identity).encode()).hexdigest()[:20] if entity not in entities: scope = 'frame' if key in collisions else 'subsequence' scope_id = f'{video}:{row["image"]["name"]}' if scope == 'frame' else f'{video}:{key[0]}' view.object(entity, frame_loc | {'source_instance_id': sid}, scope, scope_id, category_id=ann['class_id'], name=ann['name'], association_basis='source_frame_instance' if scope == 'frame' else 'official_subsequence_entity_name') entities[entity] = True id_map[sid] = entity for polygon in ann.get('segments', []): p = np.asarray(polygon) if p.ndim != 2 or p.shape[1] != 2 or len(p) < 3 or not np.isfinite(p).all(): raise ValueError(f'invalid source polygon {sid}') polys.append(dict(mask_value=code, polygons=ann.get('segments', []))) labels.append(dict(mask_value=code, category_id=ann['class_id'], entity_id=entity, part_id=None, source_instance_id=sid, source_attributes={k: v for k, v in ann.items() if k != 'segments'})) rr = [] provided = False for ann in row['annotations']: raw = ann.get('in_contact_object') values = raw if isinstance(raw, list) else [raw] for value in values: if value is None: continue provided = True status = STATES.get(value) obj = None if status is None: if value not in id_map: raise ValueError(f'unresolved source contact target {value} in {video} frame {f}') status, obj = 'positive', id_map[value] rr.append(dict(relation_type='contact', subject_id=id_map[ann['id']], object_id=obj, status=status, source_value=value, source_locator=frame_loc | {'source_instance_id': ann['id']}, provenance=source('Resolve source contact ID against instances in this frame'))) polygons.append(dict(frame_index=f, instances=polys)) mappings.append(dict(frame_index=f, labels=labels)) relations.append(dict(frame_index=f, relations=rr)) relation_valid.append(provided) jsonl_write(view.path / 'annotation/segment/polygons.jsonl', polygons) jsonl_write(view.path / 'annotation/segment/instances.jsonl', mappings) torch.save(torch.ones(len(frames), dtype=torch.bool, device='cpu'), view.path / 'annotation/segment/mask_valid.pt') view.component('segment', 'segment/instance_polygons/v1', 'annotation/segment/polygons.jsonl', ['T'], ann_loc, valid_ref='annotation/segment/mask_valid.pt', valid_axes=['T'], segmentation_type='instance', mapping_ref='annotation/segment/instances.jsonl', coverage={'kind': 'unknown', 'exhaustive_ref': 'annotation/segment/instances.jsonl'}) view.relations(relations, relation_valid, ann_loc) for component in ('depth', 'mano', 'keypoints_uv', 'keypoints_xyz', 'intrinsic', 'extrinsic'): view.absent(component, 'Not provided by VISOR sparse source annotations') return view.finish()
def main(argv=None): p = parser('EPIC-KITCHENS-VISOR', __doc__) p.add_argument('--videos', help='Comma-separated video names') p.add_argument('--splits', default='train,val') args = p.parse_args(argv) wanted = set(args.videos.split(',')) if args.videos else None splits = set(args.splits.split(',')) if not splits <= {'train', 'val'}: p.error('only annotated train/val splits are available') out = release(args, 'EPIC-KITCHENS-VISOR') archive = find_file(args.root, 'EPIC-KITCHENS VISOR.zip') with tempfile.TemporaryDirectory(prefix='visor-source-') as wd: work = Path(wd) if archive: with zipfile.ZipFile(archive) as z: suffix = 'GroundTruth-SparseAnnotations/annotations/' members = [n for n in z.namelist() if suffix in n and n.endswith('.json')] prefix = members[0].split(suffix)[0] fm = json.loads(z.read(prefix + 'frame_mapping.json')) done = 0 for member in sorted(members): split, filename = member.split(suffix)[1].split('/') video = Path(filename).stem if split not in splits or wanted and video not in wanted: continue data = z.read(member) rgb_member = prefix + f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' rgb_zip = work / (video + '.zip') with z.open(rgb_member) as inp, rgb_zip.open('wb') as dest: shutil.copyfileobj(inp, dest) with sequence_dir(out, video) as dest: report = convert_video(video, split, json.loads(data), locator(archive, member, data), rgb_zip, locator(archive, rgb_member), fm.get(video, {}), args, dest / 'ego') build_record(out, video, {'ego': report}) rgb_zip.unlink() done += 1 print(f'Converted {video}', flush=True) if args.limit and done >= args.limit: break else: root = next((r for r in roots(args.root) if (r / 'GroundTruth-SparseAnnotations').is_dir()), None) if root is None: p.error('VISOR outer ZIP or extracted source directory not found') fm = json.loads((root / 'frame_mapping.json').read_text()) if (root / 'frame_mapping.json').exists() else {} done = 0 for split in sorted(splits): for ann in sorted((root / 'GroundTruth-SparseAnnotations/annotations' / split).glob('*.json')): video = ann.stem if wanted and video not in wanted: continue rgb = root / f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' with sequence_dir(out, video) as dest: report = convert_video(video, split, json.loads(ann.read_text()), locator(ann), rgb, locator(rgb), fm.get(video, {}), args, dest / 'ego') build_record(out, video, {'ego': report}) done += 1 if args.limit and done >= args.limit: return 0 if not done: p.error('no matching annotated videos found') return 0
if __name__ == '__main__': raise SystemExit(main())
# TODO(v2.0): 旧距离猜侧和单层掩码生成仅注释保留;v1.0 不执行。# if side is None and len(frame_hands) == 1:# # 空间门槛:脱下放在远处的手套不并入(实测双峰 0..25px / ≥44px)# hb = frame_hands[0][1]# gb = _bbox_of(polys)# if hb and gb and _bbox_dist(gb, hb) <= GLOVE60_MERGE_BBOX_DIST:# side = frame_hands[0][0]# stats["glove60_merged_into_sole_hand"] += 1# if side is None:# stats["dropped_glove60_unresolved"] += 1# id_disp[mid] = ("dropped", "glove60")# continue# def rasterize_and_encode(vdir, frames, frame_draw, zip_path, n, stats):# """流式读 zip 内 jpg + 光栅化多边形 → rgb.mkv / mask.mkv;返回 (w, h)。"""# from PIL import Image, ImageDraw## with zipfile.ZipFile(zip_path) as zf:# member_of = {}# for nm in zf.namelist():# member_of[os.path.basename(nm)] = nm# names = [im["name"] for im in frames]# missing = [nm for nm in names if nm not in member_of]# if missing:# raise RuntimeError(f"{len(missing)} annotated frames missing in zip, "# f"e.g. {missing[:3]}")# stats["zip_extra_members"] = len(member_of) - len(names)## # 首帧定分辨率(官方 1920×1080,实测每帧校验)# img0 = Image.open(io.BytesIO(zf.read(member_of[names[0]]))).convert("RGB")# w, h = img0.size## bin_img = Image.new("L", (w, h), 0)# bin_draw = ImageDraw.Draw(bin_img)# canvas = np.zeros((h, w), np.uint16)# with VideoPipe(vdir / "mask.mkv", w, h, FPS, "mask") as mw, \# VideoPipe(vdir / "rgb.mkv", w, h, FPS, "rgb") as rw:# for f in range(n):# canvas[:] = 0# for pid, polys in frame_draw[f]:# bin_draw.rectangle((0, 0, w, h), fill=0)# for poly in polys:# bin_draw.polygon([(float(x), float(y)) for x, y in poly], fill=255)# arr = np.asarray(bin_img)# canvas[arr > 0] = pid # 后画覆盖先画:物体→手(modal)# mw.write(canvas)# img = img0 if f == 0 else Image.open(# io.BytesIO(zf.read(member_of[names[f]]))).convert("RGB")# if img.size != (w, h):# raise RuntimeError(f"frame {names[f]}: size {img.size} != {(w, h)}")# rw.write(np.asarray(img))# n_mask, n_rgb = mw.n, rw.n# if (n_rgb, n_mask) != (n, n):# raise RuntimeError(f"wrote rgb={n_rgb} mask={n_mask} != {n}")# got = (count_frames(vdir / "rgb.mkv"), count_frames(vdir / "mask.mkv"))# if got != (n, n):# raise RuntimeError(f"encoded rgb={got[0]} mask={got[1]} != {n} (decode verify)")# return w, h##1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374"""Benchmark full FFV1 decodes, PNG RGB decodes, and source depth PNG loading; preserve every byte."""import hashlibimport jsonimport osfrom pathlib import Pathimport statisticsimport subprocessimport timefrom concurrent.futures import ThreadPoolExecutorimport numpy as npfrom PIL import Image
old = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10')bench = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-decode-bench-20260930')bench.mkdir(exist_ok=True)media = next((old / 'H2O/shared-v1.0/data').glob('subject4_h1_0*/cam0/observation/rgb.mkv')).parentinputs = bench / 'inputs'inputs.mkdir(exist_ok=True)for name in ('rgb.mkv', 'depth.mkv', 'depth_valid.mkv'): dest = inputs / name if not dest.exists(): os.link(media / name, dest)source = next((old / 'scratch').glob('h2o-source-*/subject4/h1/0/cam0/rgb')).parentfor kind in ('rgb', 'depth'): dest = inputs / kind dest.mkdir(exist_ok=True) for frame in sorted((source / kind).glob('*.png'))[:100]: if not (dest / frame.name).exists(): os.link(frame, dest / frame.name)records = []expected = {}def record(stage, threads, digest, size, seconds): assert expected.setdefault(stage, (digest, size)) == (digest, size), stage row = dict(stage=stage, threads=threads, seconds=seconds, sha256=digest, bytes=size) records.append(row) print(json.dumps(row), flush=True) (bench / 'report.json').write_text(json.dumps(records, indent=2) + '\n')def decode(stage, arguments, threads, pix_fmt): cmd = ['ffmpeg','-v','error','-nostdin','-filter_threads',str(threads),'-threads',str(threads), '-noautorotate',*arguments,'-map','0:v:0','-vsync','0','-threads',str(threads), '-f','rawvideo','-pix_fmt',pix_fmt,'pipe:1'] digest = hashlib.sha256() size = 0 start = time.monotonic() with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc: while chunk := proc.stdout.read(1024*1024): digest.update(chunk) size += len(chunk) stderr = proc.stderr.read() assert proc.wait() == 0, stderr.decode() record(stage, threads, digest.hexdigest(), size, time.monotonic()-start)for threads in (1,10,10,1): for name, pix in (('rgb','rgb24'),('depth','gray16le'),('depth_valid','gray')): decode('ffv1_'+name, ['-i',str(inputs/(name+'.mkv'))], threads, pix) decode('source_rgb_png_100', ['-framerate','30','-i',str(inputs/'rgb/%06d.png')], threads, 'rgb24') files = sorted((inputs/'depth').glob('*.png')) def read(path): with Image.open(path) as im: return np.asarray(im).astype(np.float32)/1000.0 for depth_threads in (1,2,4): digest = hashlib.sha256() start = time.monotonic() size = 0 with ThreadPoolExecutor(max_workers=depth_threads) as pool: # Bound decoded arrays to one small batch, as the production candidate would. for begin in range(0,len(files),depth_threads): for arr in pool.map(read,files[begin:begin+depth_threads]): digest.update(arr.tobytes()) size += arr.nbytes record('source_depth_png_100', depth_threads, digest.hexdigest(), size, time.monotonic()-start)print('MEDIANS',flush=True)for stage in expected: for threads in sorted({r['threads'] for r in records if r['stage']==stage}): print(stage,threads,statistics.median(r['seconds'] for r in records if r['stage']==stage and r['threads']==threads),flush=True)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455"""Reuse only atomically published sequences; preserve previous runtime provenance."""import datetimeimport jsonimport osfrom pathlib import Pathimport shutil
old = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10')new = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10')snapshot = Path('/tmp/h2o-w4-c10-d10-recovery')new.mkdir()shutil.copytree(snapshot, new / 'frozen-code')release = new / 'H2O/shared-v1.0'for directory in ('data', 'doc/validation', 'script/provenance/previous-run', 'script/provenance/operations'): (release / directory).mkdir(parents=True, exist_ok=True)history = release / 'script/provenance/previous-run'shutil.copytree(old / 'H2O/shared-v1.0/script', history / 'script')shutil.copytree(old / 'frozen-code/docs', history / 'docs')for name in ('full.log', 'full.status', 'run-full.sh'): shutil.copy2(old / name, history / name)records = []for record in sorted((old / 'H2O/shared-v1.0/doc').glob('*.build.json')): build = json.loads(record.read_text()) seq = build['sequence_id'] assert Path(seq).name == seq and seq not in ('.', '..') assert set(build['views']) == {f'cam{i}' for i in range(5)}, seq data = old / 'H2O/shared-v1.0/data' / seq frames = {} for cam in build['views']: json.loads((data / cam / 'metainfo.json').read_text()) frames[cam] = sum(1 for _ in (data / cam / 'camera/frames.jsonl').open()) assert frames[cam] > 0 shutil.copytree(data, release / 'data' / seq, copy_function=os.link) shutil.copy2(record, release / 'doc' / record.name) records.append({'sequence_id': seq, 'frames_by_camera': frames, 'original_script_sha256': build['scripts']})manifest = {'time': datetime.datetime.now().astimezone().isoformat(), 'source_run': str(old), 'destination_run': str(new), 'configuration': {'workers': 4, 'codec_threads': 10, 'decode_threads': 10, 'depth_threads': 4, 'cpu_limit': None}, 'reuse': 'Hard-linked immutable completed views; source timeline/SHA256 still rechecked without staging published source frames', 'excluded': 'Unpublished .tmp directories; historical 62-sequence output', 'original_runtime_provenance': 'script/provenance/previous-run', 'sequences': records}(release / 'doc/RESTART_PROVENANCE.json').write_text(json.dumps(manifest, indent=2) + '\n')operations = release / 'script/provenance/operations'for name in ('h2o-prepare-d10.py', 'h2o-switch-d10.sh', 'h2o-benchmark-decode.py'): shutil.copy2(Path('/tmp') / name, operations / name)for src, dest in (('/tmp/h2o-run-d10.sh', new / 'run-full.sh'), ('/tmp/h2o-run-d10.sh', release / 'script/run-full.sh'), ('/tmp/h2o-decode-bench.log', release / 'doc/validation/DECODE_THREAD_BENCHMARK.log'), ('/data/xuzhefeng/Datasets/uni-hoi-h2o-decode-bench-20260930/report.json', release / 'doc/validation/DECODE_THREAD_BENCHMARK.json'), ('/tmp/h2o-d10-final-tests.log', operations / 'worker4-encode10-decode10-depth4-regression.log'), ('/tmp/h2o-io-sample.log', release / 'doc/validation/IO_SAMPLE.log')): shutil.copy2(src, dest)print(f'REUSED_SEQUENCES={len(records)} REUSED_VIEWS={sum(len(r["frames_by_camera"]) for r in records)}', flush=True)12345678910111213141516#!/usr/bin/env bashset -euo pipefailcd /home/xuzhefeng/Projects/uni-hoi-datasettest "$(cat /tmp/h2o-d10-final-tests.exit)" = 0test "$(cat /tmp/h2o-decode-bench.exit)" = 0test ! -e /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10old=/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10# Let the already nearly complete fifth camera publish, instead of discarding four completed cameras.while test ! -s "$old/H2O/shared-v1.0/doc/subject4_h1_0.build.json"; do test "$(systemctl --user show --no-pager h2o-full-w4c10-r2-20260930.scope -p ActiveState --value)" = active sleep 20doneprintf '\nRECONFIGURE=%s REASON=decoder10_depth4_no_resume_png_writes\n' "$(date -Is)" >> "$old/full.status"systemctl --user stop h2o-full-w4c10-r2-20260930.scope.venv/bin/python /tmp/h2o-prepare-d10.pysystemd-run --user --scope --unit=h2o-full-d10-20260930 -p CPUAccounting=yes /bin/bash /data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10-d10/run-full.sh12345678910111213141516171819202122232425262728293031323334353637Converted subject1/h1/0Converted subject2/h1/0Converted subject3/h1/0Converted subject4/h1/0Converted subject2/h1/0Converted subject1/h1/0Archive subject1_v1_1.tar.gz: 1 sequencesArchive subject2_v1_1.tar.gz: 1 sequencesConverted subject4/h1/0Converted subject3/h1/0Archive subject3_v1_1.tar.gz: 1 sequencesArchive subject4_v1_1.tar.gz: 1 sequencesConverted subject1/h1/0Archive subject1_v1_1.tar.gz: 1 sequencesConverted subject2/h1/0Archive subject2_v1_1.tar.gz: 1 sequencesConverted subject4/h1/0Converted subject3/h1/0Archive subject3_v1_1.tar.gz: 1 sequencesArchive subject4_v1_1.tar.gz: 1 sequencesVerified existing subject2/h1/0Verified existing subject1/h1/0Verified existing subject4/h1/0Archive subject1_v1_1.tar.gz: 1 sequencesArchive subject2_v1_1.tar.gz: 1 sequencesVerified existing subject3/h1/0Archive subject3_v1_1.tar.gz: 1 sequencesArchive subject4_v1_1.tar.gz: 1 sequencesConverted subject2/h1/0Converted subject1/h1/0Archive subject1_v1_1.tar.gz: 1 sequencesArchive subject2_v1_1.tar.gz: 1 sequencesConverted subject3/h1/0Archive subject3_v1_1.tar.gz: 1 sequencesConverted subject4/h1/0Archive subject4_v1_1.tar.gz: 1 sequencesPASS H2O four archive workers, codec/decode 1/4/10, ordered depth 1/2/4 and missing-depth preservation, no resume PNG writes, RGB FFV1-only, depth and persistent QC12345678910111213141516171819202122232425262728293031323334353637Converted subject1/h1/0Converted subject2/h1/0Converted subject3/h1/0Converted subject4/h1/0Converted subject1/h1/0Archive subject1_v1_1.tar.gz: 1 sequencesConverted subject2/h1/0Archive subject2_v1_1.tar.gz: 1 sequencesConverted subject3/h1/0Archive subject3_v1_1.tar.gz: 1 sequencesConverted subject4/h1/0Archive subject4_v1_1.tar.gz: 1 sequencesConverted subject1/h1/0Archive subject1_v1_1.tar.gz: 1 sequencesConverted subject3/h1/0Converted subject2/h1/0Archive subject2_v1_1.tar.gz: 1 sequencesArchive subject3_v1_1.tar.gz: 1 sequencesConverted subject4/h1/0Archive subject4_v1_1.tar.gz: 1 sequencesVerified existing subject4/h1/0Verified existing subject3/h1/0Verified existing subject1/h1/0Verified existing subject2/h1/0Archive subject1_v1_1.tar.gz: 1 sequencesArchive subject2_v1_1.tar.gz: 1 sequencesArchive subject3_v1_1.tar.gz: 1 sequencesArchive subject4_v1_1.tar.gz: 1 sequencesConverted subject1/h1/0Archive subject1_v1_1.tar.gz: 1 sequencesConverted subject2/h1/0Archive subject2_v1_1.tar.gz: 1 sequencesConverted subject3/h1/0Archive subject3_v1_1.tar.gz: 1 sequencesConverted subject4/h1/0Archive subject4_v1_1.tar.gz: 1 sequencesPASS H2O four archive workers, codec/decode 1/4/10, ordered depth 1/2/4 and missing-depth preservation, no resume PNG writes, RGB FFV1-only, depth and persistent QC123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457# 手物数据仓库统一约定 v1.0
格式版本:`hand-warehouse/1.0`。存储约定:`lossless-video-2026-09-18`。
范围限于手物交互重建。按本任务纳入的源模态转换,不要求每个数据集填满所有组件。缺失模态、尚未下载、语义未核实分别报告,不能互相替代。
本文定义各字段的含义与使用规则,机器可读注册表见 [schema.json](schema.json)。两者互相补充;如有冲突,应先核实并统一定义。
## 1. 目录
```text
hand-datasets/
<dataset_name>/
raw/
doc/ # 官方说明、来源与校验记录
script/ # 官方下载脚本、必要包装脚本
data/ # 保留原始包,不原地解压或改写
<dataset_version>/
doc/ # 发布说明、schema、来源清单
script/ # 转换、校验脚本及运行配置
data/
<sequence_id>/
<camera_id>/
metainfo.json
observation/
rgb.mkv
rgb_valid.pt
depth.mkv # float32 深度的可逆视频编码
depth_valid.mkv # 逐像素 bool 的无损视频编码
camera/
frames.jsonl
intrinsic.pt
intrinsic_valid.pt
extrinsic.pt
extrinsic_valid.pt
annotation/
mano/
motion.pt
motion_valid.pt
visibility.pt
keypoints/
uv.pt
uv_valid.pt
xyz.pt
xyz_valid.pt
visibility.pt # 源数据有时提供
object/
<object_id>/
assets/ # 该物体的网格、材质、纹理及部件资产
<mesh_id>.obj
pose.pt
pose_valid.pt
visibility.pt
metainfo.json # 物体身份、类别、mesh、尺寸与部件引用
articulation.json
keypoints/
vertex_part_ids.pt
joint_state.pt
joint_state_valid.pt
parts/<part_id>/pose.pt
parts/<part_id>/pose_valid.pt
segment/
mask.mkv
mask_valid.pt
instances.jsonl
contact/
relations.jsonl
<subject_id>__<object_id>/ # 对应实体间的距离/接触区域
```
目录展示可能存在的组件,不要求填满。具体文件、字段和缺省规则分别见后续对应小节。原始包的解压发生在临时工作区,raw 内原始包保持不变。
## 2. 相机视图的 metainfo.json
### 2.1 顶层字段与发布信息
每个相机视图必须有 `metainfo.json`。以下字段除另行说明外均为必填:
| 字段 | 填写内容 |
|---|---|
| schema_version | 结构版本,本版为 `hand-warehouse/1.0` |
| dataset_id | 数据集的逻辑标识 |
| release_id | 本次数据发布版本,对应目录中的 dataset_version |
| sequence_id | 所属序列或独立图片样本的标识 |
| camera_id | 当前相机视图标识 |
| sample_type | `image` 或 `video`,规则见 2.2 |
| num_frames | 当前视图帧数 T,所有随帧组件按同一时间轴组织 |
| hand_slots | 固定为 `["left", "right"]`;解剖学左右的使用规则见 5.1 |
| sampling | 采样类型、源 FPS、帧索引引用及选择策略,见 2.2 |
| camera | 当前相机模型与图像尺寸,见 2.3 |
| components | 实际提供的组件及其文件、schema、有效性和来源,见 2.5 |
| split | `train/val/test/unknown`,划分协议见 2.4 |
| view_type | 可选,`ego/exo/unknown` |
`dataset_version` 是数据发布版本;`schema_version` 是结构版本,两者独立。原始包校验摘要、官方来源和转换配置应记录在发布清单中。解压发生在临时工作区,原始包保持不变。
### 2.2 图片、视频与 sampling
`sample_type=image`:允许单图 T=1、`sampling.type=single`,也允许将独立图片批量装入一个视频容器,T>1 时 `sampling.type=independent`、`source_fps=null`。分片大小按数据集选择;FreiHAND 默认每片最多 4096 张,训练与评估分开,尾片不补帧。该数量不是其他数据集的强制要求;同批分辨率、相机模型类型及划分协议一致。每行 frames 必须有稳定且唯一的 `sample_id`、原始文件定位;内参、手形状等仍逐帧保留,不能因打包而共享错误的标定或身份。`sequence_id` 在这里仅是批次标识,不代表真实序列;不得按相邻帧推断跟踪、同步或接触延续。源 camera_id、image_variant、split 等随样本变化时放在 frames 的对应字段中。真实采集时间未知则 timestamp_ns=null。合成背景变体不视为真实多相机。
`sample_type=video`:`sampling.type=dense/sparse`;`source_fps` 是真实采集 FPS,未知为 null。非连续取样必须保留源帧号和已知源时间,不可用采样后索引除以 FPS 冒充源时间。可另记采样策略与步长。
shared 可以仅存所选 RGB 帧对应的数据。OakInk2 图像/动捕不同采样率时用 annotation_matches 明确映射;不要求将未采样动捕点硬塞进 T。多视角身份和源同步关系要保留;选择了哪些帧/相机及原因写在 sampling 中。
`sampling.frames_ref` 指向 `camera/frames.jsonl`。帧号、逐帧时间、同步与标注匹配记录的结构见 4.1;MKV 封装时间的约定见 3.1。
### 2.3 camera 模型声明
`camera` 至少包含 `model`、`schema_id`、`image_size:[W,H]`。模型未知使用 `unknown` 和 `null`,不猜成针孔。实际内参、畸变及外参数组放在 `camera/`,各模型的固定结构见第 4 节。
### 2.4 split 与划分协议
保留上游划分,不将同一采集序列的相邻帧随意拆到不同集合。
有官方划分时必填 split_scheme 和 split_source_locator,split_scheme 区分如 Dex-YCB s0/s1、ARCTIC P1/P2 等选定协议;不知道时 split=unknown 并给理由,不凭空分配。每发布可选择一种协议;存在逐帧差异时 frames 中的 split 覆盖视图默认值,并登记其来源。
### 2.5 components 组件登记
组件表的键是本发布内唯一名称,例如 `rgb`、`depth`、`mano`、`keypoints_uv`。每个已提供组件声明以下信息;模态特有参数在第 3–5 节对应小节中定义。
| 字段 | 约定 |
|---|---|
| available | 本发布是否提供该组件;缺省也表示未提供 |
| schema_id | 已登记的具体存储与语义类型,不得临时创造未登记名称 |
| data_ref | 数据文件路径,相对当前相机视图根目录,使用 POSIX 路径 |
| axes | 数组各维度的含义 |
| valid_ref / valid_axes | 有效性文件及其维度;语义由所属组件规定 |
| storage / valid_storage | 视频数据/视频有效性的存储配置;包含已登记 profile、实际 codec、pixel_format、encoded_size,见 3.1;非视频组件按原数组规则 |
| provenance | source / format_conversion / derived,以及转换或生成方法 |
| source_locator | 原文件、压缩包成员和记录/帧的定位信息 |
不存在的组件允许缺省或写作 `{ "available": false, "reason": "..." }`,不用引用不存在的文件。静态网格可声明标量有效性;具体见 5.4。观测的 valid 见第 3 节,标注的 valid 与 visibility 区分见 5.1。
`provenance.kind` 使用 source/format_conversion/derived,`method` 说明转换或生成方法;发布清单补充脚本版本、参数、输入摘要。`source_locator` 定位到原始文件/压缩包成员和记录、帧号;允许引用有完整溯源清单的前一发布,但链条最终应能回到 raw。不得仅写一个无法定位记录的数据集名字。
`.pt` 仅保存 CPU Tensor,不保存 Python 自定义对象;浮点默认 float32,有效性为 bool,浮点无效位置填 NaN。所有随帧数组保留首维 T,单帧也不 squeeze;静态资产按其 schema 单独声明。单位、坐标及固定形状见各组件小节。
机器注册表 `schema.json` 中,`components` 固定解码后的数据类型、形状、单位和语义;`storage_profiles` 固定视频内的编码/还原方式。不得临时创造未登记的 schema_id 或 storage.profile。同一语义允许选择其登记的不同无损存储 profile。
## 3. observation 观测数据
### 3.1 rgb.mkv 与 rgb_valid.pt
RGB、深度和栅格 mask 在 shared 中统一使用 MKV 视频容器,不展开为逐帧图片或图像 tar。MANO、关键点、位姿等数值标注仍用数组;分割的重叠多边形仍用 JSONL,不为了视频化而有损栅格化。单图可为一帧视频,独立图批量封装规则见 2.2。
**无损指共享层不增加信息损失。** 源 JPEG/H.264 等本身可能已是有损编码,原样保留并不恢复已丢失信息;不得重新以有损 JPEG、H.264、H.265、AV1 参数编码。源视频/图片的色彩、位深、分辨率和几何关系不得被静默改变。RGB schema `rgb/uint8/v1` 的统一读取结果是 `[T,H,W,3] uint8`、RGB 通道,有效性仍为 `rgb_valid.pt [T] bool`。超出该 schema 的高位深或 HDR 源必须报告并扩展定义,不能降到 8 位冒充无损。
#### 3.1.1 允许的 RGB 存储 profile
| storage.profile | 编码方式 | 适用规则 |
|---|---|---|
| mkv/mjpeg_copy/v1 | 源 JPEG 压缩帧直接封装成 MJPEG/MKV | 不解码重编码;保持每张 JPEG 码流字节;普通 8 位 JPEG 且 MKV/解码器支持时使用 |
| mkv/source_copy/v1 | 已有视频的 RGB 对应码流直接封装为 MKV | 仅源编码能被 MKV 和选定解码器支持时使用,不伪造帧;需维持正确的呈现顺序与依赖帧 |
| mkv/h264_rgb_lossless/v1 | libx264rgb 的真正无损模式 | 必须 RGB 路径、CRF=0,并通过全帧 RGB 字节比较;不能替换成默认 libx264 YUV420 路径 |
| mkv/ffv1_rgb/v1 | FFV1 的 RGB 可逆编码路径 | 作为通用候选;解码回 RGB 后必须逐字节相同,不做色度降采样 |
优先尝试源码流直接封装;不能封装或需要选择稀疏帧时,比较 FFV1 与无损 RGB H.264。对完整待发布片段,只在通过无损验收的候选中选择文件较小者,不假设某个编码器总最小;编码时间和随机读取代价记入构建记录。中间候选不作为 shared 多份常驻。H.264 跨帧压缩允许较长 GOP,必须记录 GOP/关键帧间隔,随机取帧需从前一关键帧正确解码,不能把 seek 返回的近似帧当目标帧。
普通源视频可以保留它已有的有损码流,但不允许新增有损重编码。源是 VRS 等记录容器时,先查明图像流实际编码:已有兼容 JPEG/视频包可直接提取封装,否则解码后使用真正无损编码;不把整个 VRS 改后缀当 MKV。PNG 不要求直接塞进 MKV,可选上表两种无损重编码方式。
#### 3.1.2 视频配置与校验
每个视频组件在 metainfo 中登记 `storage`,至少包含:
| 字段 | 内容 |
|---|---|
| profile | 上述登记的存储 profile;语义仍由组件 schema_id 指定 |
| codec | 文件中实际 codec,例如 mjpeg、h264、ffv1;source_copy 必须写实际 codec |
| pixel_format | 实际编码像素格式;不得仅凭编码器参数猜测 |
| encoded_size | 视频物理像素尺寸 `[width,height]`;深度可能不同于逻辑尺寸,见 3.2 |
| decoder | 解码器名称、版本,以及颜色矩阵/范围/旋转处理等实际像素解释配置;未知的源色彩声明 unknown,不擅自称为 sRGB |
| encoder_parameters | 重编码时的编码器、版本、无损模式和 GOP 等参数;直接封装时记录 stream_copy |
| source_lossy | 源是否已有损:true / false / unknown;不是共享层再有损编码的许可 |
无损重新编码的 RGB 必须使用同一固定解码配置,比较**全部帧**的统一 RGB 字节、数量及顺序。MJPEG-copy 不重新编码,生产校验采用 `jpeg-packets-all-rgb-sample16/v1`:从 MKV 逐包取回,对全部源 JPEG 的 SHA256、数量、顺序和图像尺寸进行精确核对;每视图另用同一固定解码配置比较最多 16 帧的源与目标 RGB 字节(含首尾与四分位位置,其余由固定种子抽取)。记录策略、实际索引、种子与结果;不足 16 帧时全查。试点与最终完整序列随机抽查,对选中视图的全部帧复核解码 RGB。历史已做全帧像素检查的证明继续保留。
逐包一致与像素抽查的范围必须分别声明,不能将抽查写成全量像素检查。不能用 PSNR 高、视觉相似、编码器参数称为 lossless 等替代精确检查。同时保留源编码的色彩标记和必要元数据;原图有 EXIF/色彩/方向等元数据时保留 raw 和必要来源信息;不能静默自动旋转图像而不更新像素对应与标定。以上加速策略仅适用于原 JPEG 码流直接封装,不适用于深度、标签或重新编码的 RGB。
所有共享视频的呈现帧顺序与统一 frame_index 一一对应,每个栅格组件恰好 T 帧。MKV 的 `storage_fps` 只服务封装,声明 `timebase_role=index_only`;source_copy 可以保留源 PTS 以避免改坏码流,但真实时间与标注对齐仍以 frames 为准。未知真实时间保留 null。缺失某帧组件时保留索引位置并使用该组件的无效占位/valid 标识,不删帧;不能以重复相邻图像冒充已知观测。
### 3.2 depth.mkv 与 depth_valid.mkv
深度语义仍是 `depth/z_float32/v1`:统一读取结果 `[T,H,W] float32`,米制相机 Z 分量,`depth_type=z`。有效深度有限且大于 0,无效位置为 NaN。`depth_origin=measured/rendered/unknown` 必填,来源不明时 unknown。默认与 RGB 共用像素网格及相机参考系,不处理未注册 RGB-D。射线距离必须依据源定义转换成 z,不能只改声明。
#### 3.2.1 float32 的可逆视频编码
采用 `mkv/depth_float32_bits/v1`:**不是把深度量化成 uint16**,而是将规范化后每个 IEEE-754 float32 的完整 32 位拆成两个 uint16,使用 FFV1 gray16le 保存。视频物理尺寸为 `[2W,H]`:每行前 W 列存原 float32 位串的低 16 位,后 W 列存高 16 位。读取时先合并为 uint32 位串,再按 float32 重新解释,不能数值 cast 成 float32。
```text
u = reinterpret_uint32(depth_float32)
encoded[:, :, :W] = uint16(u & 65535)
encoded[:, :, W:] = uint16(u >> 16)
u_restored = uint32(low) | (uint32(high) << 16)
depth_float32 = reinterpret_float32(u_restored)
```
统一采用 little-endian 原始字节接口。`camera.image_size` 始终是逻辑 RGB 尺寸 `[W,H]`,不能改成编���视频的 2W;`storage.encoded_size=[2W,H]`。包括 NaN 在内的 float32 位串必须全帧完全恢复,不允许改成 float16、整数毫米、归一化灰度或 RGB 伪彩色。这里的无损验收基准是完成既定米制/坐标转换后的标准 float32 数组,不声称消除 float64→float32 等原约定转换本身的舍入。
#### 3.2.2 逐像素有效性
`depth_valid.mkv` 使用 `mkv/bool_ffv1/v1`,FFV1 gray8(FFmpeg pixel_format=`gray`),物理尺寸 `[W,H]`。像素只能为 0 或 1,统一解码为 `[T,H,W] bool`,逐像素含义不变。这样不再把庞大的 bool 数组保存为未压缩 `.pt`;标注的帧级/手级 valid 仍保留原有小数组。
登记示例(W、H 以下取 640、480;decoder/encoder_parameters 的实际版本由转换器填写):
```json
{
"available": true,
"schema_id": "depth/z_float32/v1",
"data_ref": "observation/depth.mkv",
"axes": ["T", "height", "width"],
"valid_ref": "observation/depth_valid.mkv",
"valid_axes": ["T", "height", "width"],
"unit": "m",
"depth_type": "z",
"depth_origin": "measured",
"invalid_value": "NaN",
"storage": {
"profile": "mkv/depth_float32_bits/v1",
"codec": "ffv1",
"pixel_format": "gray16le",
"encoded_size": [1280, 480],
"source_lossy": false,
"decoder": {"name": "ffmpeg", "version": "填写实际版本"},
"encoder_parameters": {"name": "ffv1", "level": 3, "version": "填写实际版本"}
},
"valid_storage": {
"profile": "mkv/bool_ffv1/v1",
"codec": "ffv1",
"pixel_format": "gray",
"encoded_size": [640, 480],
"source_lossy": false,
"decoder": {"name": "ffmpeg", "version": "填写实际版本"},
"encoder_parameters": {"name": "ffv1", "version": "填写实际版本"}
},
"provenance": {"kind": "format_conversion", "method": "源深度转米制 z float32;逐位打包为 FFV1"},
"source_locator": {"file": "raw/data/depth.zip", "member": "depth/0001.png"}
}
```
深度和有效性视频都必须逐帧解码验收:float32 位串相同、bool 相同、T 相同,并检查 valid=true 的正有限值和 valid=false 的 NaN。读取器必须按 profile 还原,不能把 depth.mkv 的编码像素直接当深度值。
## 4. camera 相机、帧索引与标定
### 4.1 frames.jsonl:索引、时间与对应关系
`camera/frames.jsonl` 每行对应统一帧号 `frame_index=0..T-1`,是所有组件的唯一行索引。至少包含 `frame_index`、`timestamp_ns`、`clock_domain`、`source_locator`;原始帧号/文件名保存在 `source_frame_id`,不能被新帧号替代。每行还可有 `annotation_matches`,按组件键保存 `source_frame_id`、`source_timestamp_ns`、`clock_domain`、`match_method` 和 `delta_ns`;方法为 exact/index_map/nearest/interpolated,索引映射无时间依据时 delta_ns=null。nearest 必须记录允许误差;interpolated 必须记录两端源标识和权重。delta_ns 仅在同一时间域中计算为源标注时间减图像时间。多相机共享 `sequence_id`;已知同步关系必须用 `sync_id` 或明确的源帧/时间映射表达,不能仅凭相同数组索引认定同步。
每个视图必须提供此文件。源时间使用整数纳秒及 `clock_domain`,未知写 JSON `null`;不同时间域不能直接比较。逐帧 split 可以覆盖 metainfo 的视图默认划分,并保留来源,见 2.4。
### 4.2 坐标系与标定通则
| 项目 | 统一约定 |
|---|---|
| 相机坐标 | 右手系,X 向右、Y 向下、Z 向前,长度单位米 |
| 齐次变换 | 列向量,`p_target = T_target_from_source @ p_source` |
| 图像坐标 | `(u,v)`;左上像素中心为 `(0,0)`,u 向右、v 向下,单位 pixel |
| 固定标定 | 本版展开为 T 份,同一 schema 不混用静态与动态形状 |
| 分辨率或模型变化 | 分开存储为视图/片段,不在同一组件中混装 |
| 未知标定 | 相机内外参允许缺省,不填单位阵冒充已知标定 |
### 4.3 intrinsic.pt 与畸变参数
| model / schema_id | intrinsic.pt 的固定结构 |
|---|---|
| pinhole / camera/pinhole/v1 | `[T,3,3]`,标准 K,最后一行为 `[0,0,1]`;限无畸变或已校正图像 |
| fisheye624 / camera/fisheye624/v1 | `[T,15]`,`[f,cx,cy,k0,k1,k2,k3,k4,k5,p0,p1,s0,s1,s2,s3]`,采用 Project Aria Fisheye624 投影定义 |
| opencv_fisheye4 / camera/opencv_fisheye4/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件 `distortion_ref` 指向 `[T,4]`,顺序 `[k1,k2,k3,k4]`,使用 OpenCV fisheye 等距角度多项式;已由 ReInterHand 实际原始相机参数验证 |
| rational8 / camera/rational8/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件必需 `distortion_ref` 指向 `[T,8]`,顺序 `[k1,k2,p1,p2,k3,k4,k5,k6]` |
| unknown / null | 不提供可用 intrinsic,不声称可以投影 |
有畸变的其他模型必须注册新 schema,固定参数名、顺序和投影公式;不能塞进针孔 K 后遗失畸变项。`metainfo.camera.schema_id` 必须与 intrinsic 组件一致。同一模型的别名不可隐式改变参数布局。
`opencv_fisheye4`:对前方点令 `x=X/Z, y=Y/Z, r=sqrt(x²+y²), theta=atan(r)`,`theta_d=theta*(1+k1*theta²+k2*theta⁴+k3*theta⁶+k4*theta⁸)`;`u=fx*x*theta_d/r+cx, v=fy*y*theta_d/r+cy`。光轴 r=0 时使用连续极限 `theta_d/r=1`。四系数不能按普通径向畸变解释,也不能补零冒充 Fisheye624。
rational8 对归一化坐标 x=X/Z、y=Y/Z,令 r²=x²+y²,径向项为 `(1+k1*r²+k2*r⁴+k3*r⁶)/(1+k4*r²+k5*r⁴+k6*r⁶)`;再加 p1/p2 切向项并经 K 得到像素。`distortion_ref` 与 intrinsic 共用 `[T]` valid,保存到 camera/distortion.pt。不得把这种畸变三维坐标当作真实相机系 xyz 保存。
内参有效性为 `intrinsic_valid.pt [T] bool`;有畸变时使用对应 `distortion_ref`。同一模型的参数名和顺序固定。
### 4.4 extrinsic.pt 与 extrinsic_valid.pt
`extrinsic.pt` 为 `[T,4,4]`,schema `transform/se3/v1`,方向固定 `T_camera_from_world`,有效性 `[T]`。世界坐标含义及源坐标转换记录在 provenance 中;只有相机坐标标注不要求虚构世界坐标。旋转块须正交且 determinant≈1。
## 5. annotation 标注数据
### 5.1 标注通则:手槽、valid 与 visibility
手槽固定为 0=left、1=right,指解剖学左右,不按画面位置或可见性重排。本阶段只处理左右手两槽,不处理更多手。实体引用使用 `hand_left`、`hand_right`;手槽不证明跨采集片段的个人身份。
#### 5.1.1 valid:标注是否可用于监督
标注的 `valid=true` 表示:有对应实际标注、通过本 schema 数值检查,且通过来源明确提供并适用于该组件的有效性/QA 条件。`valid=false` 可由缺标注、无法建立帧对应、源无效占位或官方 QA 不通过导致;不等于画面没有手或手不可见。各组件独立判断,MANO 按 `[T,2]` 标记左右手,关键点按 `[T,2,K]` 标记。
**2026-09-20 将标注 valid 从“仅表示存在”修订为“可用于监督”,字段形状不变。** 公式为 `source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass`。没有官方 QA 时省略最后一项,不伪造 QA;不能把未知当成已通过已存在的 QA。适配器在组件 `valid_policy` 中记录具体规则、来源、聚合/广播作用域。缺失官方必需 QA 的记录须明确处理为未知或暂停验收,不能静默通过。无效浮点项仍填 NaN,原始数据保留在 raw;被排除原值可用于 doc 中明确标识的诊断渲染,不能冒充 shared 有效监督。
本地筛选须依据明确的规则,并在 `valid_policy.local_excluded_frame_indices`、排除原因和正式报告中记录。单个可疑投影作为问题记录,不直接硬编码排除该帧。已确认的曝光异常须明确作用范围,不能把一个序列的“前两帧有问题”套到所有序列。RGB 编码完好与几何监督可用是两件事,允许保留原图及帧索引而屏蔽对应标注;未发现问题不等于完成全部人工审核,试点待确认时不能作为已验收发布使用。
源字段必须按官方语义映射,不能直接按名字复制:
| 来源 | 官方含义 | 映射原则 |
|---|---|---|
| [H2O](https://github.com/taeinkwon/h2odataset) 的手标注首位 | 0 未标注、1 已标注 | 可作为对应手标注存在性的依据,不推断未标注原因 |
| [HOT3D](https://github.com/facebookresearch/hot3d#using-mask-files) 的 pose_available、visible、mask_qa_pass | 分别表达姿态存在、可见性、对画面中可见手物位姿的人工 QA | 逐手/物体记录决定存在性,再 AND 当前相机当前帧 QA;QA 是整帧聚合判定,保守排除该帧全部手物几何监督,不声称每个实体均有错误;源可见性基于位姿推导时,其自身 valid 同样受 QA 约束 || [Dex-YCB](https://github.com/NVlabs/dex-ycb-toolkit#loading-dataset-and-visualizing-samples) 的全零 pose_m、全 -1 joints | 不可见的手或缺标注共用占位表示 | 对应组件 valid=false;不能从该值判定 visibility=false,也不能声称原因是动捕缺失 |
| [ARCTIC](https://github.com/zc-alexfan/arctic/blob/master/docs/data/data_doc.md) 的 is_valid/left_valid/right_valid | 是否有效用于官方评估 | 核实每项筛选依据;不把可见性/评估选择直接等同 QA。本次原始 mano.npy 不含这些派生评估标记,按原记录与数值检查生成 valid,并声明没有额外官方 QA 输入 |
源 valid=false 若代表评估筛选或其他条件,应检查实际标注和源约定后映射;不能一律清空坐标。反之,占位零或 -1 只有在源官方明确规定时才判为缺失,不泛化成所有数据的判断规则。
`valid=true` 的标注应通过其 schema 的数值与形状检查;检查失败必须报告或修复,不能静默隐藏。QA 不通过应报告排除数量与原因,并保留可追溯信息;不能把这类无效称为缺标注。RGB、深度等观测有效性仍按各自 schema;手物 QA 不自动否定 RGB、静态相机内参或物体资产。相机外参是否过滤须依据其自身来源规则;HOT3D 本次保留源外参用于溯源和诊断,不能用其存在性证明 QA 失败帧的几何监督正确。
#### 5.1.2 visibility:可见性属性
附加质量属性只保留 `visibility`,存放在对应模态或标注集内,不设 quality 目录。同一份可见性仅存一次;uv 与 xyz 共用时引用同一个文件。
visibility 通过所属组件 attributes 登记 data_ref、axes、dtype、visibility_type、meaning、provenance、source_locator;未知值通过属性 valid_ref 标识,全已知可声明 valid=true。比例与布尔值不相互强转,也不按任意阈值二值化。没有 MANO 时,整手可见性挂在 keypoints 组件,使用独立的 whole_hand_visibility.pt,明确 meaning=whole_hand,不与逐关键点可见性混用。
`valid` 回答“这项标注能否用于监督”,`visibility` 回答“在当前图像中是否可见(或可见多少)”。不可见的手或关键点仍可有有效标注;不能因 visibility=0 就清空坐标。源没有 visibility 时缺省或标为未知,不由 valid 推断。
| 情况 | 手标注 valid | visibility |
|---|---|---|
| RGB 已开始录制,动捕尚未开始,没有其他对应手标注 | false | 以独立源可见性标注为准;没有则未知 |
| 手被遮挡,但源有标注且通过适用有效性检查 | true | 若源声明不可见,则 false 或源可见比例 || 手可见且有对应标注,通过适用 QA | true | 若源有此信息,则 true 或源可见比例 || 手可见,但该帧漏标或动捕中断 | false | 可以为 true,但必须有独立来源依据 || 有手部参数,但官方 QA 明确不通过 | false | 不据此断言不可见;源可见比例若基于不可靠位姿,其属性 valid 也为 false |
visibility 自己的 valid_ref 表示该可见性标注是否可用,不复用 MANO 或关键点坐标的 valid_ref;明确记录源存在性及适用的 QA 条件。上述例子不要求凭图像自动生成可见性。
不设 quality 组件或目录,不另存拟合误差、曝光、截断比例等通用质量数组。适用的官方 QA 合并进对应 valid,在 `valid_policy` 记录来源与规则;正式校验报告保留原始 QA 时间区间及排除统计。原始 QA 文件仍在 raw,官方 split 保留。
### 5.2 mano:参数与整手可见性
MANO schema `mano/axis_angle61/v1`:`motion.pt [T,2,61]`,顺序为完整 16 关节 axis-angle 48、shape betas 10、全局平移 3。姿态使用弧度,平移米,位于当前相机系。有效性 `[T,2]`;缺少一侧整槽 NaN。PCA 必须先按对应模型展开,不能将 PCA 系数直接填入 axis-angle。
`model_profile` 必须固定 MANO 版本、`flat_hand_mean=true`、左手 shapedirs 修正状态。平移表示模型输出顶点所加的全局平移,不是某个腕关节的坐标;源语义不同须转换。shape 无量纲。模型权重不作为共享数据附带上传。
`mano/visibility.pt [T,2]` 保存源整手可见比例时使用 float32 [0,1],`visibility_type=ratio`;只有实际采用 0–100 的百分比才除以100,不能只凭表头判断。HOT3D 的 `visibility_ratio[%]` 实值已经是0–1,官方读取器原样读取,必须保留原值。通过 MANO 组件 attributes 登记,使用独立有效性,不复用 motion_valid。
手部共享表示仅保留 MANO 参数与选定关键点,不发布独立手表面几何。需要渲染或接触计算时由 MANO 参数生成,几何引用使用固定 MANO 模型配置与顶点顺序;不影响 object 下的物体模型和材质资产。
### 5.3 keypoints:二维点、三维点与逐点可见性
关键点独立于 MANO 参数存在;没有 motion 也可有关键点。`uv.pt [T,2,K,2]` 与 `xyz.pt [T,2,K,3]`,有效性 `[T,2,K]`,分别采用 `keypoints/uv/v1` 和 `keypoints/xyz/v1`。K 由 `keypoint_schema` 固定,不能在同一数组中逐帧变化;同体系统一顺序。数值使用像素坐标或米制相机系。
| keypoint_schema | K 与固定索引 |
|---|---|
| mano21/v1 | 21;wrist 后依次 thumb/index/middle/ring/little,每指由近端至指尖 |
| rhd21/v1 | 21;保持 wrist,然后五指由近端至指尖;原始每指 tip→palm 反序。只统一顺序,不宣称解剖学位置等价于 MANO |
具体名称与源索引映射见 `schema.json`。当前只登记 MANO21 与 RHD21;不登记 MediaPipe、ReInterHand capture21 或 fit24 中间关键点。
每个发布中的每个视图只提供一套标准手关键点,直接放在 keypoints 下,不设 annotation_set_id 字段或目录。uv 与 xyz 是这套关键点的二维与三维表示,不是两套标注。provenance 分别记录二者来自原始标注还是计算结果;不要求已有 2D 必须由当前 xyz 重新投影覆盖。
ReInterHand 的 Original keypoints���Original fits keypoints 及带前臂关键点不纳入 shared;如需手关键点,从选定 MANO 参数生成 MANO21 并记录模型/指尖回归约定。其他数据集默认使用选定的官方关键点,不额外生成平行的 MANO 派生集合。后续主动更换生成方法或结果时发布新的 dataset_version,不在同一版本内增设方法分支。
manual/projection/fitting 只记录在 provenance,不作为目录或类型分支。不得通过坐标为零、是否出画或 visibility 判断标注是否存在。派生标注仅在实际生成并通过数值检查后声明 valid=true;没有生成的项为 false,不伪造坐标。
`keypoints/visibility.pt [T,2,K]` 保存源逐点可见性,布尔表示使用 `visibility_type=boolean`。uv 与 xyz 共用时引用同一份文件。整手比例属性没有 MANO 可挂载时使用 `whole_hand_visibility.pt [T,2]`,`meaning=whole_hand`;它与逐点可见性分开,通用登记规则见 5.1。
不使用 annotation_set_id;ReInterHand 中间关键点集合不进入 shared,raw 保留来源文件。
### 5.4 object:身份、资产、位姿与几何
#### 5.4.1 metainfo.json:物体身份与跟踪作用域
手用 `hand_left`、`hand_right` 及槽位 0、1 表示,不再另存 entities.json。物体身份登记在 `annotation/object/<object_id>/metainfo.json`,必填 `object_id`、`identity_scope`、`scope_id`、`source_locator`;可含 `category_id`、`source_object_id`、`mesh_ref`、`has_model`、部件引用。即使只有分割、没有 pose/mesh,也可只有这份物体元信息。
`identity_scope` 为 frame/subsequence/sequence,`scope_id` 指定具体作用域;跨相机共享身份只在已有源对应证据时使用。VISOR 按官方 subsequence 与实体名关联时记录 `association_basis=official_subsequence_entity_name`,不能声称这是全视频物理实例跟踪。无需与 object_id 一一对应的标准 track_id;官方独立轨迹标识存在时保留为 source_track_id,并声明作用域。手槽不证明跨采集片段的个人身份。
#### 5.4.2 assets:网格、材质与纹理
资产属于物体,统一存放在 `annotation/object/<object_id>/` 内,可用 `assets/` 子目录组织网格、材质、纹理和部件资产。序列层不设共享 assets。所有引用采用视图根目录为基准;其中物体资产组件的 `data_ref` 与部件的 `mesh_ref` 采用相对于当前视图目录的 POSIX 路径,例如 `annotation/object/cup_01/assets/cup.obj`,且必须指向所属物体目录内的资产。OBJ 内部的材质、纹理引用遵循文件格式自身的相对路径规则,依赖文件一并保留。不同相机视图允许各自保存物体资产,不要求跨视图去重;下载物体时包含其资产依赖。
网格 schema 为 `mesh/obj/v1`,顶点米制,静态有效性可直接声明标量 `valid`,或通过 `valid_ref` 指向标量 bool Tensor;不按 T 重复静态资产。由物体/部件通过引用关联,不仅凭文件名猜测。
#### 5.4.3 pose.pt、pose_valid.pt 与 visibility.pt
刚体 schema 为 `object/rigid/v1`,`pose.pt [T,4,4]` 固定为 `T_camera_from_object`,平移米制,有效性 `[T]`。物体坐标原点、轴向必须与 mesh 一致;旋转块为正交矩阵且 determinant≈1。
`object/<id>/visibility.pt [T]` 保存源物体可见比例,float32 [0,1],`visibility_type=ratio`。通过所属物体组件 attributes 登记,独立表达其有效性。
#### 5.4.4 articulation.json、部件位姿与 joint_state.pt
关节物体:schema `object/articulated/v1`,`articulation.json` 登记 `parts` 与 `joints`。每个 part 有 `part_id`、`parent_id`(根为 null)、`has_model`、`mesh_ref`;has_model=false 时 mesh_ref=null,结构节点允许没有网格。父链不得成环。每个 joint 有唯一 `joint_id`、`parent_part`、`child_part`、`type`;fixed 单位 null、revolute 弧度、prismatic 米。有源限位时保存 `limits:[lower,upper]`;没有时 null,不伪造上下限。部件姿态统一为 `T_camera_from_part [T,4,4]`,不与父局部变换混装。
若提供 `joint_state.pt [T,J]`,必须登记固定 joint_order、轴在父部件系的表达、零位变换与正方向,valid 为 `[T,J]`;缺少这些运动学定义时只发布部件位姿与已有来源信息,不伪造可驱动的关节模型。关节值与部件位姿同时存在时需验证一致性。
部件层级应声明语义:纯语义包含树允许 `joints=[]`,不将包含关系推断为机械关节。关节状态 schema 为 `object/joint_state/v1`;转动用弧度、移动用米,混合类型按 joint_order 对应的关节定义解释。
#### 5.4.5 dimensions、几何关键点与顶点部件标签
`dimensions.pt [T,3]` 采用 `object/dimensions/v1`,有效性为 `[T]`。
物体/部件 `dimensions` 为 `[length,width,height]` 米,轴顺序与该 mesh 的局部坐标关联,登记 `dimensions_semantics` 和来源。HOI4D dimensions 与 mesh 的具体尺度关���未验证前标为 source_unspecified,保留源值并暂停依赖该关系的几何验收,不能默认为待施加缩放。需要施加缩放时明确 scale_applied_to_mesh,禁止重复应用。
源物体关键点放 `object/<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。每个发布选择一套源几何点并记录选择,不另建方法分支。
`vertex_part_ids.pt [V] int64` 绑定 `mesh_ref` 与 topology_id,登记整数到 part_id 的映射;未知用 -1。ARCTIC 不同拓扑的资产分别绑定,不能共用未经转换的顶点标签。部件层级中 is_instance/has_model 等源属性保留,几何文件仍全部归 object。
### 5.5 segment:分割类别、编码与覆盖范围
每个发布选择一套任务使用的分割表示,不建立方法/标注集分支。没有分割就不创建 segment 目录,不为其他模态创建空的实体表。
| schema_id | 文件与数值语义 |
|---|---|
| segment/uint16_labels/v1 | mask.mkv;整数区域编号,通过 instances.jsonl 解释 |
| segment/instance_polygons/v1 | polygons.jsonl;实例多边形,可重叠;当前不支持孔洞拓扑 |
| segment/foreground_intensity/v1 | mask.mkv;0–255 前景强度,不是区域编号或经过校准的概率 |
#### 5.5.1 uint16 标签图与 instances.jsonl
组件声明 `segmentation_type=semantic/instance/part`;同一组件固定一种类型。`mask.mkv` 解码为 `[T,H,W] uint16`,schema `segment/uint16_labels/v1`,使用 `mkv/uint16_ffv1/v1`,FFV1 gray16le 无损;只有所有区域编码均 ≤255 时允许 gray8(pixel_format=gray),读取后转 uint16,数值不变。禁止调色板和有损编码。有效性 `[T]`,表示该帧有可用分割标注。数值 0 固定为 unassigned,65535 固定为 ignore,1–65534 为区域编码,不能直接等同 entity_id。
`instances.jsonl` 每帧一行,包含 `frame_index` 与 `labels`。每条标签包含 `mask_value`、`category_id`、`entity_id`、`part_id`;无意义或未知字段为 null。semantic 允许 entity_id=null;instance 必须引用 hand_left/hand_right 或登记的 object_id;part 还须关联登记部件。源实例 ID 和其他属性分别保存在 `source_instance_id`、`source_attributes`。mask 中每个非保留编码必须有且仅有一个映射。
FreiHAND 的试点按本任务需要,统一到手/背景类别,保留每个原生区域编码;不要求给原生细分区域猜测手指名称。需要细部件监督时,尚未核实的部件名称必须保持未知,不能因粗粒度手类别已核实便声称部件语义也已统一。
#### 5.5.2 重叠实例多边形
每发布选择一套任务使用的分割表示,不建立方法/标注集分支。VISOR 的实际试点存在重叠实例多边形,单层标签图不能无损表达。对此补充 `segment/instance_polygons/v1`:`segment/polygons.jsonl` 每帧包含 `frame_index` 和 `instances`,每实例包含 `mask_value` 与 `polygons`(列表,每个多边形为源图像像素坐标顶点序列,保留原始精度)。身份和类别仍由同一 `instances.jsonl` 映射,有效性仍为 `[T]`,通过 schema 区分物理编码。允许多实例重叠,不采用后画覆盖前画。消费者按需栅格化为独立实例二值 mask;不能声称合并的单层 mask 无损。
#### 5.5.3 灰度前景强度
ReInterHand 的官方渲染 mask 为双手合并的灰度前景掩码,实测存在 0–255 的中间值,不是左右手实例编号。登记 `segment/foreground_intensity/v1`:仍存 `segment/mask.mkv`,解码为 `[T,H,W] uint16`,使用 `mkv/uint16_ffv1/v1`,此类数据优先编码为 FFV1 gray8(pixel_format=gray),读取后转 uint16。有效值范围 0–255,归一化值为 `float32(value)/255`;0 为背景端点、255 为前景端点。组件声明 `foreground_category=hand`、`entity_id=null` 和双手合并语义,不使用区域编号映射。这里保留原始渲染 mask 强度,不把它称为经过校准的概率。若任务需要二值 mask,阈值化属于任务层派生操作,记录阈值;共享层不丢弃中间灰度。不同 schema 的数值含义不同,不能将该文件按整数类别图解码。
FreiHAND 训练集的 JPEG mask 使用 `segment/foreground_intensity/v1`,逐像素保留 JPEG 解码后的灰度,`entity_id=hand_right`。该 schema 不限定双手合并:单手或合并范围由 `entity_id` 与 `coverage` 明确声明。评估集整数区域图仍用 `segment/uint16_labels/v1`,两者不能仅凭文件名使用同一种解码语义。
#### 5.5.4 coverage 与有效性
`coverage.kind=full/selected_entities/partial/unknown`。full 指声明���标注范围完整;selected_entities 还应列出目标范围。无论哪种,0 本身不自动成为背景;背景要有明确类别映射,未标注区域不能用于构造负样本。保留源逐类/逐实例 exhaustive 信息,未知不可改写为完整。
三种表示的帧级有效性均为 `[T]`,表示该帧是否提供此分割标注;对应 valid_ref 在组件中登记,仍用小型 bool `.pt` 数组。栅格 mask 必须登记 storage,格式见 3.1.2,所有帧的整数编码或强度逐值完全相同。编码语义由 schema_id 决定,读取器不能仅依据 mask.mkv 文件名选择解码方式。
### 5.6 contact:接触、抓取、区域与距离
#### 5.6.1 relations.jsonl 与 relations_valid.pt
`annotation/contact/relations.jsonl`,schema contact/relations/v1,每帧一行含 frame_index、relations。每条记录含 relation_type(contact/grasp)、subject_id(手槽或登记实体)、object_id、status、source_locator、provenance。status 固定为 positive/negative/unknown/target_unannotated:positive 必须有可解析目标,negative 表示源明确否定该关系,unknown 为不确定,target_unannotated 为确有接触但目标未标注。非 positive 的 object_id 可 null,不能用 null 冒充“不接触”。稀疏源无记录的帧不自动补 negative。
VISOR 的对象 mask ID 必须先按同帧 source_instance_id 解析成 object_id;hand-not-in-contact、none-of-the-above、inconclusive 分别映射 negative、target_unannotated、unknown,保留原始字符串。Dex ycb_grasp_ind 通过 ycb_ids 映射到登记物体,以 relation_type=grasp 保存;不得当作逐顶点接触。
relations 组件的 valid_ref 指向 `relations_valid.pt [T] bool`,表示该帧是否有可用源关系标注。有效帧中可以存在 status=unknown 的明确不确定标注;无源标注的帧为 valid=false、relations=[]。组件仍声明 available/provenance/source_locator。
#### 5.6.2 实体对的顶点区域与距离
已发布的接触区域/距离按参与关系的 subject_id 与 object_id 组织,每对实体保留选定的一套结果,以精确 geometry_ref/topology_id 关联到手或物体/部件;不要求每套数据都有。顶点区域 schema contact/vertex_region/v1:bool `[T,V]` 加同形 valid;顶点距离 schema contact/vertex_distance/v1:float32 `[T,V]`、米、同形 valid,声明 source/target geometry_ref、distance_definition(signed/unsigned、测量到点集或表面等明确源定义)。geometry_ref 必须指向已登记 mesh 或由固定 MANO 模型配置确定的拓扑;拓扑/顶点数变化时按拓扑拆分片段。其他源区域表示只有在实际接入并登记 schema 后才可转换,不能随意栅格化宣称等价。
顶点区域/距离已有存储定义,但尚未完成真实输入试点;接入时必须提供源语义与几何验收证据,不因已经登记 schema 就视为通过。
## 附录:任务范围
不强制收录 2D bbox、完整高频动捕、动作程序、身体 SMPL-X、点云或网络特征。范围内的接触、visibility、选定手关键点、物体几何不能因不便处理而静默丢弃。分割采用的物理编码由第 5.5 节决定,存在重叠时不能以单层标签图声称无损。
不设置 entities_ref/segment/entities.json,不要求与 object_id 重复的 track_id。MediaPipe 不在当前关键点定义中;旧版本迁移必须保留可追溯关系,不能直接删表。手部共享表示不含独立 hand_mesh。
schema.json 是普通注册表,不是 JSON Schema 文档或可执行验收器;定义存在不代表真实数据已验证。验收须保留实测范围与未决项。
本存储约定只更新标准,不代表既有 FFV1/depth.pt 试点已迁移。新发布必须显式写 storage 配置;旧产物按其旧定义读取,不能只改文件后缀或版本标识伪装为合规。123456789101112131415161718192021222324252627282930# H2O raw → shared-v1.0
## 范围与来源
本版本仅转换 `raw/data/subject{1,2,3,4}_v1_1.tar.gz` 的真实五视角 (`cam0`–`cam4`) 序列;`h2o_CASA.tar` 是单独的扩展,不与标准序列混合。每个原始序列存于 `data/subjectN_<scene>_<sequence>/cam{0..4}/`。源压缩包保持不变,不合成源不存在的标注。输出仅在本地制作;完整序列试点及人工检查通过、更新全量预估之前,不启动全量。
| 源包/字段 | shared 文件/处理 || --- | --- || `subjectN_v1_1.tar.gz`: `camX/rgb/<frame>.png` | `observation/rgb.mkv`:逐帧源 RGB 解码为 RGB24,FFV1 直接编码;输出**每帧**解码与源 RGB 字节摘要完全一致。`rgb_valid.pt` 记录存在性,源帧号和每组件的包成员及 SHA256 写入 `camera/frames.jsonl`。不再额外编码未采用的 H.264 RGB 候选;FFV1 编码器进程失败时才尝试 H.264。 || 同包 `camX/depth/<frame>.png` | `observation/depth.mkv` 和 `depth_valid.mkv`;按源毫米单位除以 1000 转米,保留无效深度与全帧时间轴,深度位串以 FFV1 保真封装并逐帧校验。既不做 3 米裁剪也不造出缺失的深度。 || `camX/cam_intrinsics.txt`、`camX/cam_pose/<frame>.txt` | `camera/intrinsic.pt`、`extrinsic.pt`:保留源内参;逐帧源 `T_world_from_camera` 求逆后存 `T_camera_from_world`;声明变换约定与有效性。 || `camX/hand_pose_mano/<frame>.txt` | `annotation/mano/motion.pt`、`motion_valid.pt`:源左/右手标志各自判断有效性;姿态与平移保持源数值,声明 MANO 模型配置,缺模型则明确标依赖缺失,不伪造网格或掩码。 || `camX/hand_pose/<frame>.txt` | `annotation/keypoints/xyz.pt`、`xyz_valid.pt`:源双手 21 点,相机坐标系米制,与 MANO 有效性彼此独立。HTML 中的投影仅用于人工预览,不写回训练数据。 || `camX/obj_pose/<frame>.txt`、`obj_pose_rt/<frame>.txt` | `annotation/object/<name>/keypoints/xyz.pt`、`pose.pt`:按源类号关联 21 个物体点及物体→相机位姿;仅源存在时登记组件及有效性。 || `object.zip` | `annotation/object/<name>/assets/` 与源 OBJ、MTL、纹理;静态形状预览不等于所有帧网格位姿的投影证明。 || `label_split.zip` 的 `action_{train,val,test}.txt` | 序列元数据的官方划分及来源;未知映射明确记 `unknown`,不自行编排。 |
`cam4` 是 ego,`cam0`–`cam3` 是 exo。真实时间/FPS 缺乏可靠来源时使用 null,不把 MKV 封装帧率冒充采集时钟。源 `action_label`、`verb_label`、pose 任务帧列表和 `manolabel_v1.1.tar.gz` 保留在 raw;当前契约没有相应动作组件,本发布不宣称它们已转换。源没有像素分割,本版本不投影网格生成替代分割。
## 源资产文件名修复
源 `object/cocoa/cocoa.obj` 引用 `ovomaltine.mtl`,材质内写的是 `map_Kd cocoa.png`,但原 ZIP 只提供 `ovomaltine.png`。仅在临时解压目录为该已确认的纹理增加**字节相同**的 `cocoa.png` 别名,保留原 PNG、OBJ、MTL 不变;在网格 `source_locator.texture_aliases` 中记录别名、原始包成员和 SHA256。别名与已保留的旧 cocoa 资产一致,不替换图像、标注或网格。全部八类物体的材质依赖在读取大 subject 包之前预检,其他缺失/越界依赖仍报错。
## 加速与验收
四个互不依赖的 subject 压缩包可由 `--workers 1..4` 并行顺序读取,各 worker 一次只处理一个序列。数值库保持单线程;FFV1 编码支持 `--codec-threads 1|2|4|8|10`,当前全量按用户要求使用 10,逐帧解码校验仍保留。并发数由相同输入实测吞吐量决定,记录 OS 线程峰值和磁盘占用,不以 CPU 线程数本身作为提速证据。RGB 源为 PNG,不适用 ARCTIC/HOT3D 的 JPEG 包直封和 16 帧抽查:RGB、深度、有效性与数值模态仍逐帧精确校验。临时文件在 `/data` 上隔离放置,历史 62 条目录不复用、不覆盖;调整并发时,在新的运行目录复用本次全量已经原子发布的完整序列,并从源重新核对帧号及逐组件 SHA256。未完成的临时序列不复用,原运行的脚本、配置及 QC 保留用于溯源。
先运行不截帧的代表性完整序列试点,保存自动 QC、真实耗时和 `doc/validation/index.html`(RGB、深度、源 3D 关键点投影、原生物体网格和全组件数值/有效性)。试点由人工核查之后再决定全量;全量后再次抽样人工核查。报告须区分数据完整性、源未提供的模态与仅供人工判断的几何对齐。
2026-09-29 完整序列试点已获人工确认,用户已授权本地全量。2026-09-30 用户取消 CPU 使用量上限,指定 4 个独立压缩包 worker、每个 FFV1 编码器 10 线程;Python worker、读取及校验子进程不计入这最多 40 个编码线程,因此总线程数不固定为 40。该配置不代表已证明加速倍数。源包和旧产物保留;代码变化使用独立运行目录,已完��序列保留原始构建记录及生产脚本快照。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869{
"schema_version": "hand-warehouse/1.0", "validity_revision": "usable-annotation-2026-09-20", "annotation_validity": { "meaning": "annotation usable for supervision, not merely record presence", "formula": "source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass AND NOT explicitly_reviewed_local_exclusion", "without_official_qa": "omit QA term; declare source rules; do not fabricate QA", "policy_field": "components.<name>.valid_policy", "visibility_is_independent": true, "invalid_float_value": "NaN", "hot3d": "broadcast per-camera frame manual QA conservatively to hand/object labels and pose-derived visibility; retain RGB and source calibration; keep native QA in raw and review report", "hot3d_visibility": "native visibility_ratio[%] already ranges from 0 to 1; do not divide by 100" }, "hand_slots": [
"left",
"right"
],
"keypoints": {
"mano21/v1": {
"count": 21,
"names": [
"wrist",
"thumb_1",
"thumb_2",
"thumb_3",
"thumb_4",
"index_1",
"index_2",
"index_3",
"index_4",
"middle_1",
"middle_2",
"middle_3",
"middle_4",
"ring_1",
"ring_2",
"ring_3",
"ring_4",
"little_1",
"little_2",
"little_3",
"little_4"
],
"source_index_map": null,
"note": "adapter maps official MANO joint and fingertip convention"
},
"rhd21/v1": {
"count": 21,
"names": [
"wrist",
"thumb_1",
"thumb_2",
"thumb_3",
"thumb_4",
"index_1",
"index_2",
"index_3",
"index_4",
"middle_1",
"middle_2",
"middle_3",
"middle_4",
"ring_1",
"ring_2",
"ring_3",
"ring_4",
"little_1",
"little_2",
"little_3",
"little_4"
],
"source_index_map_per_hand": [
0,
4,
3,
2,
1,
8,
7,
6,
5,
12,
11,
10,
9,
16,
15,
14,
13,
20,
19,
18,
17
]
}
},
"camera": {
"opencv_fisheye4": {
"K": [
3,
3
],
"distortion": [
"k1",
"k2",
"k3",
"k4"
],
"projection": "theta=atan(r); theta_d=theta*(1+k1*theta^2+k2*theta^4+k3*theta^6+k4*theta^8); source ReInterHand"
},
"pinhole": {
"K": [
3,
3
]
},
"fisheye624": {
"parameters": [
"f",
"cx",
"cy",
"k0",
"k1",
"k2",
"k3",
"k4",
"k5",
"p0",
"p1",
"s0",
"s1",
"s2",
"s3"
]
},
"rational8": {
"K": [
3,
3
],
"distortion": [
"k1",
"k2",
"p1",
"p2",
"k3",
"k4",
"k5",
"k6"
]
}
},
"segmentation": {
"segment/uint16_labels/v1": {
"storage": "mask.mkv",
"dtype": "uint16",
"mapping": "instances.jsonl",
"valid_shape": [
"T"
],
"required_metadata": [
"segmentation_type",
"coverage",
"mapping_ref",
"storage"
],
"shape": [
"T",
"H",
"W"
],
"reserved_codes": {
"0": "unassigned",
"65535": "ignore"
},
"region_codes": [
1,
65534
],
"allowed_storage_profiles": [
"mkv/uint16_ffv1/v1"
]
},
"segment/instance_polygons/v1": {
"storage": "polygons.jsonl",
"mapping": "instances.jsonl",
"frame_keys": [
"frame_index",
"instances"
],
"instance_keys": [
"mask_value",
"polygons"
],
"coordinate_unit": "pixel",
"overlap_allowed": true,
"valid_shape": [
"T"
],
"required_metadata": [
"segmentation_type",
"coverage",
"mapping_ref"
],
"polygon_shape": [
"N",
2
],
"holes_supported": false
},
"segment/foreground_intensity/v1": {
"storage": "mask.mkv",
"dtype": "uint16",
"value_range": [
0,
255
],
"normalization_scale": 0.00392156862745098,
"axes": [
"T",
"height",
"width"
],
"meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability",
"zero": "background",
"full_scale": "foreground",
"mapping": "foreground_category in component metadata",
"valid_shape": [
"T"
],
"required_metadata": [
"segmentation_type",
"coverage",
"value_range",
"normalization_scale",
"foreground_category",
"entity_id",
"storage"
],
"shape": [
"T",
"H",
"W"
],
"allowed_storage_profiles": [
"mkv/uint16_ffv1/v1"
]
}
},
"note": "Registry for hand-warehouse/1.0. Read CONTRACT.md for field semantics. This is not a JSON Schema document or executable validator.",
"components": {
"mano/axis_angle61/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
2,
61
],
"valid_shape": [
"T",
2
],
"unit": "m",
"angle_unit": "rad",
"coordinate_frame": "camera",
"layout": {
"pose_axis_angle": [
0,
48
],
"shape": [
48,
58
],
"translation": [
58,
61
]
}
},
"keypoints/uv/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
2,
21,
2
],
"valid_shape": [
"T",
2,
21
],
"unit": "pixel",
"required_metadata": [
"keypoint_schema"
]
},
"keypoints/xyz/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
2,
21,
3
],
"valid_shape": [
"T",
2,
21
],
"unit": "m",
"required_metadata": [
"keypoint_schema"
]
},
"depth/z_float32/v1": {
"storage": "mkv",
"dtype": "float32",
"shape": [
"T",
"H",
"W"
],
"valid_shape": [
"T",
"H",
"W"
],
"unit": "m",
"depth_type": "z",
"pixel_grid": "current_rgb",
"coordinate_frame": "current_rgb_camera",
"valid_storage": "mkv",
"allowed_storage_profiles": [
"mkv/depth_float32_bits/v1"
],
"allowed_valid_storage_profiles": [
"mkv/bool_ffv1/v1"
],
"required_metadata": [
"storage",
"valid_storage",
"depth_origin"
],
"depth_origin_values": [
"measured",
"rendered",
"unknown"
]
},
"transform/se3/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
4,
4
],
"valid_shape": [
"T"
],
"unit": "m",
"required_metadata": [
"convention"
]
},
"object/rigid/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
4,
4
],
"valid_shape": [
"T"
],
"unit": "m",
"required_metadata": [
"convention"
]
},
"camera/pinhole/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
3,
3
],
"valid_shape": [
"T"
]
},
"camera/rational8/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
3,
3
],
"valid_shape": [
"T"
]
},
"camera/opencv_fisheye4/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
3,
3
],
"valid_shape": [
"T"
]
},
"camera/fisheye624/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
15
],
"valid_shape": [
"T"
]
},
"camera/distortion8/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
8
],
"valid_shape": [
"T"
]
},
"camera/fisheye4_distortion/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
4
],
"valid_shape": [
"T"
]
},
"object/joint_state/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
"J"
],
"valid_shape": [
"T",
"J"
],
"required_metadata": [
"joint_order"
],
"unit_rule": "revolute radians; prismatic metres; mixed types declared per joint"
},
"object_keypoints/camera/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
"K",
3
],
"valid_shape": [
"T",
"K"
],
"unit": "m",
"coordinate_frame": "camera",
"required_metadata": [
"keypoint_schema"
]
},
"object/dimensions/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
3
],
"valid_shape": [
"T"
],
"unit": "m",
"required_metadata": [
"dimensions_semantics"
],
"axis_order": [
"length",
"width",
"height"
],
"scale_rule": "do not apply to mesh without source-supported size/scale relation"
},
"object_keypoints/template/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"K",
3
],
"valid_shape": [
"K"
],
"unit": "m",
"coordinate_frame": "object",
"static": true,
"required_metadata": [
"keypoint_schema"
]
},
"mesh/obj/v1": {
"storage": "obj",
"unit": "m",
"static": true,
"valid_shape": [],
"dependencies": "MTL and textures retained under owning object"
},
"rgb/uint8/v1": {
"storage": "mkv",
"dtype": "uint8",
"shape": [
"T",
"H",
"W",
3
],
"valid_shape": [
"T"
],
"color_order": "RGB",
"allowed_storage_profiles": [
"mkv/mjpeg_copy/v1",
"mkv/source_copy/v1",
"mkv/h264_rgb_lossless/v1",
"mkv/ffv1_rgb/v1"
],
"required_metadata": [
"storage"
]
},
"contact/relations/v1": {
"storage": "jsonl",
"valid_shape": [
"T"
],
"frame_keys": [
"frame_index",
"relations"
],
"absence_semantics": "no record is not a negative contact annotation"
},
"contact/vertex_region/v1": {
"storage": "pt",
"dtype": "bool",
"shape": [
"T",
"V"
],
"valid_shape": [
"T",
"V"
],
"required_metadata": [
"source_geometry_ref",
"target_geometry_ref",
"topology_id"
],
"pilot_status": "defined_not_empirically_validated"
},
"contact/vertex_distance/v1": {
"storage": "pt",
"dtype": "float32",
"shape": [
"T",
"V"
],
"valid_shape": [
"T",
"V"
],
"unit": "m",
"required_metadata": [
"source_geometry_ref",
"target_geometry_ref",
"topology_id",
"distance_definition"
],
"pilot_status": "defined_not_empirically_validated"
},
"object/articulated/v1": {
"storage": "json",
"required_keys": [
"parts",
"joints"
],
"part_keys": [
"part_id",
"parent_id",
"has_model",
"mesh_ref"
],
"hierarchy_semantics": "declare mechanical articulation or semantic containment; containment alone does not imply joints",
"acyclic": true
},
"segment/uint16_labels/v1": {
"storage": "mkv",
"dtype": "uint16",
"mapping": "instances.jsonl",
"valid_shape": [
"T"
],
"required_metadata": [
"segmentation_type",
"coverage",
"mapping_ref",
"storage"
],
"shape": [
"T",
"H",
"W"
],
"reserved_codes": {
"0": "unassigned",
"65535": "ignore"
},
"region_codes": [
1,
65534
],
"allowed_storage_profiles": [
"mkv/uint16_ffv1/v1"
]
},
"segment/instance_polygons/v1": {
"storage": "jsonl",
"mapping": "instances.jsonl",
"frame_keys": [
"frame_index",
"instances"
],
"instance_keys": [
"mask_value",
"polygons"
],
"coordinate_unit": "pixel",
"overlap_allowed": true,
"valid_shape": [
"T"
],
"required_metadata": [
"segmentation_type",
"coverage",
"mapping_ref"
],
"polygon_shape": [
"N",
2
],
"holes_supported": false
},
"segment/foreground_intensity/v1": {
"storage": "mkv",
"dtype": "uint16",
"value_range": [
0,
255
],
"normalization_scale": 0.00392156862745098,
"axes": [
"T",
"height",
"width"
],
"meaning": "native hand foreground intensity; individual hand or union declared in metadata; not instance codes or calibrated probability",
"zero": "background",
"full_scale": "foreground",
"mapping": "foreground_category in component metadata",
"valid_shape": [
"T"
],
"required_metadata": [
"segmentation_type",
"coverage",
"value_range",
"normalization_scale",
"foreground_category",
"entity_id",
"storage"
],
"shape": [
"T",
"H",
"W"
],
"allowed_storage_profiles": [
"mkv/uint16_ffv1/v1"
]
}
},
"storage_revision": "lossless-video-2026-09-18",
"sampling": {
"image": {
"single": {
"T": 1
},
"independent": {
"T": ">=2",
"required_frame_fields": [
"sample_id",
"source_locator"
],
"temporal_relationship": false
},
"source_fps": null
},
"video": {
"sampling_types": [
"dense",
"sparse"
]
}
},
"storage_profiles": {
"mkv/mjpeg_copy/v1": {
"container": "matroska",
"codec": "mjpeg",
"method": "stream_copy_from_source_jpeg",
"logical_dtype": "uint8",
"decoded_pixel_format": "rgb24",
"validation": [ "source_jpeg_packet_sha256_exact", "all_packet_count_order_and_dimensions_exact", "deterministic_decoded_rgb_sample_exact", "pilot_and_final_selected_whole_sequences_decoded_rgb_exact" ], "validation_policy": { "id": "jpeg-packets-all-rgb-sample16/v1", "sample_count_per_view": 16, "short_views": "all_frames_if_T_less_than_16", "fixed_indices": "0,T-1,T//4,T//2,3*T//4, deduplicated", "remaining_indices": "sample without replacement to min(T,16) using Python random.Random(seed)", "seed": "first 8 bytes of SHA256(sequence_id/camera_id/20260920), big-endian integer", "report": "policy, exact selected frame indices, seed, separate packet and pixel coverage", "legacy_all_frame_pixel_proofs": "still accepted; preserve historical evidence" } },
"mkv/source_copy/v1": {
"container": "matroska",
"codec": "source_codec_declared_in_metadata",
"method": "stream_copy_only",
"logical_dtype": "uint8",
"decoded_pixel_format": "rgb24",
"validation": [
"no_reencoding",
"all_decoded_rgb_frames_exact",
"presentation_frame_order_exact"
]
},
"mkv/h264_rgb_lossless/v1": {
"container": "matroska",
"codec": "h264",
"encoder": "libx264rgb",
"crf": 0,
"decoded_pixel_format": "rgb24",
"logical_dtype": "uint8",
"gop": "declared_in_encoder_parameters",
"validation": [
"all_decoded_rgb_frames_exact"
],
"forbidden": [
"lossy_rate_control",
"rgb_to_yuv420_subsampling"
]
},
"mkv/ffv1_rgb/v1": {
"container": "matroska",
"codec": "ffv1",
"decoded_pixel_format": "rgb24",
"logical_dtype": "uint8",
"validation": [
"all_decoded_rgb_frames_exact"
]
},
"mkv/depth_float32_bits/v1": {
"container": "matroska",
"codec": "ffv1",
"pixel_format": "gray16le",
"logical_dtype": "float32",
"logical_shape": [
"T",
"H",
"W"
],
"encoded_shape": [
"T",
"H",
"2*W"
],
"packing": "IEEE754 little-endian float32 bits; low uint16 in first W columns, high uint16 in last W columns",
"decode": "reinterpret_float32(uint32(low) | (uint32(high) << 16))",
"validation": [
"all_float32_bits_exact_including_nan"
]
},
"mkv/bool_ffv1/v1": {
"container": "matroska",
"codec": "ffv1",
"pixel_format": "gray",
"logical_dtype": "bool",
"stored_values": [
0,
1
],
"validation": [
"all_bool_values_exact"
]
},
"mkv/uint16_ffv1/v1": {
"container": "matroska",
"codec": "ffv1",
"pixel_formats": [
"gray",
"gray16le"
],
"logical_dtype": "uint16",
"gray_condition": "all values <=255; decode by exact uint8-to-uint16 promotion",
"validation": [
"all_integer_values_exact"
]
}
},
"video_metadata": {
"required": [
"profile",
"codec",
"pixel_format",
"encoded_size",
"decoder",
"encoder_parameters",
"source_lossy"
],
"source_lossy_values": [
true,
false,
"unknown"
],
"timebase_role": "index_only",
"lossless_reference": "source compressed packets or fixed-decoder source pixels; depth uses normalized standard float32 bits",
"selection": "choose smaller complete candidate only after exact roundtrip validation"
}
}12345678Verified existing subject1/h1/0Verified existing subject2/h1/0Verified existing subject1/h1/6Verified existing subject1/h1/3Verified existing subject2/h1/6Converted subject3/h1/0Verified existing subject1/h1/7Converted subject4/h1/01234567START=2026-09-30T10:22:30+08:00WORKERS=4 CODEC_THREADS=10 SUBJECTS=1,2,3,4 CASA=falseCPU_LIMIT=noneCGROUP=/user.slice/user-25044.slice/user@25044.service/app.slice/h2o-full-w4c10-r2-20260930.scopeCPU_MAX=max controller_disabled
RECONFIGURE=2026-09-30T11:03:03+08:00 REASON=decoder10_depth4_no_resume_png_writes1234567891011121314151617181920212223242526#!/usr/bin/env bashset -ubase="$HOME/Datasets/uni-hoi-h2o-full-20260930-w4-c10"raw="$HOME/Datasets/Hand-Datasets-Raw/H2O"cd "$HOME/Projects/uni-hoi-dataset" || exit 1mkdir -p "$base/scratch"export TMPDIR="$base/scratch" PYTHONUNBUFFERED=1for n in 1 2 3 4; do test -s "$raw/raw/data/subject${n}_v1_1.tar.gz" || exit 2; donetest ! -e "$base/full.status" || exit 3cg=$(awk -F: '$1=="0" {print $3}' /proc/self/cgroup)if [[ -f "/sys/fs/cgroup$cg/cpu.max" ]]; then read -r quota period < "/sys/fs/cgroup$cg/cpu.max"else quota=max period=controller_disabledfiprintf 'START=%s\nWORKERS=4 CODEC_THREADS=10 SUBJECTS=1,2,3,4 CASA=false\nCPU_LIMIT=none\nCGROUP=%s\nCPU_MAX=%s %s\n' "$(date -Is)" "$cg" "$quota" "$period" > "$base/full.status"if [[ "$quota" != max ]]; then printf 'EXIT=4 ERROR=UNEXPECTED_CPU_QUOTA\n' >> "$base/full.status" exit 4fi/usr/bin/time -v .venv/bin/python "$base/frozen-code/scripts/convert_h2o_v1.0.py" --root "$raw" --out "$base" --release-id shared-v1.0 --workers 4 --codec-threads 10 --mano-dir "$HOME/Projects/WiLoR/mano_data" > "$base/full.log" 2>&1code=$?printf 'EXIT=%s END=%s\n' "$code" "$(date -Is)" >> "$base/full.status"if [[ -f "/sys/fs/cgroup$cg/cpu.stat" ]]; then cat "/sys/fs/cgroup$cg/cpu.stat" >> "$base/full.status"; fiexit "$code"12345678910111213141516171819202122232425262728293031#!/usr/bin/env python3"""Check saved Dex-YCB source 3D joints against saved source 2D joints in sampled views."""import jsonfrom pathlib import Pathimport sys
import numpy as npimport torch
root = Path(sys.argv[1])report = json.loads((root / 'doc/validation/STRUCTURAL_AUDIT.json').read_text())checks = []for name in report['sampled_views']: view = root / name load = lambda path: torch.load(view / path, weights_only=True, map_location='cpu').numpy() k = load('camera/intrinsic.pt') xyz = load('annotation/keypoints/xyz.pt') uv = load('annotation/keypoints/uv.pt') valid = load('annotation/keypoints/xyz_valid.pt') & load('annotation/keypoints/uv_valid.pt') z = xyz[..., 2] valid &= np.isfinite(xyz).all(axis=-1) & np.isfinite(uv).all(axis=-1) & (z > 0) z = np.where(valid, z, 1) pred = np.stack((k[:, 0, 0, None, None] * xyz[..., 0] / z + k[:, 0, 2, None, None], k[:, 1, 1, None, None] * xyz[..., 1] / z + k[:, 1, 2, None, None]), axis=-1) errors = np.linalg.norm(pred[valid] - uv[valid], axis=-1) checks.append(dict(view=name, points=int(errors.size), median_px=float(np.median(errors)) if errors.size else None, p95_px=float(np.percentile(errors, 95)) if errors.size else None))(root / 'doc/validation/KEYPOINT_PROJECTION_QC.json').write_text(json.dumps({ 'scope': 'Saved source 3D joints projected with saved color intrinsics vs saved source 2D joints; independent of hand mesh rendering.', 'views': checks}, ensure_ascii=False, indent=2) + '\n')print(json.dumps(checks, ensure_ascii=False), flush=True)123456789101112131415{ "root": "/home/xuzhefeng/Datasets/Hand-Datasets-Raw/H2O", "out": "/home/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10", "release_id": "shared-v1.0", "limit": null, "max_frames": null, "mano_dir": "/home/xuzhefeng/Projects/WiLoR/mano_data", "views": null, "jpeg_full_check": false, "workers": 4, "codec_threads": 10, "subjects": null, "include_casa": false, "archive": null}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349#!/usr/bin/env python3"""Dex-YCB source annotations → CONTRACT.md v1.0. No derived annotations."""import ioimport reimport shutilimport tarfileimport tempfilefrom pathlib import Path
import numpy as npfrom PIL import Imageimport yaml
from warehouse_v1_0 import (View, build_record, find_file, locator, mano_models, mesh_asset, model_profile, parser, pca_to_axis_angle, release, roots, safe_member, sequence_dir)
IMG_W, IMG_H = 640, 480
class _Loader(yaml.SafeLoader): pass
_Loader.add_constructor("tag:yaml.org,2002:python/tuple", lambda l, n: tuple(l.construct_sequence(n)))
def yaml_load_bytes(data: bytes): return yaml.load(io.BytesIO(data), Loader=_Loader)
class Calibration: def __init__(self, dexycb_root: Path): self.intrinsics = {} # serial -> {fx,fy,cx,cy,w,h} self.extrinsics = {} # group -> {serial: [12] 行优先 3×4 cam→world} self.betas = {} # mano_calib_name -> [10] calib_dir = dexycb_root / "calibration" if calib_dir.is_dir(): self._load((p.as_posix(), p.read_bytes()) for p in sorted(calib_dir.rglob("*")) if p.is_file()) else: tar_path = dexycb_root / "calibration.tar.gz" if not tar_path.exists(): raise FileNotFoundError(f"no calibration/ nor calibration.tar.gz in {dexycb_root}") with tarfile.open(tar_path, "r:gz") as tf: self._load((m.name, tf.extractfile(m).read()) for m in tf if m.isfile())
_RE_INTR = re.compile(r"(?:^|/)intrinsics/(\d+)_\d+x\d+\.yml$") _RE_EXTRA = re.compile(r"(?:^|/)extrinsics_(\d{8}_\d{6})/extrinsics\.yml$") _RE_MANO = re.compile(r"(?:^|/)mano_(\d{8}_\d{6}_subject-\d{2}_right)/mano\.yml$")
def _load(self, files): for rel, data in files: m = self._RE_INTR.search(rel) if m: c = yaml_load_bytes(data)["color"] self.intrinsics[m.group(1)] = {"fx": float(c["fx"]), "fy": float(c["fy"]), "cx": float(c["ppx"]), "cy": float(c["ppy"]), "w": IMG_W, "h": IMG_H} continue m = self._RE_EXTRA.search(rel) if m: raw = yaml_load_bytes(data)["extrinsics"] self.extrinsics[m.group(1)] = { str(s): [float(x) for x in np.asarray(v).ravel()] for s, v in raw.items()} continue m = self._RE_MANO.search(rel) if m: self.betas[m.group(1)] = [float(b) for b in yaml_load_bytes(data)["betas"]]
def calibration_locator(path, member, **extra): if path.is_dir(): return locator(path / member.removeprefix('calibration/'), **extra) return locator(path, member, **extra)
def prepare_models(root, destination): archive = find_file(root, 'models.tar.gz') if archive is None: return {}, None pattern = re.compile(r'^models/(\d{3}_[a-z0-9_]+)/(textured_simple\.obj(?:\.mtl)?|texture_map\.png)$') names = set() with tarfile.open(archive, 'r|gz') as tf: for member in tf: match = pattern.fullmatch(member.name) if member.isfile() and match: names.add(match[1]) path = safe_member(destination, '/'.join(match.groups())) path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(tf.extractfile(member).read()) if len(names) != 21: raise ValueError('expected all 21 source YCB model directories') return {i: destination / name for i, name in enumerate(sorted(names), 1)}, archive
def convert_view(path, args, seq, serial, frames, meta, meta_loc, calib, calib_path, models, assets, asset_archive): total = int(meta.get('num_frames', max(frames) + 1)) ids = list(range(min(total, args.max_frames) if args.max_frames else total)) for f in ids: frames.setdefault(f, {}) if not ids: raise ValueError('no RGB frames') source_rows = [] for f in ids: row = frames[f] source_rows.append(dict(source_frame_id=f, sync_id=f'{seq}:{f}', source_locator=row['color'][1] if 'color' in row else (meta_loc | {'source_frame_id': f, 'missing_rgb': True}), annotation_matches={ 'labels': {'source_frame_id': f, 'source_timestamp_ns': None, 'clock_domain': None, 'match_method': 'index_map', 'delta_ns': None, 'source_locator': row['labels'][1]} for _ in [0] if 'labels' in row}, component_sources={k: v[1] for k, v in row.items()})) view = View(path, 'dex-ycb', args.release_id, seq, serial, source_rows, sampling='dense' if ids == list(range(ids[0], ids[-1] + 1)) else 'sparse') view.valid_rules = { 'mano': 'Source pose_m present and not all zero; side model/calibration available', 'keypoints': 'Corresponding joint_2d/joint_3d present; whole-hand all -1 is missing, broadcast to its 21 points', 'pose': 'Source pose_y for this ycb_ids slot present and not an all-zero matrix', 'segment': 'Source seg array provided for this frame; region codes and entity references validated', 'relations': 'Source sequence ycb_grasp_ind resolves through ycb_ids; broadcast sequence grasp to selected frames', } view.full_jpeg = getattr(args, 'jpeg_full_check', False) view.meta['view_type'] = 'exo' view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} subject = re.search(r'subject-(\d+)', seq) if subject and 1 <= int(subject[1]) <= 10: index = int(subject[1]) view.meta.update(split='val' if index == 7 else 'test' if index in (8, 9) else 'train', split_scheme='Dex-YCB/s1', split_source_locator={ 'url': 'https://github.com/NVlabs/dex-ycb-toolkit/blob/master/dex_ycb_toolkit/dex_ycb.py', 'rule': 's1 unseen-subject: 01-06/10 train, 07 val, 08-09 test'}) view.meta.pop('split_reason', None) view.rgb([frames[f]['color'][0] if 'color' in frames[f] else None for f in ids], {'frames_ref': 'camera/frames.jsonl'}) n = len(ids) intr = calib.intrinsics.get(serial) K = None if intr is None else np.array([[intr['fx'], 0, intr['cx']], [0, intr['fy'], intr['cy']], [0, 0, 1]]) ext = calib.extrinsics.get(str(meta['extrinsics']), {}).get(serial) E = None if ext is not None: E = np.eye(4) E[:3] = np.asarray(ext).reshape(3, 4) E = np.linalg.inv(E) view.camera(K, calibration_locator(calib_path, f'calibration/intrinsics/{serial}_640x480.yml'), E, calibration_locator(calib_path, f'calibration/extrinsics_{meta["extrinsics"]}/extrinsics.yml', conversion='inverse of source T_world_from_camera')) sides = meta.get('mano_sides') if sides not in (['left'], ['right']): raise ValueError(f'expected exactly one anatomical source hand: {sides}') side = sides[0] slot = ['left', 'right'].index(side) cal_name = meta['mano_calib'][0] if isinstance(meta['mano_calib'], list) else meta['mano_calib'] labels = [dict(np.load(frames[f]['labels'][0])) if 'labels' in frames[f] else {} for f in ids] label_loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources.labels'} motion = np.full((n, 2, 61), np.nan, np.float32) mv = np.zeros((n, 2), bool) if side in models and any('pose_m' in lab for lab in labels): for i, lab in enumerate(labels): if 'pose_m' not in lab: continue pose = np.asarray(lab['pose_m']).reshape(51) if not np.any(pose): # Official Dex-YCB missing-pose sentinel, independent of joints/seg. continue motion[i, slot] = np.r_[pose[:3], pca_to_axis_angle(pose[3:48], models[side]), calib.betas[cal_name], pose[48:51]] mv[i, slot] = True view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, ['T', 'hand', 'parameter'], label_loc, model_profile=model_profile(models), calibration_source=calibration_locator(calib_path, f'calibration/mano_{cal_name}/mano.yml'), provenance={'kind': 'format_conversion', 'method': 'source PCA @ hands_components + hands_mean; explicit axis-angle consumed with flat_hand_mean=true'}) elif any('pose_m' in lab for lab in labels): view.absent('mano', 'Source PCA exists; provide --mano-dir to expand it', 'dependency_missing') else: view.absent('mano', 'No source pose_m field') for source_key, key, dim, unit in [('joint_2d', 'uv', 2, 'pixel'), ('joint_3d', 'xyz', 3, 'm')]: if not any(source_key in x for x in labels): view.absent('keypoints_' + key, 'No source ' + source_key) continue points = np.full((n, 2, 21, dim), np.nan, np.float32) valid = np.zeros((n, 2, 21), bool) for i, lab in enumerate(labels): if source_key not in lab: continue p = np.asarray(lab[source_key]).reshape(21, dim) points[i, slot] = p valid[i, slot] = not np.all(p == -1) # Official sentinel covers the whole source hand. # An individual off-image point (-1, -1) is not evidence of missing annotation. view.tensor('keypoints_' + key, f'keypoints/{key}/v1', f'annotation/keypoints/{key}.pt', points, valid, ['T', 'hand', 'keypoint', 'coordinate'], label_loc, keypoint_schema='mano21/v1', unit=unit) ycb_ids = [int(x) for x in meta['ycb_ids']] for j, oid in enumerate(ycb_ids): entity = f'ycb_{oid:02d}' view.object(entity, meta_loc, source_object_id=oid, category_id=oid) poses = np.full((n, 4, 4), np.nan, np.float32) valid = np.zeros(n, bool) for i, lab in enumerate(labels): if 'pose_y' in lab: pose = np.asarray(lab['pose_y']) if pose.shape != (len(ycb_ids), 3, 4): raise ValueError('pose_y shape differs from ycb_ids') if np.any(pose[j]): # Official all-zero missing object pose sentinel. poses[i] = np.eye(4) poses[i, :3] = pose[j] valid[i] = True if any('pose_y' in lab for lab in labels): view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', poses, valid, ['T', 'row', 'column'], label_loc, convention='T_camera_from_object', unit='m') else: view.absent('pose_' + entity, 'No source pose_y field') if oid in assets: mesh_asset(view, entity, assets[oid], assets[oid] / 'textured_simple.obj', locator(asset_archive, f'models/{assets[oid].name}/textured_simple.obj')) else: view.absent('mesh_' + entity, 'models.tar.gz unavailable', 'not_downloaded') if any('seg' in lab for lab in labels): mask_rows = [] width, height = view.meta['camera']['image_size'] for i, lab in enumerate(labels): values = np.unique(lab.get('seg', np.zeros((height, width), np.uint8))) mappings = [] for value in values: value = int(value) if value == 0: continue if value != 255 and value not in ycb_ids: raise ValueError(f'unknown Dex-YCB region value {value}') mappings.append(dict(mask_value=value, category_id='hand' if value == 255 else value, entity_id='hand_' + side if value == 255 else f'ycb_{value:02d}', part_id=None, source_instance_id=value)) mask_rows.append(dict(frame_index=i, labels=mappings)) view.raster('segment', (lab.get('seg', np.zeros((height, width), np.uint16)) for lab in labels), ['seg' in lab for lab in labels], label_loc, mask_rows) view.meta['components']['segment'].update(coverage={'kind': 'selected_entities', 'entities': ['hand_' + side] + [f'ycb_{o:02d}' for o in ycb_ids]}, source_zero_meaning='background') else: view.absent('segment', 'No source seg field') if any('aligned_depth_to_color' in frames[f] for f in ids): def depths(): width, height = view.meta['camera']['image_size'] for f in ids: item = frames[f].get('aligned_depth_to_color') if item is None: yield np.full((height, width), np.nan, np.float32) else: with Image.open(item[0]) as im: yield np.asarray(im).astype(np.float32) / 1000.0 view.raster('depth', depths(), None, {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources.aligned_depth_to_color', 'conversion': 'millimetres to metres'}) else: view.absent('depth', 'No source aligned_depth_to_color frames') grasp = meta.get('ycb_grasp_ind') if grasp is not None: if not 0 <= int(grasp) < len(ycb_ids): raise ValueError('invalid ycb_grasp_ind') relation = dict(relation_type='grasp', subject_id='hand_' + side, object_id=f'ycb_{ycb_ids[int(grasp)]:02d}', status='positive', source_locator=meta_loc, provenance={'kind': 'source', 'method': 'sequence ycb_grasp_ind resolved through ycb_ids; not per-frame contact'}) view.relations([{'frame_index': i, 'relations': [relation]} for i in range(n)], np.ones(n, bool), meta_loc) else: view.absent('relations', 'No source grasp/contact relation') return view.finish()
MEMBER = re.compile(r'^([^/]+)/(\d{8}_\d{6})/(meta\.yml|(\d{12})/(color|labels|aligned_depth_to_color)_(\d+)\.(jpg|npz|png))$')
def convert_archive(archive, args, out, calib, calib_path, models, assets, asset_archive): selected_views = set(args.views.split(',')) if args.views else None done = 0 current, meta, meta_loc, rows = None, None, None, {} with tempfile.TemporaryDirectory(prefix='dex-source-') as wd: work = Path(wd) def flush(): nonlocal done if not rows: return seq = archive.name.split('.tar')[0] + '_' + current reports = {} with sequence_dir(out, seq) as target: for serial, frames in sorted(rows.items()): reports[serial] = convert_view(target / serial, args, seq, serial, frames, meta, meta_loc, calib, calib_path, models, assets, asset_archive) build_record(out, seq, reports) for staged in list(work.iterdir()): if staged.is_dir(): shutil.rmtree(staged) else: staged.unlink() done += 1 print(f'Converted {seq}', flush=True) with tarfile.open(archive, 'r|gz') as tf: for member in tf: match = MEMBER.fullmatch(member.name) if not member.isfile() or not match: continue seq = match[2] if seq != current: flush() if args.limit and done >= args.limit: break current, meta, meta_loc, rows = seq, None, None, {} data_kind = match[3] if data_kind == 'meta.yml': data = tf.extractfile(member).read() meta = yaml_load_bytes(data) meta_loc = locator(archive, member.name, data) continue serial, kind, f = match[4], match[5], int(match[6]) if selected_views and serial not in selected_views or args.max_frames and f >= args.max_frames: continue data = tf.extractfile(member).read() dest = safe_member(work, member.name) dest.parent.mkdir(parents=True, exist_ok=True) dest.write_bytes(data) row = rows.setdefault(serial, {}).setdefault(f, {}) if kind in row: raise ValueError('duplicate archive frame') row[kind] = (dest, locator(archive, member.name, data)) else: flush() return done
def main(argv=None): p = parser('dex-ycb', __doc__) p.add_argument('--subjects') args = p.parse_args(argv) archives = sorted({a for r in roots(args.root) for a in r.glob('*-subject-*.tar.gz')}) if args.subjects: subjects = {s.strip().zfill(2) for s in args.subjects.split(',')} archives = [a for a in archives if re.search(r'subject-(\d+)', a.name)[1] in subjects] if not archives: p.error('no Dex-YCB subject archives found') cp = find_file(args.root, 'calibration.tar.gz') or find_file(args.root, 'calibration') if cp is None: p.error('calibration source missing') calib = Calibration(cp.parent) models = mano_models(args.mano_dir) out = release(args, 'dex-ycb') with tempfile.TemporaryDirectory(prefix='dex-models-') as wd: assets, asset_archive = prepare_models(args.root, Path(wd)) for archive in archives: convert_archive(archive, args, out, calib, cp, models, assets, asset_archive) return 0
if __name__ == '__main__': raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527#!/usr/bin/env python3"""H2O native RGB-D, MANO, joints and objects → CONTRACT.md v1.0 (no rendered masks)."""from concurrent.futures import ThreadPoolExecutorimport jsonimport osimport reimport shutilimport tarfileimport tempfilefrom pathlib import Pathimport zipfile
# Bound native libraries before loading NumPy/Torch; each worker still uses independent FFmpeg processes.for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): os.environ[key] = '1'
import numpy as npfrom PIL import Imageimport torch
from warehouse_v1_0 import (View, build_record, check_mesh, find_file, locator, mano_models, mesh_asset, model_profile, parser, release, roots, safe_member, sequence_dir, sha256)
OBJECTS = {1: 'book', 2: 'espresso', 3: 'lotion', 4: 'spray', 5: 'milk', 6: 'cocoa', 7: 'chips', 8: 'cappuccino'}MEMBER = re.compile(r'^(?:h2o_CASA/)?(subject\d+)/([^/]+)/(\d+)/(cam\d)/(.+)$')FRAME = re.compile(r'(rgb|depth|cam_pose|hand_pose|hand_pose_mano|obj_pose|obj_pose_rt)/(\d+)\.(png|jpg|txt)$')
def load_splits(root): archive = find_file(root, 'label_split.zip') result = {} if archive is not None: with zipfile.ZipFile(archive) as z: for split in ('train', 'val', 'test'): member = f'label_split/action_{split}.txt' for line_no, line in enumerate(z.read(member).decode().splitlines(), 1): fields = line.split() if len(fields) < 2 or fields[1] == 'path': continue key = fields[1] if key in result and result[key][0] != split: raise ValueError('conflicting official splits') result[key] = (split, locator(archive, member, record=line_no)) return result
def load_assets(root, work): archive = find_file(root, 'object.zip') if archive is None: return {}, None with zipfile.ZipFile(archive) as z: for member in z.infolist(): if member.is_dir(): continue path = safe_member(work, member.filename) path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(z.read(member)) result = {} for oid, name in OBJECTS.items(): directory = work / 'object' / name aliases = [] # Source cocoa.obj -> ovomaltine.mtl -> cocoa.png, but the ZIP names the # supplied texture ovomaltine.png. Keep all originals and add a byte-identical alias. if name == 'cocoa' and not (directory / 'cocoa.png').exists(): mtl = directory / 'ovomaltine.mtl' if mtl.is_file() and 'map_Kd cocoa.png' in mtl.read_text().splitlines(): texture = directory / 'ovomaltine.png' shutil.copyfile(texture, directory / 'cocoa.png') aliases.append({'file': 'cocoa.png', 'sha256': sha256(texture), 'source': locator(archive, 'object/cocoa/ovomaltine.png')}) candidates = list(directory.glob('*.obj')) if len(candidates) != 1: raise ValueError(f'expected one source OBJ for {name}') check_mesh(candidates[0], directory) # Fail before decoding any large subject archive. result[oid] = (directory, candidates[0], aliases) return result, archive
def convert_view(path, args, seq, cam, rows, intr, splits, models, assets, asset_archive): codec_threads = getattr(args, 'codec_threads', 1) ids = list(range(min(rows), max(rows) + 1)) for f in ids: rows.setdefault(f, {}) n = len(ids) if not n: raise ValueError('no RGB frames') split, split_loc = splits.get(seq, ('unknown', None)) frame_rows = [dict(source_frame_id=f, sync_id=f'{seq}:{f}', source_locator=rows[f]['rgb'][1] if 'rgb' in rows[f] else {'sequence': seq, 'camera': cam, 'source_frame_id': f, 'missing_rgb': True}, component_sources={k: item[1] for k, item in rows[f].items()}, annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, clock_domain=None, match_method='index_map', delta_ns=None) for k in rows[f] if k != 'rgb'}) for f in ids] view = View(path, 'H2O', args.release_id, seq.replace('/', '_'), cam, frame_rows, split=split) view.valid_rules = { 'mano': 'Per-hand hand_pose_mano flag equals 1; corresponding side model available', 'keypoints': "Per-hand hand_pose flag equals 1, broadcast to that hand's 21 source points independently of MANO", 'pose': 'Source obj_pose_rt class equals this nonzero object class', 'points': 'Source obj_pose class equals this nonzero object class, broadcast to its 21 points', } view.full_jpeg = getattr(args, 'jpeg_full_check', False) view.meta['view_type'] = 'ego' if cam == 'cam4' else 'exo' if cam in ('cam0', 'cam1', 'cam2', 'cam3') else 'unknown' view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'views': args.views} if split_loc: view.meta.update(split_scheme='official_action_split', split_source_locator=split_loc) # In the measured 275 H2O views, exact FFV1 was always smaller than exact H.264. view.rgb([rows[f]['rgb'][0] if 'rgb' in rows[f] else None for f in ids], {'frames_ref': 'camera/frames.jsonl'}, ffv1_first=True, codec_threads=codec_threads) loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} if intr is not None: fx, fy, cx, cy, width, height = np.loadtxt(intr[0]).ravel() if [int(width), int(height)] != view.meta['camera']['image_size']: raise ValueError('source intrinsics resolution mismatch') K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) view.camera(K, intr[1]) camps = np.full((n, 4, 4), np.nan, np.float32) cv = np.zeros(n, bool) data = [] for i, f in enumerate(ids): lab = {k: np.loadtxt(item[0]).ravel() for k, item in rows[f].items() if k not in ('rgb', 'depth')} data.append(lab) if 'cam_pose' in lab: camps[i] = np.linalg.inv(lab['cam_pose'].reshape(4, 4)) cv[i] = True if cv.any(): view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', camps, cv, ['T', 'row', 'column'], loc, convention='T_camera_from_world', source_convention='T_world_from_camera') motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) points, pv = np.full((n, 2, 21, 3), np.nan, np.float32), np.zeros((n, 2, 21), bool) object_ids = set() for i, lab in enumerate(data): if 'hand_pose_mano' in lab: hands = lab['hand_pose_mano'].reshape(2, 62) for side, row in enumerate(hands): if row[0] not in (0, 1): raise ValueError('unexpected H2O MANO presence flag') if row[0] == 1: motion[i, side] = np.r_[row[4:52], row[52:62], row[1:4]] mv[i, side] = True if 'hand_pose' in lab: hands = lab['hand_pose'].reshape(2, 64) for side, row in enumerate(hands): if row[0] not in (0, 1): raise ValueError('unexpected H2O keypoint presence flag') if row[0] == 1: points[i, side] = row[1:].reshape(21, 3) pv[i, side] = True for key in ('obj_pose', 'obj_pose_rt'): if key in lab and lab[key][0] != 0: object_ids.add(int(lab[key][0])) if any('hand_pose_mano' in lab for lab in data): if len(models) == 2: view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) else: view.absent('mano', 'Source parameters exist; --mano-dir must identify both model profiles', 'dependency_missing') if any('hand_pose' in lab for lab in data): view.tensor('keypoints_xyz', 'keypoints/xyz/v1', 'annotation/keypoints/xyz.pt', points, pv, ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='m') for oid in sorted(object_ids): if oid not in OBJECTS: raise ValueError(f'unknown H2O object class {oid}') entity = OBJECTS[oid] view.object(entity, loc, category_id=oid, source_object_id=oid) poses, ov = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) pts, kv = np.full((n, 21, 3), np.nan, np.float32), np.zeros((n, 21), bool) for i, lab in enumerate(data): if 'obj_pose_rt' in lab and lab['obj_pose_rt'][0] == oid: poses[i] = lab['obj_pose_rt'][1:].reshape(4, 4) ov[i] = True if 'obj_pose' in lab and lab['obj_pose'][0] == oid: pts[i] = lab['obj_pose'][1:].reshape(21, 3) kv[i] = True if ov.any(): view.tensor('pose_' + entity, 'object/rigid/v1', f'annotation/object/{entity}/pose.pt', poses, ov, ['T', 'row', 'column'], loc, convention='T_camera_from_object', unit='m') if kv.any(): view.tensor('points_' + entity, 'object_keypoints/camera/v1', f'annotation/object/{entity}/keypoints/xyz.pt', pts, kv, ['T', 'keypoint', 'coordinate'], loc, keypoint_schema='H2O_official_object21', keypoint_names=['center'] + [f'corner_{i}' for i in range(8)] + [f'edge_midpoint_{i}' for i in range(12)], source_order='official obj_point_order.jpg: center, 8 corners, 12 edge midpoints', unit='m') if oid in assets: directory, obj, aliases = assets[oid] asset_loc = locator(asset_archive, f'object/{entity}/{obj.name}') if aliases: asset_loc['texture_aliases'] = aliases mesh_asset(view, entity, directory, obj, asset_loc) else: view.absent('mesh_' + entity, 'Source object.zip unavailable', 'not_downloaded') if any('depth' in rows[f] for f in ids): width, height = view.meta['camera']['image_size'] def depths(): for f in ids: item = rows[f].get('depth') if item: with Image.open(item[0]) as im: yield np.asarray(im).astype(np.float32) / 1000.0 else: yield np.full((height, width), np.nan, np.float32) view.raster('depth', depths(), None, loc | {'source_field': 'component_sources.depth', 'definition': 'https://github.com/taeinkwon/h2oplayer/blob/main/utils.py', 'conversion': 'registered millimetre camera-Z to metres; no viewer range clipping'}, codec_threads=codec_threads) else: view.absent('depth', 'No source depth frames') view.absent('segment', 'H2O provides no native segmentation; rendering deferred to v2.0') view.absent('relations', 'No source contact/grasp annotation') return view.finish()
def convert_archive(archive, args, out, splits, models, assets, asset_archive): selected_views = set(args.views.split(',')) if args.views else None subjects = {'subject' + s.strip() for s in args.subjects.split(',')} if args.subjects else None current, rows, intrinsics, done = None, {}, {}, 0 with tempfile.TemporaryDirectory(prefix='h2o-source-') as wd: work = Path(wd) def flush(): nonlocal done if not rows: return seq = '/'.join(current) reports, pending = {}, {} for cam, frames in sorted(rows.items()): existing = out / 'data' / seq.replace('/', '_') / cam if (existing / 'metainfo.json').is_file(): old_frames = [json.loads(line) for line in (existing / 'camera/frames.jsonl').read_text().splitlines()] if [f['source_frame_id'] for f in old_frames] != list(range(min(frames), max(frames) + 1)): raise ValueError('existing view has different sampling; choose a new release-id') for frame in old_frames: incoming = frames.get(frame['source_frame_id'], {}) previous = frame.get('component_sources', {}) if set(previous) != set(incoming) or any(previous[k].get('sha256') != v[1].get('sha256') for k, v in incoming.items()): raise ValueError('duplicate H2O view differs from the published source; choose a new release-id') else: pending[cam] = frames if pending: with sequence_dir(out, seq.replace('/', '_')) as target: for cam, frames in pending.items(): reports[cam] = convert_view(target / cam, args, seq, cam, frames, intrinsics.get(cam), splits, models, assets, asset_archive) build_record(out, seq.replace('/', '_'), reports) for staged in list(work.iterdir()): if staged.is_dir(): shutil.rmtree(staged) else: staged.unlink() done += 1 print(f'{"Converted" if pending else "Verified existing"} {seq}', flush=True) # Uncompressed CASA supports seeking over large frames; gzip is single-pass. mode = 'r:' if archive.suffix == '.tar' else 'r|gz' with tarfile.open(archive, mode) as tf: for member in tf: match = MEMBER.fullmatch(member.name) if not member.isfile() or not match: continue subj, scene, seq, cam, tail = match.groups() if subjects and subj not in subjects: continue key = (subj, scene, seq) if key != current: flush() if args.limit and done >= args.limit: break current, rows, intrinsics = key, {}, {} if selected_views and cam not in selected_views: continue frame = FRAME.fullmatch(tail) if tail != 'cam_intrinsics.txt' and not frame: continue if frame and args.max_frames and int(frame[2]) >= args.max_frames: continue data = tf.extractfile(member).read() dest = safe_member(work, member.name) dest.parent.mkdir(parents=True, exist_ok=True) dest.write_bytes(data) item = (dest, locator(archive, member.name, data)) if tail == 'cam_intrinsics.txt': intrinsics[cam] = item else: kind, f = frame[1], int(frame[2]) row = rows.setdefault(cam, {}).setdefault(f, {}) if kind in row: raise ValueError('duplicate H2O frame') row[kind] = item else: flush() return done
def main(argv=None): p = parser('H2O', __doc__) p.set_defaults(release_id='shared-v1.0') p.add_argument('--workers', type=int, choices=range(1, 5), default=1, help='Independent subject archives in parallel, 1..4; benchmark before using >2') p.add_argument('--codec-threads', type=int, choices=(1, 2, 4, 8, 10), default=4, help='FFV1 slice threads per encode; default 4, use 10 for the current full run') p.add_argument('--subjects') p.add_argument('--include-casa', action='store_true') p.add_argument('--archive', type=Path, help='Convert one explicit source archive') args = p.parse_args(argv) if args.include_casa and args.workers != 1: p.error('CASA can share sequence IDs with subject archives; convert it sequentially in a separate release') archives = [args.archive.expanduser()] if args.archive else sorted( {a for root in roots(args.root) for a in root.glob('subject*_v1_1.tar.gz')}) if args.subjects and not args.archive: requested = {'subject' + s.strip() for s in args.subjects.split(',')} archives = [arc for arc in archives if arc.name.split('_', 1)[0] in requested] if args.include_casa: casa = find_file(args.root, 'h2o_CASA.tar') if casa: archives.append(casa) if not archives: p.error('no H2O archives found') out = release(args, 'H2O') source_mapping = next(p for p in (Path(__file__).resolve().parents[1] / 'docs/h2o-RAW_TO_SHARED.md', Path(__file__).resolve().parents[1] / 'doc/RAW_TO_SHARED.md', out / 'doc/RAW_TO_SHARED.md') if p.is_file()) mapping = out / 'doc/RAW_TO_SHARED.md' if mapping.exists() and mapping.read_bytes() != source_mapping.read_bytes(): raise ValueError('RAW_TO_SHARED.md changed; choose a new release-id') if not mapping.exists(): shutil.copyfile(source_mapping, mapping) torch.set_num_threads(1) models, splits = mano_models(args.mano_dir), load_splits(args.root) with tempfile.TemporaryDirectory(prefix='h2o-assets-') as wd: assets, asset_archive = load_assets(args.root, Path(wd)) def convert_one(archive): return convert_archive(archive, args, out, splits, models, assets, asset_archive) if args.workers == 1: for archive in archives: convert_one(archive) else: with ThreadPoolExecutor(max_workers=args.workers) as pool: for archive, count in zip(archives, pool.map(convert_one, archives), strict=True): print(f'Archive {archive.name}: {count} sequences', flush=True) return 0
if __name__ == '__main__': raise SystemExit(main())
# TODO(v2.0): 以下旧 MANO 网格和渲染分割代码仅保留备查;v1.0 不生成标注。# def load_mano_model(path: Path):# """MPI MANO pkl → numpy 字典。shapedirs 在 pkl 内为 chumpy Select(对 (778,3,20) 基# 底 flat 选取前 10 个 shape 分量;idxs 已核实等价于 base[:,:,:10])。"""# with open(path, "rb") as f:# d = _ManoUnpickler(f, encoding="latin1").load()# sd = d["shapedirs"]# base = np.asarray(sd.a.x, np.float64) # (778, 3, 20)# shapedirs = base.reshape(-1)[np.asarray(sd.idxs)].reshape(base.shape[0], 3, -1)# jreg = d["J_regressor"]# jreg = np.asarray(jreg.todense()) if hasattr(jreg, "todense") else np.asarray(jreg)# return {"v_template": np.asarray(d["v_template"], np.float64),# "shapedirs": shapedirs,# "posedirs": np.asarray(d["posedirs"], np.float64),# "weights": np.asarray(d["weights"], np.float64),# "J_regressor": np.asarray(jreg, np.float64),# "kintree": np.asarray(d["kintree_table"], np.int64),# "faces": np.asarray(d["f"], np.int64)}### def rodrigues(r):# """axis-angle (N,3) → 旋转矩阵 (N,3,3)。公式 I + sinθ·K + (1−cosθ)·K²(已对 scipy 核验)。"""# r = np.asarray(r, np.float64).reshape(-1, 3)# th = np.linalg.norm(r, axis=1)# R = np.zeros((len(r), 3, 3))# nz = th > 1e-12# R[~nz] = np.eye(3)# k = r[nz] / th[nz, None]# K = np.zeros((len(k), 3, 3))# K[:, 0, 1], K[:, 0, 2], K[:, 1, 2] = -k[:, 2], k[:, 1], -k[:, 0]# K[:, 1, 0], K[:, 2, 0], K[:, 2, 1] = k[:, 2], -k[:, 1], k[:, 0]# s, c = np.sin(th[nz])[:, None, None], np.cos(th[nz])[:, None, None]# R[nz] = np.eye(3) + s * K + (1 - c) * (K @ K)# return R### def _mano_chain(model, betas, pose):# """返回 (v_shaped, J, Rs, G):G 为 16 个关节的全��变换(平移列 = 关节位置)。"""# v = model["v_template"] + np.einsum("nkc,c->nk", model["shapedirs"], betas)# J = model["J_regressor"] @ v# Rs = rodrigues(np.asarray(pose, np.float64).reshape(16, 3))# kt = model["kintree"]# G = np.zeros((16, 4, 4))# for j in range(16):# p = kt[0, j] if j else -1# loc = np.eye(4)# loc[:3, :3] = Rs[j]# loc[:3, 3] = J[j] - (J[p] if j else 0.0)# G[j] = loc if not j else G[p] @ loc# return v, J, Rs, G### def mano_forward(model, betas, pose, transl):# """MANO LBS 前向(经典蒙皮 M_j = G_j·G0_j⁻¹;对 hand_pose 21 关节实证 0.0 mm)。# pose: 48 axis-angle([0:3] 全局);返回相机系米顶点 (778,3)。"""# v, J, Rs, G = _mano_chain(model, betas, pose)# lrot = (Rs[1:] - np.eye(3)).ravel()# v_posed = v + np.einsum("nkc,c->nk", model["posedirs"], lrot)# kt = model["kintree"]# G0 = np.zeros((16, 4, 4))# for j in range(16):# p = kt[0, j] if j else -1# loc = np.eye(4)# loc[:3, 3] = J[j] - (J[p] if j else 0.0)# G0[j] = loc if not j else G0[p] @ loc# M = np.einsum("nj,jab->nab", model["weights"], G @ np.linalg.inv(G0))# out = np.einsum("nab,nb->na", M[:, :3, :3], v_posed) + M[:, :3, 3]# return out + np.asarray(transl, np.float64)### def mano_chain_joints(model, betas, pose, transl):# """16 个关节位置(相机系米)= 链平移列;自检用。"""# _, _, _, G = _mano_chain(model, betas, pose)# return G[:, :3, 3] + np.asarray(transl, np.float64)### def rasterize(verts_cam, faces, labels, W, H, fx, fy, cx, cy):# z = verts_cam[:, 2]# P = faces# ok = (z[P] > 0.02).all(1) # 任一顶点在相机后 → 丢弃该三角形# P, labels = P[ok], labels[ok]# if len(P) == 0:# return np.zeros((H, W), np.uint16), np.zeros(0, np.int64)# x = verts_cam[:, 0] / z * fx + cx# y = verts_cam[:, 1] / z * fy + cy# xa = np.maximum(0, np.minimum(np.floor(x[P[:, 0]]), np.minimum(# np.floor(x[P[:, 1]]), np.floor(x[P[:, 2]]))).astype(np.int64))# xb = np.minimum(W - 1, np.maximum(np.ceil(x[P[:, 0]]), np.maximum(# np.ceil(x[P[:, 1]]), np.ceil(x[P[:, 2]]))).astype(np.int64))# ya = np.maximum(0, np.minimum(np.floor(y[P[:, 0]]), np.minimum(# np.floor(y[P[:, 1]]), np.floor(y[P[:, 2]]))).astype(np.int64))# yb = np.minimum(H - 1, np.maximum(np.ceil(y[P[:, 0]]), np.maximum(# np.ceil(y[P[:, 1]]), np.ceil(y[P[:, 2]]))).astype(np.int64))# xa, ya = np.minimum(xa, xb), np.minimum(ya, yb) # 完全出画的三角形 → 空 bbox# wdt, hgt = xb - xa + 1, yb - ya + 1# cnt = wdt * hgt# tot = int(cnt.sum())# tri = np.repeat(np.arange(len(P)), cnt)# k = np.arange(tot) - (np.cumsum(cnt) - cnt)[tri]# px = xa[tri] + k % wdt[tri] + 0.5# py = ya[tri] + k // wdt[tri] + 0.5# ax, ay = x[P[tri, 0]], y[P[tri, 0]]# bx, by = x[P[tri, 1]], y[P[tri, 1]]# cx_, cy_ = x[P[tri, 2]], y[P[tri, 2]]# area = ((x[P[:, 1]] - x[P[:, 0]]) * (y[P[:, 2]] - y[P[:, 0]])# - (y[P[:, 1]] - y[P[:, 0]]) * (x[P[:, 2]] - x[P[:, 0]]))# areat = area[tri]# e0 = (bx - ax) * (py - ay) - (by - ay) * (px - ax)# e1 = (cx_ - bx) * (py - by) - (cy_ - by) * (px - bx)# e2 = (ax - cx_) * (py - cy_) - (ay - cy_) * (px - cx_)# s = np.sign(areat)# inside = (np.abs(areat) > 1e-9) & ((e0 * s >= 0) & (e1 * s >= 0) & (e2 * s >= 0))# px, py, tri = px[inside], py[inside], tri[inside]# at = areat[inside]# w0, w1, w2 = e1[inside] / at, e2[inside] / at, e0[inside] / at# zz = w0 * z[P[tri, 0]] + w1 * z[P[tri, 1]] + w2 * z[P[tri, 2]]# pix = py.astype(np.int64) * W + px.astype(np.int64)# order = np.lexsort((zz, pix)) # 同像素按深度升序 → 首条即最近# pix, tri = pix[order], tri[order]# first = np.unique(pix, return_index=True)[1]# mask = np.zeros(H * W, np.uint16)# win = tri[first]# mask[pix[first]] = labels[win] + 1 # 临时标签 +1(0=背景)# return mask.reshape(H, W), np.bincount(labels[win] + 1)### # ============================================================================# # ffmpeg 写出与核验(与 convert_dexycb.py 同构)# # ============================================================================# verts, faces_all, labels = [], [], []# for ti, (tid, kind) in enumerate(tracks):# if kind == "hand_left" and b["mano"][0] > 0.5:# verts.append(mano_forward(mano_models["left"], b["mano"][52:62],# b["mano"][4:52], b["mano"][1:4]))# faces_all.append(mano_models["left"]["faces"])# elif kind == "hand_right" and b["mano"][62] > 0.5:# verts.append(mano_forward(mano_models["right"], b["mano"][114:124],# b["mano"][66:114], b["mano"][63:66]))# faces_all.append(mano_models["right"]["faces"])# elif isinstance(kind, tuple) and int(b["objp"][0]) == kind[1]:# M = np.asarray(b["objrt"][1:17], np.float64).reshape(4, 4)# V0, F0 = meshes[kind[1]]# verts.append(V0 @ M[:3, :3].T + M[:3, 3])# faces_all.append(F0)# else:# continue# labels.append(np.full(len(faces_all[-1]), ti))# if verts:# V = np.concatenate(verts)# offs = np.cumsum([0] + [len(v) for v in verts[:-1]])# F = np.concatenate([fa + o for fa, o in zip(faces_all, offs)])# mask, counts = rasterize(V, F, np.concatenate(labels),# IMG_W, IMG_H, fx, fy, cx, cy)# else:# mask, counts = np.zeros((IMG_H, IMG_W), np.uint16), np.zeros(0, np.int64)# lut = np.zeros(n_tracks + 1, np.uint16)# for ti in range(n_tracks):# present = ti + 1 < len(counts) and counts[ti + 1] > 0# if present:# presence[tracks[ti][0]][f] = True# if active_id[ti] is None:# pid = next(i for i in range(1, 65535) if i not in used)# used.add(pid)# active_id[ti], seg_start[ti] = pid, f# frame_maps[ti].append({"id": pid})# lut[ti + 1] = active_id[ti]# elif active_id[ti] is not None:# frame_maps[ti][-1]["frames"] = [seg_start[ti], f - 1]# segments[ti].append([seg_start[ti], f - 1])# used.discard(active_id[ti])# active_id[ti] = None# mw.write(lut[mask])
# TODO(v2.0): 旧物体尺寸派生代码;v1.0 仅保留源物体关键点。# pts = np.asarray(b["objp"][1:64], np.float64).reshape(21, 3)# half = np.abs((pts[1:9] - pts[0]) @ M[:3, :3]).max(0)# obj_recs.append({# "track_id": f"o{classes.index(c)}", "frame": f,# "mesh_ref": f"h2o/{OBJ_CLASSES[c]}.obj",# "pose": {"quat": rotmat_to_quat_wxyz(M[:3, :3])[0].tolist(),# "trans": M[:3, 3].tolist()},# "bbox_center3d": pts[0].tolist(),# "bbox_size": (2 * half).tolist()})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595#!/usr/bin/env python3"""HOI4D native observations and annotations → CONTRACT.md v1.0."""from collections import Counterfrom concurrent.futures import ThreadPoolExecutorfrom contextlib import ExitStackfrom functools import lru_cacheimport gzipimport ioimport jsonimport osfrom pathlib import Pathimport pickleimport reimport shutilimport shleximport posixpathimport subprocessimport tempfileimport tarfileimport threadingimport zipfile
# Each worker owns one Python thread; prevent native libraries spawning CPU pools.for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS'): os.environ[key] = '1'
import numpy as npfrom PIL import Imagefrom scipy.spatial.transform import Rotation
import torch
from warehouse_v1_0 import (View, build_record, check_mesh, decode_args, find_file, json_write, locator, mano_models, model_profile, parser, probe, release, run, safe_member, sequence_dir)
CATEGORIES = { 1: dict(cad="rigid/ToyCar", groups=[("main", [1], "Toy Car", 1)], hands={2: "right"}, objmap={"Toycar": "main"}), 2: dict(cad="rigid/Mug", groups=[("a", [1], "Mug", 2), ("b", [3], "Mug", 2)], hands={2: "right"}, objmap={"Watercup": "a"}), 3: dict(cad="articulated/Laptop", groups=[("main", [1, 3], "Laptop", 3)], hands={2: "right"}, objmap={"Laptopdisplay": "main", "Laptopkeyboard": "main"}), 4: dict(cad="articulated/StorageFurniture", groups=[("main", [1, 3, 4], "Storage Furniture", 4), ("bottle", [5], "Bottle", 5)], hands={2: "right"}, objmap={"Lockerbody": "main", "Lockersldingdoor": "main", "Lockerdrawer": "main", "Safebox": "main"}), 5: dict(cad="rigid/Bottle", groups=[("main", [1], "Bottle", 5), ("mug", [3], "Mug", 2)], hands={2: "right"}, objmap={"bottleddrinks": "main"}), 6: dict(cad="articulated/Safe", groups=[("main", [1, 3], "Safe", 6), ("bottle", [4], "Bottle", 5)], hands={2: "right"}, objmap={"Safebox": "main", "Safedoor": "main"}), 7: dict(cad="rigid/Bowl", groups=[("main", [1], "Bowl", 7), ("ball", [3], "Ball", None)], hands={2: "right"}, objmap={"bowl": "main"}), 8: dict(cad="articulated/Bucket", groups=[("a", [1, 3], "Bucket", 8), ("b", [4, 5], "Bucket", 8)], hands={2: "right", 6: "left"}, objmap={"bucket": "a", "Buckethandle": "a"}), 9: dict(cad="articulated/Scissors", groups=[("main", [1, 3], "Scissors", 9)], hands={2: "right"}, objmap={"scissors": "main", "scissors2": None}), # scissors2:场景道具,无掩码 11: dict(cad="articulated/Pliers", groups=[("main", [1, 3], "Pliers", 11)], hands={2: "right"}, objmap={"Pliersleft": "main", "Pliersright": "main"}), 12: dict(cad="rigid/Kettle", groups=[("main", [1], "Kettle", 12), ("mug", [3], "Mug", 2)], hands={2: "right"}, objmap={"kettle": "main"}), 13: dict(cad="rigid/Knife", groups=[("main", [1], "Knife", 13), ("apple", [3], "Apple", None)], hands={2: "right"}, objmap={"knife": "main"}), 14: dict(cad="articulated/TrashCan", groups=[("main", [1, 3], "Trash Can", 14), ("bottle", [4], "Bottle", 5)], hands={2: "right"}, objmap={"Dustbinbase": "main", "Dustbincover": "main"}), 17: dict(cad="articulated/Lamp", groups=[("main", [1, 3, 4, 5], "Lamp", 17)], hands={2: "right", 6: "left"}, objmap={"Lampbase": "main", "Tablelampfirstjoint": "main", "Tablelampsecondjoint": "main", "Thirdjointoftablelamp": "main"}), 18: dict(cad="articulated/Stapler", groups=[("main", [1, 3, 4], "Stapler", 18), ("paper", [5], "Paper", None)], hands={2: "right", 6: "left"}, # 6=左手:官方 label.csv 缺列,实测修正 objmap={"Staplerbase": "main", "Staplercover": "main"}), 20: dict(cad="rigid/Chair", groups=[("main", [1], "Chair", 20)], hands={2: "right", 3: "left"}, objmap={"chair": "main"}),}
# Official HOI4D definitions/motion segmentation/label.csv; no spatial side inference.REGION_NAMES = {1: {1: 'Toy Car', 2: 'Right Hand'}, 2: {1: 'Mug', 2: 'Right Hand', 3: 'Mug'}, 3: {1: 'Screen', 2: 'Right Hand', 3: 'Keyboard'}, 4: {1: 'Door', 2: 'Right Hand', 3: 'Body of the Cabinet', 4: 'Drawer', 5: 'Bottle'}, 5: {1: 'Bottle', 2: 'Right Hand', 3: 'Mug'}, 6: {1: 'Body of the Safe', 2: 'Right Hand', 3: 'Door', 4: 'Bottle'}, 7: {1: 'Bowl', 2: 'Right Hand', 3: 'Ball'}, 8: {1: 'Body of the Bucket', 2: 'Right Hand', 3: 'Handle', 4: 'Body of the Bucket', 5: 'Handle', 6: 'Left Hand'}, 9: {1: 'Left Part of the Scissors', 2: 'Right Hand', 3: 'Right Part of the Scissors'}, 11: {1: 'Left Part of the Pliers', 2: 'Right Hand', 3: 'Right Part of the Pliers'}, 12: {1: 'Kettle', 2: 'Right Hand', 3: 'Mug'}, 13: {1: 'Knife', 2: 'Right Hand', 3: 'Apple'}, 14: {1: 'Body of the Trash Can', 2: 'Right Hand', 3: 'Lid', 4: 'Bottle'}, 17: {1: 'Base', 2: 'Right Hand', 3: 'Tube', 4: 'Top Link', 5: 'Bottom Link', 6: 'Left Hand'}, 18: {1: 'Base', 2: 'Right Hand', 3: 'Slot', 4: 'Lid', 5: 'Paper'}, 20: {1: 'Chair', 2: 'Right Hand', 3: 'Left Hand'}}
class SplitFiles(io.RawIOBase): """Read concatenated source gzip parts without concatenating 119 GB on disk.""" def __init__(self, paths): self.paths = iter(paths) self.current = None
def readable(self): return True
def readinto(self, buffer): while True: if self.current is None: path = next(self.paths, None) if path is None: return 0 self.current = path.open('rb') n = self.current.readinto(buffer) if n: return n self.current.close() self.current = None
def close(self): if self.current is not None: self.current.close() super().close()
def extract_depths(root, sequences, work): directory = find_file(root, 'DEPTH') if directory is None: return {}, [] parts = sorted(directory.glob('HOI4D_depth_video.tar.gz*'), key=lambda p: int(p.name.split('.gz')[1] or 0)) if not parts: return {}, [] wanted = {f'HOI4D_depth_video/{seq}/align_depth/depth_video.avi': seq for seq in sequences} found = {} with SplitFiles(parts) as joined, io.BufferedReader(joined) as inp, gzip.GzipFile(fileobj=inp) as gz: with tarfile.open(fileobj=gz, mode='r|') as tf: for member in tf: if member.isfile() and member.name in wanted: seq = wanted[member.name] dest = work / (seq.replace('/', '_') + '.avi') with tf.extractfile(member) as src, dest.open('wb') as dst: shutil.copyfileobj(src, dst) found[seq] = (dest, {'files': [str(p.resolve()) for p in parts], 'member': member.name}) if len(found) == len(wanted): break return found, parts
def palette_mask(data): with Image.open(io.BytesIO(data)) as im: arr = np.asarray(im) if arr.ndim == 2: return arr.astype(np.uint16) if arr.shape[-1] != 3: raise ValueError('unsupported HOI4D mask representation') # VOC's 256-color palette interleaves eight label bits into the high RGB bits. # Invert it directly instead of sorting every pixel with np.unique. if np.any(arr & np.array([31, 31, 63], dtype=np.uint8)): raise ValueError('source mask has colors outside official VOC palette') mask = np.zeros(arr.shape[:2], dtype=np.uint16) for bit in range(8): mask |= ((arr[..., bit % 3] >> (7 - bit // 3)) & 1).astype(np.uint16) << bit return mask
# Four workers each reuse annotation and hand indices instead of rebuilding the ZIP directory.@lru_cache(maxsize=8)def index_frames(z): index = {} for name in z.namelist(): parent, _, filename = name.rpartition('/') stem, dot, suffix = filename.rpartition('.') if not dot or not stem.isdigit() or suffix not in ('png', 'json', 'pickle'): continue entries = index.setdefault((parent + '/', '.' + suffix), {}) f = int(stem) if f in entries: raise ValueError(f'duplicate frame number under {parent}') entries[f] = name return index
def frame_members(z, prefix, suffix): return index_frames(z).get((prefix, suffix), {})
def convert_sequence(seq, args, target, rgbz, annz, hpz, calz, cadz, paths, models, depth): # ponytail: cache only one sequence's encoded annotation bytes; no decoded masks or CAD cache. @lru_cache(maxsize=None) def read_annotation(archive, name): return archive.read(name)
category = int(re.search(r'/C(\d+)/', seq)[1]) definition = CATEGORIES.get(category) if definition is None: raise ValueError(f'category mapping unavailable: {category}') prefix = f'HOI4D_annotations/{seq}' mask_members = frame_members(annz, prefix + '/2Dseg/mask/', '.png') shifted = frame_members(annz, prefix + '/2Dseg/shift_mask/', '.png') if not mask_members: mask_members = shifted pose_members = frame_members(annz, prefix + '/objpose/', '.json') hand_members = {side: frame_members(hpz, f'Hand_pose/handpose_{side}_hand/{seq}/', '.pickle') for side in ('left', 'right')} if hpz else {'left': {}, 'right': {}} with tempfile.TemporaryDirectory(prefix='hoi4d-source-') as wd: work = Path(wd) member = f'HOI4D_release/{seq}/align_rgb/image.mp4' video = work / 'rgb.mp4' with rgbz.open(member) as src, video.open('wb') as dst: shutil.copyfileobj(src, dst) info = probe(video) if 'nb_frames' not in info: info['nb_frames'] = json.loads(run(['ffprobe', '-v', 'error', '-count_frames', '-select_streams', 'v:0', '-show_entries', 'stream=nb_read_frames', '-of', 'json', str(video)], stdout=subprocess.PIPE).stdout)['streams'][0]['nb_read_frames'] n = int(info['nb_frames']) if args.max_frames: n = min(n, args.max_frames) if shifted and mask_members != shifted and any(f not in mask_members and f in shifted for f in range(n)): raise ValueError('shift_mask has frames absent from mask; correspondence unverified') frames = [] for f in range(n): sources = {} if f in mask_members: sources['segment'] = locator(paths['annotations'], mask_members[f], read_annotation(annz, mask_members[f])) if f in pose_members: sources['object'] = locator(paths['annotations'], pose_members[f], read_annotation(annz, pose_members[f])) for side in ('left', 'right'): if f in hand_members[side]: sources['hand_' + side] = locator(paths['hand'], hand_members[side][f], read_annotation(hpz, hand_members[side][f])) frames.append(dict(source_frame_id=f, source_locator=locator(paths['release'], member, frame=f), component_sources=sources, annotation_matches={k: dict(source_frame_id=f, source_timestamp_ns=None, clock_domain=None, match_method='index_map', delta_ns=None) for k in sources})) view = View(target, 'HOI4D', args.release_id, seq.replace('/', '_'), 'ego', frames) view.valid_rules = { 'mano': 'Matched side pickle contains poseCoeff, beta, trans and corresponding model available; zero angles are not missing', 'keypoints': 'Matched side pickle contains kps2D; independently provided source points, no visibility gate', 'pose': 'Matched source object record contains rotation and center; record identity retained', 'dimensions': 'Matched source object record contains dimensions; size/mesh relation remains source_unspecified', 'segment': 'Source mask or shift_mask present with verified palette codes and entity/part mapping', } view.full_jpeg = getattr(args, 'jpeg_full_check', False) view.meta['view_type'] = 'ego' view.meta['sampling']['selection'] = {'max_frames': args.max_frames, 'source_sequence': seq} view.rgb([], locator(paths['release'], member), video=video, count=n) intr_name = f'camera_params/{seq.split("/")[0]}/intrin.npy' if calz and intr_name in calz.namelist(): view.camera(np.load(io.BytesIO(calz.read(intr_name))), locator(paths['camera'], intr_name)) extr_name = prefix + '/3Dseg/output.log' if extr_name in annz.NameToInfo: lines = [line for line in annz.read(extr_name).decode().splitlines() if line.strip()] if len(lines) % 5: raise ValueError('invalid Open3D camera trajectory') extr, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) for i in range(0, len(lines), 5): idx = int(lines[i].split()[0]) if idx < n: if valid[idx]: raise ValueError('duplicate trajectory index') extr[idx] = np.linalg.inv(np.loadtxt(io.StringIO('\n'.join(lines[i + 1:i + 5])))) valid[idx] = True view.tensor('extrinsic', 'transform/se3/v1', 'camera/extrinsic.pt', extr, valid, ['T', 'row', 'column'], locator(paths['annotations'], extr_name), convention='T_camera_from_world', source_convention='Open3D LOG camera-to-world; inverted') loc = {'frames_ref': 'camera/frames.jsonl', 'source_field': 'component_sources'} motion, mv = np.full((n, 2, 61), np.nan, np.float32), np.zeros((n, 2), bool) points, pv = np.full((n, 2, 21, 2), np.nan, np.float32), np.zeros((n, 2, 21), bool) for slot, side in enumerate(('left', 'right')): for f, name in hand_members[side].items(): if f >= n: continue data = pickle.loads(read_annotation(hpz, name), encoding='latin1') if all(k in data for k in ('poseCoeff', 'beta', 'trans')): motion[f, slot] = np.r_[np.asarray(data['poseCoeff']).reshape(48), np.asarray(data['beta']).reshape(10), np.asarray(data['trans']).reshape(3)] mv[f, slot] = True # Zero angles are a valid pose, not a missing sentinel. if 'kps2D' in data: points[f, slot] = np.asarray(data['kps2D']).reshape(21, 2) pv[f, slot] = True if mv.any(): if all(side in models for slot, side in enumerate(('left', 'right')) if mv[:, slot].any()): view.tensor('mano', 'mano/axis_angle61/v1', 'annotation/mano/motion.pt', motion, mv, ['T', 'hand', 'parameter'], loc, model_profile=model_profile(models)) else: view.absent('mano', 'Source MANO exists; provide --mano-dir to fix model identity', 'dependency_missing') if pv.any(): view.tensor('keypoints_uv', 'keypoints/uv/v1', 'annotation/keypoints/uv.pt', points, pv, ['T', 'hand', 'keypoint', 'coordinate'], loc, keypoint_schema='mano21/v1', unit='pixel', source_method='Upstream fitted MANO projection already present in kps2D') objects = {} groups = {key: (vals, name, cls) for key, vals, name, cls in definition['groups']} def ensure_object(key, source_loc, category_id=None, frame=None, source_id=None): if key not in objects: view.object(key, source_loc, scope='frame' if frame is not None else 'sequence', scope_id=f'{seq}:{frame}' if frame is not None else None, category_id=category_id, source_object_id=source_id) objects[key] = {} mappings = [] mask_valid = [f in mask_members for f in range(n)] if any(mask_valid): width, height = view.meta['camera']['image_size'] def masks(): for f in range(n): labels = [] if f in mask_members: mask = palette_mask(read_annotation(annz, mask_members[f])) for value in np.unique(mask): value = int(value) if value in (0, 255): if value == 255: raise ValueError('HOI4D 255 region semantics unverified') continue if REGION_NAMES[category].get(value) in ('Left Hand', 'Right Hand'): entity, part, cls = 'hand_' + REGION_NAMES[category][value].split()[0].lower(), None, 'hand' else: group = next((k for k, (vals, _, _) in groups.items() if value in vals), None) entity = group or f'unknown_region_{value}' cls = groups[group][2] if group else None part = f'region_{value}' if group and len(groups[group][0]) > 1 else None ensure_object(entity, frames[f]['component_sources']['segment'], cls) if part: objects[entity].setdefault('parts', {})[part] = {'part_id': part, 'parent_id': None, 'has_model': False, 'mesh_ref': None, 'source_region_code': value, 'name': REGION_NAMES[category].get(value)} labels.append(dict(mask_value=value, category_id=cls, entity_id=entity, part_id=part, source_instance_id=value, source_attributes={'region_name': REGION_NAMES[category].get(value)})) else: mask = np.zeros((height, width), np.uint16) mappings.append(dict(frame_index=f, labels=labels)) yield mask view.raster('segment', masks(), mask_valid, loc, mappings) view.meta['components']['segment']['coverage'] = {'kind': 'unknown'} if any(label['part_id'] for row in mappings for label in row['labels']): view.meta['components']['segment']['segmentation_type'] = 'part' else: view.absent('segment', 'No native segmentation for this source sequence') records = {} for f, name in pose_members.items(): if f >= n: continue data = json.loads(read_annotation(annz, name)) # isEffective is not used to erase existing numerical annotations. source_records = data.get('dataList', data.get('objects')) if source_records is None: raise ValueError('unrecognized source object annotation structure') if category == 2 and source_records and (len(source_records) != 1 or source_records[0].get('id') != 1 or source_records[0].get('label') != 'Watercup'): raise ValueError('C2 native pose differs from the verified one-object target; cannot map to mask region 1') label_counts = Counter(record['label'] for record in source_records) per_frame = set() for record_index, record in enumerate(source_records): label = record['label'] group = definition['objmap'].get(label) # Pinned official ObjTracking reads dataList[0] with segmentation label 1. source_primary = category == 2 and record_index == 0 and record.get('id') == 1 and group == 'a' ambiguous = group is not None and sum(g[2] == groups[group][2] for g in groups.values()) > 1 and not source_primary ambiguous = ambiguous or (label_counts[label] > 1 and not source_primary) or group is None entity = f'pose_frame_{f}_{record_index}' if ambiguous else group ensure_object(entity, locator(paths['annotations'], name, record=record_index), groups[group][2] if group else None, frame=f if ambiguous else None, source_id=record.get('id')) if ambiguous: view.build['unresolved'].append({'component': entity, 'status': 'source_semantics_unverified', 'reason': 'Source pose retained with frame identity; no guessed association to same-class mask instances'}) label_key = (entity, label) if label_key in per_frame: raise ValueError(f'ambiguous repeated object label {label}; source identity must be resolved') per_frame.add(label_key) records.setdefault(label_key, {})[f] = (record, locator(paths['annotations'], name, record=record.get('id'))) if category == 2 and any(entity == 'a' for entity, _ in records): view.build['validation'].append({'component': 'C2_source_pose_mask_identity', 'rule': 'Official ObjTracking process_data.py reads dataList[0] with semantic mask label 1', 'source_revision': 'afa7bf37b02b7e33cf245acd08b98c207ccc175c', 'source_pose_id': 1, 'mask_value': 1, 'matched_frames': sum(len(by_frame) for (entity, _), by_frame in records.items() if entity == 'a')}) for (entity, label), by_frame in records.items(): part_labels = [k[1] for k in records if k[0] == entity] articulated = definition['cad'].startswith('articulated/') and entity == definition['groups'][0][0] part = 'pose_' + re.sub(r'[^a-zA-Z0-9_]', '_', label) if articulated or len(part_labels) > 1 else None base = f'annotation/object/{entity}' if part: base += '/parts/' + part objects[entity].setdefault('parts', {})[part] = dict(part_id=part, parent_id=None, has_model=False, mesh_ref=None, source_label=label) poses, valid = np.full((n, 4, 4), np.nan, np.float32), np.zeros(n, bool) dimensions = np.full((n, 3), np.nan, np.float32) dv = np.zeros(n, bool) for f, (record, _) in by_frame.items(): if all(k in record for k in ('rotation', 'center')): poses[f] = np.eye(4) poses[f, :3, :3] = Rotation.from_euler('XYZ', [record['rotation'][k] for k in ('x', 'y', 'z')]).as_matrix() poses[f, :3, 3] = [record['center'][k] for k in ('x', 'y', 'z')] valid[f] = True if 'dimensions' in record: dimensions[f] = [record['dimensions'][k] for k in ('length', 'width', 'height')] dv[f] = True key = entity + ('_' + part if part else '') view.tensor('pose_' + key, 'transform/se3/v1' if part else 'object/rigid/v1', base + '/pose.pt', poses, valid, ['T', 'row', 'column'], loc, convention='T_camera_from_part' if part else 'T_camera_from_object', unit='m', source_label=label, source_euler_order='XYZ', definition='https://github.com/hoi4d/ObjTracking/blob/main/process_data.py') if dv.any(): view.tensor('dimensions_' + key, 'object/dimensions/v1', base + '/dimensions.pt', dimensions, dv, ['T', 'dimension'], loc, dimensions_semantics='source_unspecified', unit='m', scale_applied_to_mesh=False) if cadz: primary = definition['groups'][0][0] if category != 2 and sum(g[2] == category for g in groups.values()) > 1: primary = 'source_cad_instance' instance = int(re.search(r'/N(\d+)/', seq)[1]) mesh_prefix = f'HOI4D_CAD_Model_for_release/{definition["cad"]}/{instance:03d}' candidates = [name for name in cadz.namelist() if not name.endswith('/') and (name == mesh_prefix + '.obj' or name.startswith(mesh_prefix + '/'))] if candidates: # Retain OBJ material/texture dependencies beside their original names. queue = list(candidates) for name in queue: if Path(name).suffix.lower() not in ('.obj', '.mtl'): continue for line in cadz.read(name).decode().splitlines(): fields = shlex.split(line, comments=True) if not fields: continue refs = fields[1:] if fields[0] == 'mtllib' else ([fields[-1]] if fields[0].startswith('map_') or fields[0] in ('bump', 'norm', 'disp', 'decal') else []) for ref in refs: dependency = posixpath.normpath(posixpath.join(posixpath.dirname(name), ref)) if dependency not in cadz.NameToInfo: raise ValueError(f'missing CAD dependency: {dependency}') if dependency not in candidates: candidates.append(dependency) queue.append(dependency) ensure_object(primary, locator(paths['cad'], mesh_prefix), category) asset_dir = view.path / f'annotation/object/{primary}/assets' asset_refs = [] for name in candidates: relative = posixpath.relpath(name, mesh_prefix if definition['cad'].startswith('articulated/') else posixpath.dirname(mesh_prefix)) dest = safe_member(asset_dir, relative) dest.parent.mkdir(parents=True, exist_ok=True) dest.write_bytes(cadz.read(name)) ref = dest.relative_to(view.path).as_posix() if dest.suffix.lower() == '.obj': asset_key = re.sub(r'[^a-zA-Z0-9_]', '_', relative) view.component('mesh_' + primary + '_' + asset_key, 'mesh/obj/v1', ref, ['vertex'], locator(paths['cad'], name), unit='m', valid=True, scale_applied_to_mesh=False, dimensions_semantics='source_unspecified') asset_refs.append(ref) if definition['cad'].startswith('articulated/'): part_id = 'asset_' + asset_key objects[primary].setdefault('parts', {})[part_id] = dict(part_id=part_id, parent_id=None, has_model=True, mesh_ref=ref, source_asset=relative, note='Source asset; correspondence to motion part labels remains unverified') for asset_ref in asset_refs: mesh_check = check_mesh(view.path / asset_ref, asset_dir) view.build['validation'].append({'component': asset_ref, **mesh_check, 'unit_basis': 'official ObjTracking loads source canonical CAD without scaling in metre camera coordinates', 'geometric_acceptance': 'physical dimensions-to-mesh relation remains source_unspecified'}) metadata_path = view.path / f'annotation/object/{primary}/metainfo.json' metadata = json.loads(metadata_path.read_text()) metadata.update(has_model=bool(asset_refs), asset_refs=asset_refs) if definition['cad'].startswith('rigid/') and len(asset_refs) == 1: metadata['mesh_ref'] = asset_refs[0] json_write(metadata_path, metadata) if definition['cad'].startswith('articulated/'): view.build['unresolved'].append({'component': 'object_part_asset_association', 'status': 'source_semantics_unverified', 'reason': 'All source assets and motion labels retained, but no guessed correspondence or joint_state'}) for entity, info in objects.items(): if 'parts' in info: ref = f'annotation/object/{entity}/articulation.json' json_write(view.path / ref, {'parts': list(info['parts'].values()), 'joints': [], 'hierarchy_semantics': 'semantic_containment', 'note': 'Unassociated source region, motion and asset nodes; original CAD trees retained in assets'}) view.component('articulation_' + entity, 'object/articulated/v1', ref, [], loc) meta_path = view.path / f'annotation/object/{entity}/metainfo.json' metadata = json.loads(meta_path.read_text()) metadata['articulation_ref'] = ref json_write(meta_path, metadata) if depth is not None: dpath, dloc = depth dmeta = probe(dpath) if [dmeta['width'], dmeta['height']] != view.meta['camera']['image_size']: raise ValueError('HOI4D depth grid differs from RGB') if dmeta['pix_fmt'] != 'gray16le': raise ValueError('unexpected HOI4D depth pixel format') width, height = view.meta['camera']['image_size'] raw = work / 'depth.raw' limits = ['-frames:v', str(n)] if args.max_frames else [] run(decode_args(dpath, 'gray16le') + limits + ['-y', str(raw)]) if raw.stat().st_size != n * width * height * 2: raise ValueError('depth/RGB frame count or grid mismatch') def depths(): with raw.open('rb') as inp: for _ in range(n): yield np.frombuffer(inp.read(width * height * 2), '<u2').reshape(height, width).astype(np.float32) / 1000 view.raster('depth', depths(), None, dloc | {'conversion': 'registered millimetre camera-Z to metres'}) else: if find_file(args.root, 'DEPTH'): raise ValueError('DEPTH source exists, but no matching depth video was found') view.absent('depth', 'Depth source not downloaded', 'not_downloaded') return view.finish()
def main(argv=None): p = parser('HOI4D', __doc__) p.set_defaults(release_id='shared-v1.0') # Four workers reached 21 observed OS threads including timing; stay below the 24-thread budget. p.add_argument('--workers', type=int, choices=range(1, 5), default=1, help='Independent views in parallel, 1..4; codec/BLAS threads fixed at 1') p.add_argument('--tasks', help='Comma-separated substrings of source sequence paths') p.add_argument('--sessions', help='Comma-separated sessions') p.add_argument('--categories', help='Comma-separated category numbers') args = p.parse_args(argv) if args.views and args.views != 'ego': p.error('HOI4D source camera ID is ego') paths = {key: find_file(args.root, name) for key, name in { 'release': 'HOI4D_release.zip', 'annotations': 'HOI4D_annotations.zip', 'hand': 'HOI4D_Hand_pose.zip', 'camera': 'camera_params.zip', 'cad': 'HOI4D_CAD_Model_for_release.zip'}.items()} if not paths['release'] or not paths['annotations']: p.error('HOI4D release and annotation ZIPs are required') out = release(args, 'HOI4D') mapping = Path(__file__).resolve().parent.parent / 'docs/hoi4d-RAW_TO_SHARED.md' published_mapping = out / 'doc/RAW_TO_SHARED.md' if published_mapping.exists() and published_mapping.read_bytes() != mapping.read_bytes(): raise ValueError('RAW_TO_SHARED.md changed; choose a new release-id') if not published_mapping.exists(): shutil.copyfile(mapping, published_mapping) torch.set_num_threads(1) models = mano_models(args.mano_dir) with ExitStack() as stack, tempfile.TemporaryDirectory(prefix='hoi4d-depth-') as wd: archives = {key: stack.enter_context(zipfile.ZipFile(path)) if path else None for key, path in paths.items()} sequences = sorted(name.removeprefix('HOI4D_release/').removesuffix('/align_rgb/image.mp4') for name in archives['release'].namelist() if name.endswith('/align_rgb/image.mp4')) if args.tasks: sequences = [s for s in sequences if any(token in s for token in args.tasks.split(','))] if args.sessions: sequences = [s for s in sequences if s.split('/')[0] in args.sessions.split(',')] if args.categories: sequences = [s for s in sequences if re.search(r'/C(\d+)/', s)[1] in args.categories.split(',')] if args.limit: sequences = sequences[:args.limit] if not sequences: p.error('no matching source sequences') depths, _ = extract_depths(args.root, sequences, Path(wd)) worker = threading.local() worker_stacks = [] def init_worker(): owned = ExitStack() try: # ZipFile.read mutates a shared seek position: never share a handle across workers. worker.archives = {key: owned.enter_context(zipfile.ZipFile(path)) if path else None for key, path in paths.items()} index_frames(worker.archives['annotations']) if worker.archives['hand']: index_frames(worker.archives['hand']) except BaseException: owned.close() raise worker_stacks.append(owned) def convert_one(seq): source = archives if args.workers == 1 else worker.archives name = seq.replace('/', '_') with sequence_dir(out, name) as target: report = convert_sequence(seq, args, target / 'ego', source['release'], source['annotations'], source['hand'], source['camera'], source['cad'], paths, models, depths.get(seq)) build_record(out, name, {'ego': report}) return seq if args.workers == 1: for seq in map(convert_one, sequences): print(f'Converted {seq}', flush=True) else: try: with ThreadPoolExecutor(max_workers=args.workers, initializer=init_worker) as pool: for seq in pool.map(convert_one, sequences): print(f'Converted {seq}', flush=True) finally: for owned in worker_stacks: owned.close() return 0
if __name__ == '__main__': raise SystemExit(main())
# TODO(v2.0): 旧 bbox IoU 实例重分配属于推断,注释保留,不在 v1.0 执行。# # 同类多实例(C8 双桶 / C2 双杯):2dBox 可用时按 IoU 复核归属# cls = next(x[3] for x in cat["groups"] if x[0] == gk)# sibs = [g for g in cat["groups"]# if g[0] != gk and cls is not None and g[3] == cls]# box = (d.get("2dBox") or {}).get("camera1")# box = (box[0][0], box[0][1], box[1][0], box[1][1]) \# if box and len(box) == 2 else None# if box is not None and sibs:# gvals = next(x[1] for x in cat["groups"] if x[0] == gk)# best, best_iou = gk, box_iou(box, bbox_of(mask, gvals))# for s in sibs:# if ("obj", s[0]) not in tid_of_group:# continue# i = box_iou(box, bbox_of(mask, s[1]))# if i > best_iou + 0.1 and i > 0.15:# best, best_iou = s[0], i# if best != gk:# gk, iou_fixups = best, iou_fixups + 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271#!/usr/bin/env python3"""VISOR source polygons and contact → CONTRACT.md v1.0, without rasterization or side inference."""from collections import Counterimport hashlibimport jsonimport reimport shutilimport tempfilefrom pathlib import Pathimport zipfile
import numpy as npimport torch
from warehouse_v1_0 import (View, build_record, find_file, jsonl_write, locator, parser, release, roots, sequence_dir, source)
FRAME = re.compile(r'frame_(\d+)')HAND = {300: 'left', 301: 'right'}GLOVE = {303: 'left', 304: 'right'}STATES = {'hand-not-in-contact': 'negative', 'glove-not-in-contact': 'negative', 'none-of-the-above': 'target_unannotated', 'inconclusive': 'unknown'}
def hand_side(ann): if ann['class_id'] in HAND: return HAND[ann['class_id']] if ann['class_id'] not in (60, 303, 304): return None raw = ann.get('on_which_hand') raw = raw if isinstance(raw, list) else [raw] sides = set() for item in raw: if item == 'left hand': sides.add('left') if item in ('right hand', 'rigth hand'): sides.add('right') if len(sides) == 1: return next(iter(sides)) if not sides and ann['class_id'] in GLOVE: return GLOVE[ann['class_id']] return None
def convert_video(video, split, annotation, ann_loc, rgb_zip, rgb_loc, mapping, args, target): indexed = sorted(enumerate(annotation['video_annotations']), key=lambda row: int(FRAME.search(row[1]['image']['name'])[1])) if args.max_frames: indexed = indexed[:args.max_frames] if len({row['image']['name'] for _, row in indexed}) != len(indexed): raise ValueError('duplicate VISOR frame') keys = lambda row, ann: (row['image']['subsequence'], ann['class_id'], ann['name']) collisions = set() for _, row in indexed: collisions.update(key for key, number in Counter(keys(row, a) for a in row['annotations']).items() if number > 1) frames, paths = [], [] with tempfile.TemporaryDirectory(prefix='visor-rgb-') as wd, zipfile.ZipFile(rgb_zip) as z: work = Path(wd) for original_index, row in indexed: name = row['image']['name'] data = z.read(name) path = work / Path(name).name path.write_bytes(data) paths.append(path) loc = rgb_loc | {'nested_member': name, 'sha256': hashlib.sha256(data).hexdigest()} frames.append(dict(source_frame_id=int(FRAME.search(name)[1]), source_locator=loc, source_image=row['image'], original_frame_name=mapping.get(name), annotation_matches={'segment': dict(source_frame_id=name, source_timestamp_ns=None, clock_domain=None, match_method='index_map', delta_ns=None, source_locator=ann_loc | {'record': f'video_annotations[{original_index}]'})})) view = View(target, 'EPIC-KITCHENS-VISOR', args.release_id, video, 'ego', frames, sampling='sparse', split=split) view.valid_rules = { 'segment': 'Selected sparse annotation frame present; all source polygons finite with at least three vertices and entity mapping valid', 'relations': 'At least one source in_contact_object value present; positive targets resolve in the same frame; unknown is an explicit usable status', } view.full_jpeg = getattr(args, 'jpeg_full_check', False) view.meta.update(view_type='ego', split_scheme='VISOR_GroundTruth_SparseAnnotations', split_source_locator=ann_loc) view.meta['sampling']['selection'] = {'representation': 'official sparse annotations', 'max_frames': args.max_frames} view.rgb(paths, rgb_loc) entities = {} polygons, mappings, relations, relation_valid = [], [], [], [] for f, (original_index, row) in enumerate(indexed): frame_loc = ann_loc | {'record': f'video_annotations[{original_index}]'} id_map, labels, polys = {}, [], [] for code, ann in enumerate(row['annotations'], 1): if code >= 65535: raise ValueError('too many source instances') sid = ann['id'] if sid in id_map: raise ValueError('duplicate source instance ID within a frame') side = hand_side(ann) if side is not None: entity = 'hand_' + side else: key = keys(row, ann) identity = key + (sid, row['image']['name']) if key in collisions else key entity = 'object_' + hashlib.sha256(json.dumps(identity).encode()).hexdigest()[:20] if entity not in entities: scope = 'frame' if key in collisions else 'subsequence' scope_id = f'{video}:{row["image"]["name"]}' if scope == 'frame' else f'{video}:{key[0]}' view.object(entity, frame_loc | {'source_instance_id': sid}, scope, scope_id, category_id=ann['class_id'], name=ann['name'], association_basis='source_frame_instance' if scope == 'frame' else 'official_subsequence_entity_name') entities[entity] = True id_map[sid] = entity for polygon in ann.get('segments', []): p = np.asarray(polygon) if p.ndim != 2 or p.shape[1] != 2 or len(p) < 3 or not np.isfinite(p).all(): raise ValueError(f'invalid source polygon {sid}') polys.append(dict(mask_value=code, polygons=ann.get('segments', []))) labels.append(dict(mask_value=code, category_id=ann['class_id'], entity_id=entity, part_id=None, source_instance_id=sid, source_attributes={k: v for k, v in ann.items() if k != 'segments'})) rr = [] provided = False for ann in row['annotations']: raw = ann.get('in_contact_object') values = raw if isinstance(raw, list) else [raw] for value in values: if value is None: continue provided = True status = STATES.get(value) obj = None if status is None: if value not in id_map: raise ValueError(f'unresolved source contact target {value} in {video} frame {f}') status, obj = 'positive', id_map[value] rr.append(dict(relation_type='contact', subject_id=id_map[ann['id']], object_id=obj, status=status, source_value=value, source_locator=frame_loc | {'source_instance_id': ann['id']}, provenance=source('Resolve source contact ID against instances in this frame'))) polygons.append(dict(frame_index=f, instances=polys)) mappings.append(dict(frame_index=f, labels=labels)) relations.append(dict(frame_index=f, relations=rr)) relation_valid.append(provided) jsonl_write(view.path / 'annotation/segment/polygons.jsonl', polygons) jsonl_write(view.path / 'annotation/segment/instances.jsonl', mappings) torch.save(torch.ones(len(frames), dtype=torch.bool, device='cpu'), view.path / 'annotation/segment/mask_valid.pt') view.component('segment', 'segment/instance_polygons/v1', 'annotation/segment/polygons.jsonl', ['T'], ann_loc, valid_ref='annotation/segment/mask_valid.pt', valid_axes=['T'], segmentation_type='instance', mapping_ref='annotation/segment/instances.jsonl', coverage={'kind': 'unknown', 'exhaustive_ref': 'annotation/segment/instances.jsonl'}) view.relations(relations, relation_valid, ann_loc) for component in ('depth', 'mano', 'keypoints_uv', 'keypoints_xyz', 'intrinsic', 'extrinsic'): view.absent(component, 'Not provided by VISOR sparse source annotations') return view.finish()
def main(argv=None): p = parser('EPIC-KITCHENS-VISOR', __doc__) p.add_argument('--videos', help='Comma-separated video names') p.add_argument('--splits', default='train,val') args = p.parse_args(argv) wanted = set(args.videos.split(',')) if args.videos else None splits = set(args.splits.split(',')) if not splits <= {'train', 'val'}: p.error('only annotated train/val splits are available') out = release(args, 'EPIC-KITCHENS-VISOR') archive = find_file(args.root, 'EPIC-KITCHENS VISOR.zip') with tempfile.TemporaryDirectory(prefix='visor-source-') as wd: work = Path(wd) if archive: with zipfile.ZipFile(archive) as z: suffix = 'GroundTruth-SparseAnnotations/annotations/' members = [n for n in z.namelist() if suffix in n and n.endswith('.json')] prefix = members[0].split(suffix)[0] fm = json.loads(z.read(prefix + 'frame_mapping.json')) done = 0 for member in sorted(members): split, filename = member.split(suffix)[1].split('/') video = Path(filename).stem if split not in splits or wanted and video not in wanted: continue data = z.read(member) rgb_member = prefix + f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' rgb_zip = work / (video + '.zip') with z.open(rgb_member) as inp, rgb_zip.open('wb') as dest: shutil.copyfileobj(inp, dest) with sequence_dir(out, video) as dest: report = convert_video(video, split, json.loads(data), locator(archive, member, data), rgb_zip, locator(archive, rgb_member), fm.get(video, {}), args, dest / 'ego') build_record(out, video, {'ego': report}) rgb_zip.unlink() done += 1 print(f'Converted {video}', flush=True) if args.limit and done >= args.limit: break else: root = next((r for r in roots(args.root) if (r / 'GroundTruth-SparseAnnotations').is_dir()), None) if root is None: p.error('VISOR outer ZIP or extracted source directory not found') fm = json.loads((root / 'frame_mapping.json').read_text()) if (root / 'frame_mapping.json').exists() else {} done = 0 for split in sorted(splits): for ann in sorted((root / 'GroundTruth-SparseAnnotations/annotations' / split).glob('*.json')): video = ann.stem if wanted and video not in wanted: continue rgb = root / f'GroundTruth-SparseAnnotations/rgb_frames/{split}/{video.split("_")[0]}/{video}.zip' with sequence_dir(out, video) as dest: report = convert_video(video, split, json.loads(ann.read_text()), locator(ann), rgb, locator(rgb), fm.get(video, {}), args, dest / 'ego') build_record(out, video, {'ego': report}) done += 1 if args.limit and done >= args.limit: return 0 if not done: p.error('no matching annotated videos found') return 0
if __name__ == '__main__': raise SystemExit(main())
# TODO(v2.0): 旧距离猜侧和单层掩码生成仅注释保留;v1.0 不执行。# if side is None and len(frame_hands) == 1:# # 空间门槛:脱下放在远处的手套不并入(实测双峰 0..25px / ≥44px)# hb = frame_hands[0][1]# gb = _bbox_of(polys)# if hb and gb and _bbox_dist(gb, hb) <= GLOVE60_MERGE_BBOX_DIST:# side = frame_hands[0][0]# stats["glove60_merged_into_sole_hand"] += 1# if side is None:# stats["dropped_glove60_unresolved"] += 1# id_disp[mid] = ("dropped", "glove60")# continue# def rasterize_and_encode(vdir, frames, frame_draw, zip_path, n, stats):# """流式读 zip 内 jpg + 光栅化多边形 → rgb.mkv / mask.mkv;返回 (w, h)。"""# from PIL import Image, ImageDraw## with zipfile.ZipFile(zip_path) as zf:# member_of = {}# for nm in zf.namelist():# member_of[os.path.basename(nm)] = nm# names = [im["name"] for im in frames]# missing = [nm for nm in names if nm not in member_of]# if missing:# raise RuntimeError(f"{len(missing)} annotated frames missing in zip, "# f"e.g. {missing[:3]}")# stats["zip_extra_members"] = len(member_of) - len(names)## # 首帧定分辨率(官方 1920×1080,实测每帧校验)# img0 = Image.open(io.BytesIO(zf.read(member_of[names[0]]))).convert("RGB")# w, h = img0.size## bin_img = Image.new("L", (w, h), 0)# bin_draw = ImageDraw.Draw(bin_img)# canvas = np.zeros((h, w), np.uint16)# with VideoPipe(vdir / "mask.mkv", w, h, FPS, "mask") as mw, \# VideoPipe(vdir / "rgb.mkv", w, h, FPS, "rgb") as rw:# for f in range(n):# canvas[:] = 0# for pid, polys in frame_draw[f]:# bin_draw.rectangle((0, 0, w, h), fill=0)# for poly in polys:# bin_draw.polygon([(float(x), float(y)) for x, y in poly], fill=255)# arr = np.asarray(bin_img)# canvas[arr > 0] = pid # 后画覆盖先画:物体→手(modal)# mw.write(canvas)# img = img0 if f == 0 else Image.open(# io.BytesIO(zf.read(member_of[names[f]]))).convert("RGB")# if img.size != (w, h):# raise RuntimeError(f"frame {names[f]}: size {img.size} != {(w, h)}")# rw.write(np.asarray(img))# n_mask, n_rgb = mw.n, rw.n# if (n_rgb, n_mask) != (n, n):# raise RuntimeError(f"wrote rgb={n_rgb} mask={n_mask} != {n}")# got = (count_frames(vdir / "rgb.mkv"), count_frames(vdir / "mask.mkv"))# if got != (n, n):# raise RuntimeError(f"encoded rgb={got[0]} mask={got[1]} != {n} (decode verify)")# return w, h##12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""Preserve completed r1 sequences without re-encoding or touching source files."""import datetimeimport jsonimport osfrom pathlib import Pathimport shutil
old = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260929-r1')new = Path('/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10')snapshot = Path('/tmp/h2o-w4-c10-recovery')new.mkdir()shutil.copytree(snapshot / 'scripts', new / 'frozen-code/scripts')shutil.copytree(snapshot / 'docs', new / 'frozen-code/docs')shutil.copytree(snapshot / 'tests', new / 'frozen-code/tests')release = new / 'H2O/shared-v1.0'for directory in ('data', 'doc', 'script', 'script/provenance/r1', 'script/provenance/operations'): (release / directory).mkdir(parents=True, exist_ok=True)history = release / 'script/provenance/r1'shutil.copytree(old / 'H2O/shared-v1.0/script', history / 'script')shutil.copytree(old / 'frozen-code/docs', history / 'docs')for name in ('full.log', 'full.status', 'run-full.sh'): shutil.copy2(old / name, history / name)records = []for record in sorted((old / 'H2O/shared-v1.0/doc').glob('*.build.json')): build = json.loads(record.read_text()) seq = build['sequence_id'] assert Path(seq).name == seq and seq not in ('.', '..') assert set(build['views']) == {f'cam{i}' for i in range(5)}, seq data = old / 'H2O/shared-v1.0/data' / seq frames = {} for cam in build['views']: meta = json.loads((data / cam / 'metainfo.json').read_text()) frames[cam] = sum(1 for _ in (data / cam / 'camera/frames.jsonl').open()) assert frames[cam] > 0 shutil.copytree(data, release / 'data' / seq, copy_function=os.link) shutil.copy2(record, release / 'doc' / record.name) records.append({'sequence_id': seq, 'frames_by_camera': frames, 'original_script_sha256': build['scripts']})manifest = {'time': datetime.datetime.now().astimezone().isoformat(), 'source_run': str(old), 'destination_run': str(new), 'reason': 'User requested four archive workers, ten threads per encoder, no CPU quota', 'reuse': 'Hard-linked immutable completed views; frames and component source SHA256 rechecked during resume', 'excluded': 'Unpublished .tmp directories; historical 62-sequence output; failed initial full run', 'original_runtime_provenance': 'script/provenance/r1', 'sequences': records}(release / 'doc/RESTART_PROVENANCE.json').write_text(json.dumps(manifest, indent=2) + '\n')for source, target in (('/tmp/h2o-prepare-w4-c10.py', 'provenance/operations/prepare-w4-c10.py'), ('/tmp/h2o-reconfigure-w4-c10.sh', 'reconfigure-w4-c10.sh'), ('/tmp/h2o-run-w4-c10.sh', 'run-full.sh')): shutil.copy2(source, release / 'script' / target)shutil.copy2('/tmp/h2o-run-w4-c10.sh', new / 'run-full.sh')shutil.copy2('/tmp/h2o-w4-c10-frozen-tests.log', history.parent / 'worker4-codec10-regression.log')print(f'REUSED_SEQUENCES={len(records)} REUSED_VIEWS={sum(len(r["frames_by_camera"]) for r in records)}', flush=True)1234567891011#!/usr/bin/env bashset -euo pipefailbase=/data/xuzhefeng/Datasets/uni-hoi-h2o-full-20260930-w4-c10script="$base/H2O/shared-v1.0/script"mkdir -p "$script/provenance/operations" "$script/provenance/startup-failure"mv "$script/prepare-w4-c10.py" "$script/provenance/startup-failure/prepare-w4-c10.py"cp /tmp/h2o-prepare-w4-c10.py "$script/provenance/operations/prepare-w4-c10.py"mv "$base/full.status" "$script/provenance/startup-failure/full.status"mv "$base/full.log" "$script/provenance/startup-failure/full.log"cp /tmp/h2o-retry-w4-c10.sh "$script/provenance/operations/retry-w4-c10.sh"systemd-run --user --scope --unit=h2o-full-w4c10-r2-20260930 -p CPUAccounting=yes /bin/bash "$base/run-full.sh"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457# 手物数据仓库统一约定 v1.0
格式版本:`hand-warehouse/1.0`。存储约定:`lossless-video-2026-09-18`。
范围限于手物交互重建。按本任务纳入的源模态转换,不要求每个数据集填满所有组件。缺失模态、尚未下载、语义未核实分别报告,不能互相替代。
本文定义各字段的含义与使用规则,机器可读注册表见 [schema.json](schema.json)。两者互相补充;如有冲突,应先核实并统一定义。
## 1. 目录
```text
hand-datasets/
<dataset_name>/
raw/
doc/ # 官方说明、来源与校验记录
script/ # 官方下载脚本、必要包装脚本
data/ # 保留原始包,不原地解压或改写
<dataset_version>/
doc/ # 发布说明、schema、来源清单
script/ # 转换、校验脚本及运行配置
data/
<sequence_id>/
<camera_id>/
metainfo.json
observation/
rgb.mkv
rgb_valid.pt
depth.mkv # float32 深度的可逆视频编码
depth_valid.mkv # 逐像素 bool 的无损视频编码
camera/
frames.jsonl
intrinsic.pt
intrinsic_valid.pt
extrinsic.pt
extrinsic_valid.pt
annotation/
mano/
motion.pt
motion_valid.pt
visibility.pt
keypoints/
uv.pt
uv_valid.pt
xyz.pt
xyz_valid.pt
visibility.pt # 源数据有时提供
object/
<object_id>/
assets/ # 该物体的网格、材质、纹理及部件资产
<mesh_id>.obj
pose.pt
pose_valid.pt
visibility.pt
metainfo.json # 物体身份、类别、mesh、尺寸与部件引用
articulation.json
keypoints/
vertex_part_ids.pt
joint_state.pt
joint_state_valid.pt
parts/<part_id>/pose.pt
parts/<part_id>/pose_valid.pt
segment/
mask.mkv
mask_valid.pt
instances.jsonl
contact/
relations.jsonl
<subject_id>__<object_id>/ # 对应实体间的距离/接触区域
```
目录展示可能存在的组件,不要求填满。具体文件、字段和缺省规则分别见后续对应小节。原始包的解压发生在临时工作区,raw 内原始包保持不变。
## 2. 相机视图的 metainfo.json
### 2.1 顶层字段与发布信息
每个相机视图必须有 `metainfo.json`。以下字段除另行说明外均为必填:
| 字段 | 填写内容 |
|---|---|
| schema_version | 结构版本,本版为 `hand-warehouse/1.0` |
| dataset_id | 数据集的逻辑标识 |
| release_id | 本次数据发布版本,对应目录中的 dataset_version |
| sequence_id | 所属序列或独立图片样本的标识 |
| camera_id | 当前相机视图标识 |
| sample_type | `image` 或 `video`,规则见 2.2 |
| num_frames | 当前视图帧数 T,所有随帧组件按同一时间轴组织 |
| hand_slots | 固定为 `["left", "right"]`;解剖学左右的使用规则见 5.1 |
| sampling | 采样类型、源 FPS、帧索引引用及选择策略,见 2.2 |
| camera | 当前相机模型与图像尺寸,见 2.3 |
| components | 实际提供的组件及其文件、schema、有效性和来源,见 2.5 |
| split | `train/val/test/unknown`,划分协议见 2.4 |
| view_type | 可选,`ego/exo/unknown` |
`dataset_version` 是数据发布版本;`schema_version` 是结构版本,两者独立。原始包校验摘要、官方来源和转换配置应记录在发布清单中。解压发生在临时工作区,原始包保持不变。
### 2.2 图片、视频与 sampling
`sample_type=image`:允许单图 T=1、`sampling.type=single`,也允许将独立图片批量装入一个视频容器,T>1 时 `sampling.type=independent`、`source_fps=null`。分片大小按数据集选择;FreiHAND 默认每片最多 4096 张,训练与评估分开,尾片不补帧。该数量不是其他数据集的强制要求;同批分辨率、相机模型类型及划分协议一致。每行 frames 必须有稳定且唯一的 `sample_id`、原始文件定位;内参、手形状等仍逐帧保留,不能因打包而共享错误的标定或身份。`sequence_id` 在这里仅是批次标识,不代表真实序列;不得按相邻帧推断跟踪、同步或接触延续。源 camera_id、image_variant、split 等随样本变化时放在 frames 的对应字段中。真实采集时间未知则 timestamp_ns=null。合成背景变体不视为真实多相机。
`sample_type=video`:`sampling.type=dense/sparse`;`source_fps` 是真实采集 FPS,未知为 null。非连续取样必须保留源帧号和已知源时间,不可用采样后索引除以 FPS 冒充源时间。可另记采样策略与步长。
shared 可以仅存所选 RGB 帧对应的数据。OakInk2 图像/动捕不同采样率时用 annotation_matches 明确映射;不要求将未采样动捕点硬塞进 T。多视角身份和源同步关系要保留;选择了哪些帧/相机及原因写在 sampling 中。
`sampling.frames_ref` 指向 `camera/frames.jsonl`。帧号、逐帧时间、同步与标注匹配记录的结构见 4.1;MKV 封装时间的约定见 3.1。
### 2.3 camera 模型声明
`camera` 至少包含 `model`、`schema_id`、`image_size:[W,H]`。模型未知使用 `unknown` 和 `null`,不猜成针孔。实际内参、畸变及外参数组放在 `camera/`,各模型的固定结构见第 4 节。
### 2.4 split 与划分协议
保留上游划分,不将同一采集序列的相邻帧随意拆到不同集合。
有官方划分时必填 split_scheme 和 split_source_locator,split_scheme 区分如 Dex-YCB s0/s1、ARCTIC P1/P2 等选定协议;不知道时 split=unknown 并给理由,不凭空分配。每发布可选择一种协议;存在逐帧差异时 frames 中的 split 覆盖视图默认值,并登记其来源。
### 2.5 components 组件登记
组件表的键是本发布内唯一名称,例如 `rgb`、`depth`、`mano`、`keypoints_uv`。每个已提供组件声明以下信息;模态特有参数在第 3–5 节对应小节中定义。
| 字段 | 约定 |
|---|---|
| available | 本发布是否提供该组件;缺省也表示未提供 |
| schema_id | 已登记的具体存储与语义类型,不得临时创造未登记名称 |
| data_ref | 数据文件路径,相对当前相机视图根目录,使用 POSIX 路径 |
| axes | 数组各维度的含义 |
| valid_ref / valid_axes | 有效性文件及其维度;语义由所属组件规定 |
| storage / valid_storage | 视频数据/视频有效性的存储配置;包含已登记 profile、实际 codec、pixel_format、encoded_size,见 3.1;非视频组件按原数组规则 |
| provenance | source / format_conversion / derived,以及转换或生成方法 |
| source_locator | 原文件、压缩包成员和记录/帧的定位信息 |
不存在的组件允许缺省或写作 `{ "available": false, "reason": "..." }`,不用引用不存在的文件。静态网格可声明标量有效性;具体见 5.4。观测的 valid 见第 3 节,标注的 valid 与 visibility 区分见 5.1。
`provenance.kind` 使用 source/format_conversion/derived,`method` 说明转换或生成方法;发布清单补充脚本版本、参数、输入摘要。`source_locator` 定位到原始文件/压缩包成员和记录、帧号;允许引用有完整溯源清单的前一发布,但链条最终应能回到 raw。不得仅写一个无法定位记录的数据集名字。
`.pt` 仅保存 CPU Tensor,不保存 Python 自定义对象;浮点默认 float32,有效性为 bool,浮点无效位置填 NaN。所有随帧数组保留首维 T,单帧也不 squeeze;静态资产按其 schema 单独声明。单位、坐标及固定形状见各组件小节。
机器注册表 `schema.json` 中,`components` 固定解码后的数据类型、形状、单位和语义;`storage_profiles` 固定视频内的编码/还原方式。不得临时创造未登记的 schema_id 或 storage.profile。同一语义允许选择其登记的不同无损存储 profile。
## 3. observation 观测数据
### 3.1 rgb.mkv 与 rgb_valid.pt
RGB、深度和栅格 mask 在 shared 中统一使用 MKV 视频容器,不展开为逐帧图片或图像 tar。MANO、关键点、位姿等数值标注仍用数组;分割的重叠多边形仍用 JSONL,不为了视频化而有损栅格化。单图可为一帧视频,独立图批量封装规则见 2.2。
**无损指共享层不增加信息损失。** 源 JPEG/H.264 等本身可能已是有损编码,原样保留并不恢复已丢失信息;不得重新以有损 JPEG、H.264、H.265、AV1 参数编码。源视频/图片的色彩、位深、分辨率和几何关系不得被静默改变。RGB schema `rgb/uint8/v1` 的统一读取结果是 `[T,H,W,3] uint8`、RGB 通道,有效性仍为 `rgb_valid.pt [T] bool`。超出该 schema 的高位深或 HDR 源必须报告并扩展定义,不能降到 8 位冒充无损。
#### 3.1.1 允许的 RGB 存储 profile
| storage.profile | 编码方式 | 适用规则 |
|---|---|---|
| mkv/mjpeg_copy/v1 | 源 JPEG 压缩帧直接封装成 MJPEG/MKV | 不解码重编码;保持每张 JPEG 码流字节;普通 8 位 JPEG 且 MKV/解码器支持时使用 |
| mkv/source_copy/v1 | 已有视频的 RGB 对应码流直接封装为 MKV | 仅源编码能被 MKV 和选定解码器支持时使用,不伪造帧;需维持正确的呈现顺序与依赖帧 |
| mkv/h264_rgb_lossless/v1 | libx264rgb 的真正无损模式 | 必须 RGB 路径、CRF=0,并通过全帧 RGB 字节比较;不能替换成默认 libx264 YUV420 路径 |
| mkv/ffv1_rgb/v1 | FFV1 的 RGB 可逆编码路径 | 作为通用候选;解码回 RGB 后必须逐字节相同,不做色度降采样 |
优先尝试源码流直接封装;不能封装或需要选择稀疏帧时,比较 FFV1 与无损 RGB H.264。对完整待发布片段,只在通过无损验收的候选中选择文件较小者,不假设某个编码器总最小;编码时间和随机读取代价记入构建记录。中间候选不作为 shared 多份常驻。H.264 跨帧压缩允许较长 GOP,必须记录 GOP/关键帧间隔,随机取帧需从前一关键帧正确解码,不能把 seek 返回的近似帧当目标帧。
普通源视频可以保留它已有的有损码流,但不允许新增有损重编码。源是 VRS 等记录容器时,先查明图像流实际编码:已有兼容 JPEG/视频包可直接提取封装,否则解码后使用真正无损编码;不把整个 VRS 改后缀当 MKV。PNG 不要求直接塞进 MKV,可选上表两种无损重编码方式。
#### 3.1.2 视频配置与校验
每个视频组件在 metainfo 中登记 `storage`,至少包含:
| 字段 | 内容 |
|---|---|
| profile | 上述登记的存储 profile;语义仍由组件 schema_id 指定 |
| codec | 文件中实际 codec,例如 mjpeg、h264、ffv1;source_copy 必须写实际 codec |
| pixel_format | 实际编码像素格式;不得仅凭编码器参数猜测 |
| encoded_size | 视频物理像素尺寸 `[width,height]`;深度可能不同于逻辑尺寸,见 3.2 |
| decoder | 解码器名称、版本,以及颜色矩阵/范围/旋转处理等实际像素解释配置;未知的源色彩声明 unknown,不擅自称为 sRGB |
| encoder_parameters | 重编码时的编码器、版本、无损模式和 GOP 等参数;直接封装时记录 stream_copy |
| source_lossy | 源是否已有损:true / false / unknown;不是共享层再有损编码的许可 |
无损重新编码的 RGB 必须使用同一固定解码配置,比较**全部帧**的统一 RGB 字节、数量及顺序。MJPEG-copy 不重新编码,生产校验采用 `jpeg-packets-all-rgb-sample16/v1`:从 MKV 逐包取回,对全部源 JPEG 的 SHA256、数量、顺序和图像尺寸进行精确核对;每视图另用同一固定解码配置比较最多 16 帧的源与目标 RGB 字节(含首尾与四分位位置,其余由固定种子抽取)。记录策略、实际索引、种子与结果;不足 16 帧时全查。试点与最终完整序列随机抽查,对选中视图的全部帧复核解码 RGB。历史已做全帧像素检查的证明继续保留。
逐包一致与像素抽查的范围必须分别声明,不能将抽查写成全量像素检查。不能用 PSNR 高、视觉相似、编码器参数称为 lossless 等替代精确检查。同时保留源编码的色彩标记和必要元数据;原图有 EXIF/色彩/方向等元数据时保留 raw 和必要来源信息;不能静默自动旋转图像而不更新像素对应与标定。以上加速策略仅适用于原 JPEG 码流直接封装,不适用于深度、标签或重新编码的 RGB。
所有共享视频的呈现帧顺序与统一 frame_index 一一对应,每个栅格组件恰好 T 帧。MKV 的 `storage_fps` 只服务封装,声明 `timebase_role=index_only`;source_copy 可以保留源 PTS 以避免改坏码流,但真实时间与标注对齐仍以 frames 为准。未知真实时间保留 null。缺失某帧组件时保留索引位置并使用该组件的无效占位/valid 标识,不删帧;不能以重复相邻图像冒充已知观测。
### 3.2 depth.mkv 与 depth_valid.mkv
深度语义仍是 `depth/z_float32/v1`:统一读取结果 `[T,H,W] float32`,米制相机 Z 分量,`depth_type=z`。有效深度有限且大于 0,无效位置为 NaN。`depth_origin=measured/rendered/unknown` 必填,来源不明时 unknown。默认与 RGB 共用像素网格及相机参考系,不处理未注册 RGB-D。射线距离必须依据源定义转换成 z,不能只改声明。
#### 3.2.1 float32 的可逆视频编码
采用 `mkv/depth_float32_bits/v1`:**不是把深度量化成 uint16**,而是将规范化后每个 IEEE-754 float32 的完整 32 位拆成两个 uint16,使用 FFV1 gray16le 保存。视频物理尺寸为 `[2W,H]`:每行前 W 列存原 float32 位串的低 16 位,后 W 列存高 16 位。读取时先合并为 uint32 位串,再按 float32 重新解释,不能数值 cast 成 float32。
```text
u = reinterpret_uint32(depth_float32)
encoded[:, :, :W] = uint16(u & 65535)
encoded[:, :, W:] = uint16(u >> 16)
u_restored = uint32(low) | (uint32(high) << 16)
depth_float32 = reinterpret_float32(u_restored)
```
统一采用 little-endian 原始字节接口。`camera.image_size` 始终是逻辑 RGB 尺寸 `[W,H]`,不能改成编���视频的 2W;`storage.encoded_size=[2W,H]`。包括 NaN 在内的 float32 位串必须全帧完全恢复,不允许改成 float16、整数毫米、归一化灰度或 RGB 伪彩色。这里的无损验收基准是完成既定米制/坐标转换后的标准 float32 数组,不声称消除 float64→float32 等原约定转换本身的舍入。
#### 3.2.2 逐像素有效性
`depth_valid.mkv` 使用 `mkv/bool_ffv1/v1`,FFV1 gray8(FFmpeg pixel_format=`gray`),物理尺寸 `[W,H]`。像素只能为 0 或 1,统一解码为 `[T,H,W] bool`,逐像素含义不变。这样不再把庞大的 bool 数组保存为未压缩 `.pt`;标注的帧级/手级 valid 仍保留原有小数组。
登记示例(W、H 以下取 640、480;decoder/encoder_parameters 的实际版本由转换器填写):
```json
{
"available": true,
"schema_id": "depth/z_float32/v1",
"data_ref": "observation/depth.mkv",
"axes": ["T", "height", "width"],
"valid_ref": "observation/depth_valid.mkv",
"valid_axes": ["T", "height", "width"],
"unit": "m",
"depth_type": "z",
"depth_origin": "measured",
"invalid_value": "NaN",
"storage": {
"profile": "mkv/depth_float32_bits/v1",
"codec": "ffv1",
"pixel_format": "gray16le",
"encoded_size": [1280, 480],
"source_lossy": false,
"decoder": {"name": "ffmpeg", "version": "填写实际版本"},
"encoder_parameters": {"name": "ffv1", "level": 3, "version": "填写实际版本"}
},
"valid_storage": {
"profile": "mkv/bool_ffv1/v1",
"codec": "ffv1",
"pixel_format": "gray",
"encoded_size": [640, 480],
"source_lossy": false,
"decoder": {"name": "ffmpeg", "version": "填写实际版本"},
"encoder_parameters": {"name": "ffv1", "version": "填写实际版本"}
},
"provenance": {"kind": "format_conversion", "method": "源深度转米制 z float32;逐位打包为 FFV1"},
"source_locator": {"file": "raw/data/depth.zip", "member": "depth/0001.png"}
}
```
深度和有效性视频都必须逐帧解码验收:float32 位串相同、bool 相同、T 相同,并检查 valid=true 的正有限值和 valid=false 的 NaN。读取器必须按 profile 还原,不能把 depth.mkv 的编码像素直接当深度值。
## 4. camera 相机、帧索引与标定
### 4.1 frames.jsonl:索引、时间与对应关系
`camera/frames.jsonl` 每行对应统一帧号 `frame_index=0..T-1`,是所有组件的唯一行索引。至少包含 `frame_index`、`timestamp_ns`、`clock_domain`、`source_locator`;原始帧号/文件名保存在 `source_frame_id`,不能被新帧号替代。每行还可有 `annotation_matches`,按组件键保存 `source_frame_id`、`source_timestamp_ns`、`clock_domain`、`match_method` 和 `delta_ns`;方法为 exact/index_map/nearest/interpolated,索引映射无时间依据时 delta_ns=null。nearest 必须记录允许误差;interpolated 必须记录两端源标识和权重。delta_ns 仅在同一时间域中计算为源标注时间减图像时间。多相机共享 `sequence_id`;已知同步关系必须用 `sync_id` 或明确的源帧/时间映射表达,不能仅凭相同数组索引认定同步。
每个视图必须提供此文件。源时间使用整数纳秒及 `clock_domain`,未知写 JSON `null`;不同时间域不能直接比较。逐帧 split 可以覆盖 metainfo 的视图默认划分,并保留来源,见 2.4。
### 4.2 坐标系与标定通则
| 项目 | 统一约定 |
|---|---|
| 相机坐标 | 右手系,X 向右、Y 向下、Z 向前,长度单位米 |
| 齐次变换 | 列向量,`p_target = T_target_from_source @ p_source` |
| 图像坐标 | `(u,v)`;左上像素中心为 `(0,0)`,u 向右、v 向下,单位 pixel |
| 固定标定 | 本版展开为 T 份,同一 schema 不混用静态与动态形状 |
| 分辨率或模型变化 | 分开存储为视图/片段,不在同一组件中混装 |
| 未知标定 | 相机内外参允许缺省,不填单位阵冒充已知标定 |
### 4.3 intrinsic.pt 与畸变参数
| model / schema_id | intrinsic.pt 的固定结构 |
|---|---|
| pinhole / camera/pinhole/v1 | `[T,3,3]`,标准 K,最后一行为 `[0,0,1]`;限无畸变或已校正图像 |
| fisheye624 / camera/fisheye624/v1 | `[T,15]`,`[f,cx,cy,k0,k1,k2,k3,k4,k5,p0,p1,s0,s1,s2,s3]`,采用 Project Aria Fisheye624 投影定义 |
| opencv_fisheye4 / camera/opencv_fisheye4/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件 `distortion_ref` 指向 `[T,4]`,顺序 `[k1,k2,k3,k4]`,使用 OpenCV fisheye 等距角度多项式;已由 ReInterHand 实际原始相机参数验证 |
| rational8 / camera/rational8/v1 | `intrinsic.pt [T,3,3]` 保存 K;同组件必需 `distortion_ref` 指向 `[T,8]`,顺序 `[k1,k2,p1,p2,k3,k4,k5,k6]` |
| unknown / null | 不提供可用 intrinsic,不声称可以投影 |
有畸变的其他模型必须注册新 schema,固定参数名、顺序和投影公式;不能塞进针孔 K 后遗失畸变项。`metainfo.camera.schema_id` 必须与 intrinsic 组件一致。同一模型的别名不可隐式改变参数布局。
`opencv_fisheye4`:对前方点令 `x=X/Z, y=Y/Z, r=sqrt(x²+y²), theta=atan(r)`,`theta_d=theta*(1+k1*theta²+k2*theta⁴+k3*theta⁶+k4*theta⁸)`;`u=fx*x*theta_d/r+cx, v=fy*y*theta_d/r+cy`。光轴 r=0 时使用连续极限 `theta_d/r=1`。四系数不能按普通径向畸变解释,也不能补零冒充 Fisheye624。
rational8 对归一化坐标 x=X/Z、y=Y/Z,令 r²=x²+y²,径向项为 `(1+k1*r²+k2*r⁴+k3*r⁶)/(1+k4*r²+k5*r⁴+k6*r⁶)`;再加 p1/p2 切向项并经 K 得到像素。`distortion_ref` 与 intrinsic 共用 `[T]` valid,保存到 camera/distortion.pt。不得把这种畸变三维坐标当作真实相机系 xyz 保存。
内参有效性为 `intrinsic_valid.pt [T] bool`;有畸变时使用对应 `distortion_ref`。同一模型的参数名和顺序固定。
### 4.4 extrinsic.pt 与 extrinsic_valid.pt
`extrinsic.pt` 为 `[T,4,4]`,schema `transform/se3/v1`,方向固定 `T_camera_from_world`,有效性 `[T]`。世界坐标含义及源坐标转换记录在 provenance 中;只有相机坐标标注不要求虚构世界坐标。旋转块须正交且 determinant≈1。
## 5. annotation 标注数据
### 5.1 标注通则:手槽、valid 与 visibility
手槽固定为 0=left、1=right,指解剖学左右,不按画面位置或可见性重排。本阶段只处理左右手两槽,不处理更多手。实体引用使用 `hand_left`、`hand_right`;手槽不证明跨采集片段的个人身份。
#### 5.1.1 valid:标注是否可用于监督
标注的 `valid=true` 表示:有对应实际标注、通过本 schema 数值检查,且通过来源明确提供并适用于该组件的有效性/QA 条件。`valid=false` 可由缺标注、无法建立帧对应、源无效占位或官方 QA 不通过导致;不等于画面没有手或手不可见。各组件独立判断,MANO 按 `[T,2]` 标记左右手,关键点按 `[T,2,K]` 标记。
**2026-09-20 将标注 valid 从“仅表示存在”修订为“可用于监督”,字段形状不变。** 公式为 `source_annotation_present AND numerical_checks_pass AND applicable_official_QA_pass`。没有官方 QA 时省略最后一项,不伪造 QA;不能把未知当成已通过已存在的 QA。适配器在组件 `valid_policy` 中记录具体规则、来源、聚合/广播作用域。缺失官方必需 QA 的记录须明确处理为未知或暂停验收,不能静默通过。无效浮点项仍填 NaN,原始数据保留在 raw;被排除原值可用于 doc 中明确标识的诊断渲染,不能冒充 shared 有效监督。
本地筛选须依据明确的规则,并在 `valid_policy.local_excluded_frame_indices`、排除原因和正式报告中记录。单个可疑投影作为问题记录,不直接硬编码排除该帧。已确认的曝光异常须明确作用范围,不能把一个序列的“前两帧有问题”套到所有序列。RGB 编码完好与几何监督可用是两件事,允许保留原图及帧索引而屏蔽对应标注;未发现问题不等于完成全部人工审核,试点待确认时不能作为已验收发布使用。
源字段必须按官方语义映射,不能直接按名字复制:
| 来源 | 官方含义 | 映射原则 |
|---|---|---|
| [H2O](https://github.com/taeinkwon/h2odataset) 的手标注首位 | 0 未标注、1 已标注 | 可作为对应手标注存在性的依据,不推断未标注原因 |
| [HOT3D](https://github.com/facebookresearch/hot3d#using-mask-files) 的 pose_available、visible、mask_qa_pass | 分别表达姿态存在、可见性、对画面中可见手物位姿的人工 QA | 逐手/物体记录决定存在性,再 AND 当前相机当前帧 QA;QA 是整帧聚合判定,保守排除该帧全部手物几何监督,不声称每个实体均有错误;源可见性基于位姿推导时,其自身 valid 同样受 QA 约束 || [Dex-YCB](https://github.com/NVlabs/dex-ycb-toolkit#loading-dataset-and-visualizing-samples) 的全零 pose_m、全 -1 joints | 不可见的手或缺标注共用占位表示 | 对应组件 valid=false;不能从该值判定 visibility=false,也不能声称原因是动捕缺失 |
| [ARCTIC](https://github.com/zc-alexfan/arctic/blob/master/docs/data/data_doc.md) 的 is_valid/left_valid/right_valid | 是否有效用于官方评估 | 核实每项筛选依据;不把可见性/评估选择直接等同 QA。本次原始 mano.npy 不含这些派生评估标记,按原记录与数值检查生成 valid,并声明没有额外官方 QA 输入 |
源 valid=false 若代表评估筛选或其他条件,应检查实际标注和源约定后映射;不能一律清空坐标。反之,占位零或 -1 只有在源官方明确规定时才判为缺失,不泛化成所有数据的判断规则。
`valid=true` 的标注应通过其 schema 的数值与形状检查;检查失败必须报告或修复,不能静默隐藏。QA 不通过应报告排除数量与原因,并保留可追溯信息;不能把这类无效称为缺标注。RGB、深度等观测有效性仍按各自 schema;手物 QA 不自动否定 RGB、静态相机内参或物体资产。相机外参是否过滤须依据其自身来源规则;HOT3D 本次保留源外参用于溯源和诊断,不能用其存在性证明 QA 失败帧的几何监督正确。
#### 5.1.2 visibility:可见性属性
附加质量属性只保留 `visibility`,存放在对应模态或标注集内,不设 quality 目录。同一份可见性仅存一次;uv 与 xyz 共用时引用同一个文件。
visibility 通过所属组件 attributes 登记 data_ref、axes、dtype、visibility_type、meaning、provenance、source_locator;未知值通过属性 valid_ref 标识,全已知可声明 valid=true。比例与布尔值不相互强转,也不按任意阈值二值化。没有 MANO 时,整手可见性挂在 keypoints 组件,使用独立的 whole_hand_visibility.pt,明确 meaning=whole_hand,不与逐关键点可见性混用。
`valid` 回答“这项标注能否用于监督”,`visibility` 回答“在当前图像中是否可见(或可见多少)”。不可见的手或关键点仍可有有效标注;不能因 visibility=0 就清空坐标。源没有 visibility 时缺省或标为未知,不由 valid 推断。
| 情况 | 手标注 valid | visibility |
|---|---|---|
| RGB 已开始录制,动捕尚未开始,没有其他对应手标注 | false | 以独立源可见性标注为准;没有则未知 |
| 手被遮挡,但源有标注且通过适用有效性检查 | true | 若源声明不可见,则 false 或源可见比例 || 手可见且有对应标注,通过适用 QA | true | 若源有此信息,则 true 或源可见比例 || 手可见,但该帧漏标或动捕中断 | false | 可以为 true,但必须有独立来源依据 || 有手部参数,但官方 QA 明确不通过 | false | 不据此断言不可见;源可见比例若基于不可靠位姿,其属性 valid 也为 false |
visibility 自己的 valid_ref 表示该可见性标注是否可用,不复用 MANO 或关键点坐标的 valid_ref;明确记录源存在性及适用的 QA 条件。上述例子不要求凭图像自动生成可见性。
不设 quality 组件或目录,不另存拟合误差、曝光、截断比例等通用质量数组。适用的官方 QA 合并进对应 valid,在 `valid_policy` 记录来源与规则;正式校验报告保留原始 QA 时间区间及排除统计。原始 QA 文件仍在 raw,官方 split 保留。
### 5.2 mano:参数与整手可见性
MANO schema `mano/axis_angle61/v1`:`motion.pt [T,2,61]`,顺序为完整 16 关节 axis-angle 48、shape betas 10、全局平移 3。姿态使用弧度,平移米,位于当前相机系。有效性 `[T,2]`;缺少一侧整槽 NaN。PCA 必须先按对应模型展开,不能将 PCA 系数直接填入 axis-angle。
`model_profile` 必须固定 MANO 版本、`flat_hand_mean=true`、左手 shapedirs 修正状态。平移表示模型输出顶点所加的全局平移,不是某个腕关节的坐标;源语义不同须转换。shape 无量纲。模型权重不作为共享数据附带上传。
`mano/visibility.pt [T,2]` 保存源整手可见比例时使用 float32 [0,1],`visibility_type=ratio`;只有实际采用 0–100 的百分比才除以100,不能只凭表头判断。HOT3D 的 `visibility_ratio[%]` 实值已经是0–1,官方读取器原样读取,必须保留原值。通过 MANO 组件 attributes 登记,使用独立有效性,不复用 motion_valid。
手部共享表示仅保留 MANO 参数与选定关键点,不发布独立手表面几何。需要渲染或接触计算时由 MANO 参数生成,几何引用使用固定 MANO 模型配置与顶点顺序;不影响 object 下的物体模型和材质资产。
### 5.3 keypoints:二维点、三维点与逐点可见性
关键点独立于 MANO 参数存在;没有 motion 也可有关键点。`uv.pt [T,2,K,2]` 与 `xyz.pt [T,2,K,3]`,有效性 `[T,2,K]`,分别采用 `keypoints/uv/v1` 和 `keypoints/xyz/v1`。K 由 `keypoint_schema` 固定,不能在同一数组中逐帧变化;同体系统一顺序。数值使用像素坐标或米制相机系。
| keypoint_schema | K 与固定索引 |
|---|---|
| mano21/v1 | 21;wrist 后依次 thumb/index/middle/ring/little,每指由近端至指尖 |
| rhd21/v1 | 21;保持 wrist,然后五指由近端至指尖;原始每指 tip→palm 反序。只统一顺序,不宣称解剖学位置等价于 MANO |
具体名称与源索引映射见 `schema.json`。当前只登记 MANO21 与 RHD21;不登记 MediaPipe、ReInterHand capture21 或 fit24 中间关键点。
每个发布中的每个视图只提供一套标准手关键点,直接放在 keypoints 下,不设 annotation_set_id 字段或目录。uv 与 xyz 是这套关键点的二维与三维表示,不是两套标注。provenance 分别记录二者来自原始标注还是计算结果;不要求已有 2D 必须由当前 xyz 重新投影覆盖。
ReInterHand 的 Original keypoints���Original fits keypoints 及带前臂关键点不纳入 shared;如需手关键点,从选定 MANO 参数生成 MANO21 并记录模型/指尖回归约定。其他数据集默认使用选定的官方关键点,不额外生成平行的 MANO 派生集合。后续主动更换生成方法或结果时发布新的 dataset_version,不在同一版本内增设方法分支。
manual/projection/fitting 只记录在 provenance,不作为目录或类型分支。不得通过坐标为零、是否出画或 visibility 判断标注是否存在。派生标注仅在实际生成并通过数值检查后声明 valid=true;没有生成的项为 false,不伪造坐标。
`keypoints/visibility.pt [T,2,K]` 保存源逐点可见性,布尔表示使用 `visibility_type=boolean`。uv 与 xyz 共用时引用同一份文件。整手比例属性没有 MANO 可挂载时使用 `whole_hand_visibility.pt [T,2]`,`meaning=whole_hand`;它与逐点可见性分开,通用登记规则见 5.1。
不使用 annotation_set_id;ReInterHand 中间关键点集合不进入 shared,raw 保留来源文件。
### 5.4 object:身份、资产、位姿与几何
#### 5.4.1 metainfo.json:物体身份与跟踪作用域
手用 `hand_left`、`hand_right` 及槽位 0、1 表示,不再另存 entities.json。物体身份登记在 `annotation/object/<object_id>/metainfo.json`,必填 `object_id`、`identity_scope`、`scope_id`、`source_locator`;可含 `category_id`、`source_object_id`、`mesh_ref`、`has_model`、部件引用。即使只有分割、没有 pose/mesh,也可只有这份物体元信息。
`identity_scope` 为 frame/subsequence/sequence,`scope_id` 指定具体作用域;跨相机共享身份只在已有源对应证据时使用。VISOR 按官方 subsequence 与实体名关联时记录 `association_basis=official_subsequence_entity_name`,不能声称这是全视频物理实例跟踪。无需与 object_id 一一对应的标准 track_id;官方独立轨迹标识存在时保留为 source_track_id,并声明作用域。手槽不证明跨采集片段的个人身份。
#### 5.4.2 assets:网格、材质与纹理
资产属于物体,统一存放在 `annotation/object/<object_id>/` 内,可用 `assets/` 子目录组织网格、材质、纹理和部件资产。序列层不设共享 assets。所有引用采用视图根目录为基准;其中物体资产组件的 `data_ref` 与部件的 `mesh_ref` 采用相对于当前视图目录的 POSIX 路径,例如 `annotation/object/cup_01/assets/cup.obj`,且必须指向所属物体目录内的资产。OBJ 内部的材质、纹理引用遵循文件格式自身的相对路径规则,依赖文件一并保留。不同相机视图允许各自保存物体资产,不要求跨视图去重;下载物体时包含其资产依赖。
网格 schema 为 `mesh/obj/v1`,顶点米制,静态有效性可直接声明标量 `valid`,或通过 `valid_ref` 指向标量 bool Tensor;不按 T 重复静态资产。由物体/部件通过引用关联,不仅凭文件名猜测。
#### 5.4.3 pose.pt、pose_valid.pt 与 visibility.pt
刚体 schema 为 `object/rigid/v1`,`pose.pt [T,4,4]` 固定为 `T_camera_from_object`,平移米制,有效性 `[T]`。物体坐标原点、轴向必须与 mesh 一致;旋转块为正交矩阵且 determinant≈1。
`object/<id>/visibility.pt [T]` 保存源物体可见比例,float32 [0,1],`visibility_type=ratio`。通过所属物体组件 attributes 登记,独立表达其有效性。
#### 5.4.4 articulation.json、部件位姿与 joint_state.pt
关节物体:schema `object/articulated/v1`,`articulation.json` 登记 `parts` 与 `joints`。每个 part 有 `part_id`、`parent_id`(根为 null)、`has_model`、`mesh_ref`;has_model=false 时 mesh_ref=null,结构节点允许没有网格。父链不得成环。每个 joint 有唯一 `joint_id`、`parent_part`、`child_part`、`type`;fixed 单位 null、revolute 弧度、prismatic 米。有源限位时保存 `limits:[lower,upper]`;没有时 null,不伪造上下限。部件姿态统一为 `T_camera_from_part [T,4,4]`,不与父局部变换混装。
若提供 `joint_state.pt [T,J]`,必须登记固定 joint_order、轴在父部件系的表达、零位变换与正方向,valid 为 `[T,J]`;缺少这些运动学定义时只发布部件位姿与已有来源信息,不伪造可驱动的关节模型。关节值与部件位姿同时存在时需验证一致性。
部件层级应声明语义:纯语义包含树允许 `joints=[]`,不将包含关系推断为机械关节。关节状态 schema 为 `object/joint_state/v1`;转动用弧度、移动用米,混合类型按 joint_order 对应的关节定义解释。
#### 5.4.5 dimensions、几何关键点与顶点部件标签
`dimensions.pt [T,3]` 采用 `object/dimensions/v1`,有效性为 `[T]`。
物体/部件 `dimensions` 为 `[length,width,height]` 米,轴顺序与该 mesh 的局部坐标关联,登记 `dimensions_semantics` 和来源。HOI4D dimensions 与 mesh 的具体尺度关���未验证前标为 source_unspecified,保留源值并暂停依赖该关系的几何验收,不能默认为待施加缩放。需要施加缩放时明确 scale_applied_to_mesh,禁止重复应用。
源物体关键点放 `object/<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。每个发布选择一套源几何点并记录选择,不另建方法分支。
`vertex_part_ids.pt [V] int64` 绑定 `mesh_ref` 与 topology_id,登记整数到 part_id 的映射;未知用 -1。ARCTIC 不同拓扑的资产分别绑定,不能共用未经转换的顶点标签。部件层级中 is_instance/has_model 等源属性保留,几何文件仍全部归 object。
### 5.5 segment:分割类别、编码与覆盖范围
每个发布选择一套任务使用的分割表示,不建立方法/标注集分支。没有分割就不创建 segment 目录,不为其他模态创建空的实体表。
| schema_id | 文件与数值语义 |
|---|---|
| segment/uint16_labels/v1 | mask.mkv;整数区域编号,通过 instances.jsonl 解释 |
| segment/instance_polygons/v1 | polygons.jsonl;实例多边形,可重叠;当前不支持孔洞拓扑 |
| segment/foreground_intensity/v1 | mask.mkv;0–255 前景强度,不是区域编号或经过校准的概率 |
#### 5.5.1 uint16 标签图与 instances.jsonl
组件声明 `segmentation_type=semantic/instance/part`;同一组件固定一种类型。`mask.mkv` 解码为 `[T,H,W] uint16`,schema `segment/uint16_labels/v1`,使用 `mkv/uint16_ffv1/v1`,FFV1 gray16le 无损;只有所有区域编码均 ≤255 时允许 gray8(pixel_format=gray),读取后转 uint16,数值不变。禁止调色板和有损编码。有效性 `[T]`,表示该帧有可用分割标注。数值 0 固定为 unassigned,65535 固定为 ignore,1–65534 为区域编码,不能直接等同 entity_id。
`instances.jsonl` 每帧一行,包含 `frame_index` 与 `labels`。每条标签包含 `mask_value`、`category_id`、`entity_id`、`part_id`;无意义或未知字段为 null。semantic 允许 entity_id=null;instance 必须引用 hand_left/hand_right 或登记的 object_id;part 还须关联登记部件。源实例 ID 和其他属性分别保存在 `source_instance_id`、`source_attributes`。mask 中每个非保留编码必须有且仅有一个映射。
FreiHAND 的试点按本任务需要,统一到手/背景类别,保留每个原生区域编码;不要求给原生细分区域猜测手指名称。需要细部件监督时,尚未核实的部件名称必须保持未知,不能因粗粒度手类别已核实便声称部件语义也已统一。
#### 5.5.2 重叠实例多边形
每发布选择一套任务使用的分割表示,不建立方法/标注集分支。VISOR 的实际试点存在重叠实例多边形,单层标签图不能无损表达。对此补充 `segment/instance_polygons/v1`:`segment/polygons.jsonl` 每帧包含 `frame_index` 和 `instances`,每实例包含 `mask_value` 与 `polygons`(列表,每个多边形为源图像像素坐标顶点序列,保留原始精度)。身份和类别仍由同一 `instances.jsonl` 映射,有效性仍为 `[T]`,通过 schema 区分物理编码。允许多实例重叠,不采用后画覆盖前画。消费者按需栅格化为独立实例二值 mask;不能声称合并的单层 mask 无损。
#### 5.5.3 灰度前景强度
ReInterHand 的官方渲染 mask 为双手合并的灰度前景掩码,实测存在 0–255 的中间值,不是左右手实例编号。登记 `segment/foreground_intensity/v1`:仍存 `segment/mask.mkv`,解码为 `[T,H,W] uint16`,使用 `mkv/uint16_ffv1/v1`,此类数据优先编码为 FFV1 gray8(pixel_format=gray),读取后转 uint16。有效值范围 0–255,归一化值为 `float32(value)/255`;0 为背景端点、255 为前景端点。组件声明 `foreground_category=hand`、`entity_id=null` 和双手合并语义,不使用区域编号映射。这里保留原始渲染 mask 强度,不把它称为经过校准的概率。若任务需要二值 mask,阈值化属于任务层派生操作,记录阈值;共享层不丢弃中间灰度。不同 schema 的数值含义不同,不能将该文件按整数类别图解码。
FreiHAND 训练集的 JPEG mask 使用 `segment/foreground_intensity/v1`,逐像素保留 JPEG 解码后的灰度,`entity_id=hand_right`。该 schema 不限定双手合并:单手或合并范围由 `entity_id` 与 `coverage` 明确声明。评估集整数区域图仍用 `segment/uint16_labels/v1`,两者不能仅凭文件名使用同一种解码语义。
#### 5.5.4 coverage 与有效性
`coverage.kind=full/selected_entities/partial/unknown`。full 指声明���标注范围完整;selected_entities 还应列出目标范围。无论哪种,0 本身不自动成为背景;背景要有明确类别映射,未标注区域不能用于构造负样本。保留源逐类/逐实例 exhaustive 信息,未知不可改写为完整。
三种表示的帧级有效性均为 `[T]`,表示该帧是否提供此分割标注;对应 valid_ref 在组件中登记,仍用小型 bool `.pt` 数组。栅格 mask 必须登记 storage,格式见 3.1.2,所有帧的整数编码或强度逐值完全相同。编码语义由 schema_id 决定,读取器不能仅依据 mask.mkv 文件名选择解码方式。
### 5.6 contact:接触、抓取、区域与距离
#### 5.6.1 relations.jsonl 与 relations_valid.pt
`annotation/contact/relations.jsonl`,schema contact/relations/v1,每帧一行含 frame_index、relations。每条记录含 relation_type(contact/grasp)、subject_id(手槽或登记实体)、object_id、status、source_locator、provenance。status 固定为 positive/negative/unknown/target_unannotated:positive 必须有可解析目标,negative 表示源明确否定该关系,unknown 为不确定,target_unannotated 为确有接触但目标未标注。非 positive 的 object_id 可 null,不能用 null 冒充“不接触”。稀疏源无记录的帧不自动补 negative。
VISOR 的对象 mask ID 必须先按同帧 source_instance_id 解析成 object_id;hand-not-in-contact、none-of-the-above、inconclusive 分别映射 negative、target_unannotated、unknown,保留原始字符串。Dex ycb_grasp_ind 通过 ycb_ids 映射到登记物体,以 relation_type=grasp 保存;不得当作逐顶点接触。
relations 组件的 valid_ref 指向 `relations_valid.pt [T] bool`,表示该帧是否有可用源关系标注。有效帧中可以存在 status=unknown 的明确不确定标注;无源标注的帧为 valid=false、relations=[]。组件仍声明 available/provenance/source_locator。
#### 5.6.2 实体对的顶点区域与距离
已发布的接触区域/距离按参与关系的 subject_id 与 object_id 组织,每对实体保留选定的一套结果,以精确 geometry_ref/topology_id 关联到手或物体/部件;不要求每套数据都有。顶点区域 schema contact/vertex_region/v1:bool `[T,V]` 加同形 valid;顶点距离 schema contact/vertex_distance/v1:float32 `[T,V]`、米、同形 valid,声明 source/target geometry_ref、distance_definition(signed/unsigned、测量到点集或表面等明确源定义)。geometry_ref 必须指向已登记 mesh 或由固定 MANO 模型配置确定的拓扑;拓扑/顶点数变化时按拓扑拆分片段。其他源区域表示只有在实际接入并登记 schema 后才可转换,不能随意栅格化宣称等价。
顶点区域/距离已有存储定义,但尚未完成真实输入试点;接入时必须提供源语义与几何验收证据,不因已经登记 schema 就视为通过。
## 附录:任务范围
不强制收录 2D bbox、完整高频动捕、动作程序、身体 SMPL-X、点云或网络特征。范围内的接触、visibility、选定手关键点、物体几何不能因不便处理而静默丢弃。分割采用的物理编码由第 5.5 节决定,存在重叠时不能以单层标签图声称无损。
不设置 entities_ref/segment/entities.json,不要求与 object_id 重复的 track_id。MediaPipe 不在当前关键点定义中;旧版本迁移必须保留可追溯关系,不能直接删表。手部共享表示不含独立 hand_mesh。
schema.json 是普通注册表,不是 JSON Schema 文档或可执行验收器;定义存在不代表真实数据已验证。验收须保留实测范围与未决项。
本存储约定只更新标准,不代表既有 FFV1/depth.pt 试点已迁移。新发布必须显式写 storage 配置;旧产物按其旧定义读取,不能只改文件后缀或版本标识伪装为合规。H2O/shared-v1.0/script/check_dexycb_projection.pyAdded+31
H2O/shared-v1.0/script/config.jsonAdded+24
H2O/shared-v1.0/script/convert_dexycb_v1.0.pyAdded+349
H2O/shared-v1.0/script/convert_h2o_v1.0.pyAdded+678
H2O/shared-v1.0/script/convert_hoi4d_v1.0.pyAdded+595
H2O/shared-v1.0/script/convert_visor_v1.0.pyAdded+271
H2O/shared-v1.0/script/provenance/operations/h2o-check-fallback.pyAdded+137
H2O/shared-v1.0/script/provenance/operations/h2o-finalize-quick-validation.pyAdded+39
H2O/shared-v1.0/script/provenance/operations/h2o-pipeline-bench-job.shAdded+25
H2O/shared-v1.0/script/provenance/operations/h2o-pipeline-benchmark.pyAdded+48
H2O/shared-v1.0/script/provenance/operations/h2o-pipeline-process-benchmark.pyAdded+48
H2O/shared-v1.0/script/provenance/operations/h2o-prepare-pipeline-bench.pyAdded+28
H2O/shared-v1.0/script/provenance/operations/h2o-prepare-process-full.pyAdded+45
H2O/shared-v1.0/script/provenance/operations/h2o-process-final-tests.logAdded+39
H2O/shared-v1.0/script/provenance/operations/h2o-quick-validation.pyAdded+161
H2O/shared-v1.0/script/provenance/operations/h2o-shared-final-tests.logAdded+1
H2O/shared-v1.0/script/provenance/operations/h2o-switch-process-full.shAdded+12
H2O/shared-v1.0/script/provenance/operations/watch-steady-cpu.pyAdded+38
H2O/shared-v1.0/script/provenance/previous-run/docs/CONTRACT.mdAdded+457
H2O/shared-v1.0/script/provenance/previous-run/docs/h2o-RAW_TO_SHARED.mdAdded+48
H2O/shared-v1.0/script/provenance/previous-run/docs/schema.jsonAdded+869
H2O/shared-v1.0/script/provenance/previous-run/full.logAdded+61
H2O/shared-v1.0/script/provenance/previous-run/full.statusAdded+7
H2O/shared-v1.0/script/provenance/previous-run/run-full.shAdded+26
H2O/shared-v1.0/script/provenance/previous-run/script/check_dexycb_projection.pyAdded+31
H2O/shared-v1.0/script/provenance/previous-run/script/config.jsonAdded+17
H2O/shared-v1.0/script/provenance/previous-run/script/convert_dexycb_v1.0.pyAdded+349
H2O/shared-v1.0/script/provenance/previous-run/script/convert_h2o_v1.0.pyAdded+545
H2O/shared-v1.0/script/provenance/previous-run/script/convert_hoi4d_v1.0.pyAdded+595
H2O/shared-v1.0/script/provenance/previous-run/script/convert_visor_v1.0.pyAdded+271
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/h2o-benchmark-decode.pyAdded+74
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/h2o-prepare-d10.pyAdded+55
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/h2o-switch-d10.shAdded+16
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/worker4-encode10-decode10-depth4-regression.logAdded+37
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/operations/workspace-regression.logAdded+37
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/docs/CONTRACT.mdAdded+457
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/docs/h2o-RAW_TO_SHARED.mdAdded+30
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/docs/schema.jsonAdded+869
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/full.logAdded+8
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/full.statusAdded+7
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/run-full.shAdded+26
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/check_dexycb_projection.pyAdded+31
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/config.jsonAdded+15
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_dexycb_v1.0.pyAdded+349
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_h2o_v1.0.pyAdded+527
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_hoi4d_v1.0.pyAdded+595
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/convert_visor_v1.0.pyAdded+271
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/operations/prepare-w4-c10.pyAdded+52
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/operations/retry-w4-c10.shAdded+11
H2O/shared-v1.0/script/provenance/previous-run/script/provenance/previous-run/script/provenance/r1/docs/CONTRACT.mdAdded+457