Simplify RHD shared-v1.0 scripts
Browse files- RHD/shared-v1.0/doc/RAW_MAPPING.md +2 -0
- RHD/shared-v1.0/script/README.md +18 -0
- RHD/shared-v1.0/script/convert_freihand_lossless.py +0 -123
- RHD/shared-v1.0/script/{convert_rhd_full.py → convert_rhd.py} +20 -20
- RHD/shared-v1.0/script/pilot_build.py +0 -209
- RHD/shared-v1.0/script/pilot_fetch.py +0 -63
- RHD/shared-v1.0/script/pilot_mano.py +0 -87
- RHD/shared-v1.0/script/pilot_rhd_lossless.py +0 -79
- RHD/shared-v1.0/script/{review_rhd_full_random.py → render_full_random_review.py} +8 -12
- RHD/shared-v1.0/script/rhd_common.py +135 -0
- RHD/shared-v1.0/script/sequence_pilot_common.py +0 -53
- RHD/shared-v1.0/script/sequence_pilot_images.py +0 -53
- RHD/shared-v1.0/script/validate_rhd.py +46 -0
RHD/shared-v1.0/doc/RAW_MAPPING.md
CHANGED
|
@@ -13,3 +13,5 @@
|
|
| 13 |
| 原图编号 | camera/frames.jsonl | 稳定 sample_id、原 ZIP 成员和标注索引;image 类型,无真实时间序列 |
|
| 14 |
|
| 15 |
没有源 MANO、物体、接触或相机外参就缺省,不补造。RHD 21 点只统一其原生体系顺序,不宣称与 MANO 关节位置等价。完整 ZIP 原样保留并随发布上传;运行日志只存 tmp。24 张试点已通过人工核验;全量按每片最多 512 张,训练/评估分开、尾片不补帧。预计 87 个分片;完成后另做全量随机抽查。
|
|
|
|
|
|
|
|
|
| 13 |
| 原图编号 | camera/frames.jsonl | 稳定 sample_id、原 ZIP 成员和标注索引;image 类型,无真实时间序列 |
|
| 14 |
|
| 15 |
没有源 MANO、物体、接触或相机外参就缺省,不补造。RHD 21 点只统一其原生体系顺序,不宣称与 MANO 关节位置等价。完整 ZIP 原样保留并随发布上传;运行日志只存 tmp。24 张试点已通过人工核验;全量按每片最多 512 张,训练/评估分开、尾片不补帧。预计 87 个分片;完成后另做全量随机抽查。
|
| 16 |
+
|
| 17 |
+
正式入口为 `script/convert_rhd.py`、`script/validate_rhd.py` 和 `script/render_full_random_review.py`。三者均无必填命令行参数,并从自身位置定位本数据集的 `raw/`、`shared-v1.0/` 与 `tmp/`;公共实现位于 `script/rhd_common.py`。完整运行方式和依赖见 `script/README.md`。脚本不会删除或改写 raw,也不会自动上传或把自动检查写成人工通过。
|
RHD/shared-v1.0/script/README.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# RHD shared-v1.0 脚本
|
| 2 |
+
|
| 3 |
+
本目录只服务于相邻的 `shared-v1.0`。脚本从自身位置定位 RHD 的 `raw/`、`shared-v1.0/`、`doc/` 和 `tmp/`,不要求数据集路径、release、split 或分片大小参数。
|
| 4 |
+
|
| 5 |
+
```bash
|
| 6 |
+
python script/convert_rhd.py
|
| 7 |
+
python script/validate_rhd.py
|
| 8 |
+
python script/render_full_random_review.py
|
| 9 |
+
```
|
| 10 |
+
|
| 11 |
+
三个入口均无必填参数,`--help` 仅显示帮助。
|
| 12 |
+
|
| 13 |
+
- `convert_rhd.py`:读取官方 `RHD_v1-1.zip`,按 training/evaluation 分开写入固定的每片最多 512 张布局;完整分片跳过,不完整或不兼容分片停止运行。
|
| 14 |
+
- `validate_rhd.py`:按 `doc/schema.json` 检查全部 43,986 张的路径、组件、张量和媒体登记,并生成当前发布树的 SHA256 内容指纹。指纹不能单独证明官方源正确、转换语义正确或视觉质量合格。
|
| 15 |
+
- `render_full_random_review.py`:固定种子从 training 和 evaluation 各抽 12 张,直接读取全量产物并与 raw 的 RGB、mask、depth 对照,生成 `doc/validation/full_random/`。
|
| 16 |
+
- `rhd_common.py`:三个入口共用的路径、受限 pickle、JSON/张量、FFmpeg 和视图结构实现;不是单独入口。
|
| 17 |
+
|
| 18 |
+
环境需要 Python 3、NumPy、PyTorch、Pillow、OpenCV 和 `imageio-ffmpeg`。RHD 没有原生 MANO,因此这里没有 MANO 依赖或 FreiHAND 代码。脚本不会删除或改写 raw,不上传数据,也不会把自动检查写成人工通过。
|
RHD/shared-v1.0/script/convert_freihand_lossless.py
DELETED
|
@@ -1,123 +0,0 @@
|
|
| 1 |
-
"""FreiHAND complete ZIP -> lossless-video v1.0; never deletes raw.
|
| 2 |
-
--output is the hand-datasets root. --max-batches is for converter validation only.
|
| 3 |
-
"""
|
| 4 |
-
from sequence_pilot_images import *
|
| 5 |
-
import sequence_pilot_common as common
|
| 6 |
-
import hashlib
|
| 7 |
-
|
| 8 |
-
BaseView=View
|
| 9 |
-
class View(BaseView):
|
| 10 |
-
def finish(self):
|
| 11 |
-
lines(self.p/'camera/frames.jsonl',self.frames);save(self.p/'metainfo.json',self.m)
|
| 12 |
-
save(self.root.parent/'tmp/production/checks'/f'{self.m["sequence_id"]}__{self.m["camera_id"]}.checks.json',{'checks':self.checks,'frames':self.T,'input':self.source})
|
| 13 |
-
print('Converted',self.m['dataset_id'],self.m['sequence_id'],self.m['camera_id'],self.T,flush=True)
|
| 14 |
-
|
| 15 |
-
def ff(args,data=None):
|
| 16 |
-
r=subprocess.run([FF,'-v','error','-y',*args],input=data,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
| 17 |
-
if r.returncode: raise RuntimeError(r.stderr.decode(errors='replace'))
|
| 18 |
-
return r.stdout
|
| 19 |
-
|
| 20 |
-
def storage(profile,codec,pix,size,lossy,params):
|
| 21 |
-
return dict(profile=profile,codec=codec,pixel_format=pix,encoded_size=size,source_lossy=lossy,
|
| 22 |
-
decoder=ff(['-version']).decode().splitlines()[0],encoder_parameters=params)
|
| 23 |
-
|
| 24 |
-
def main():
|
| 25 |
-
ap=argparse.ArgumentParser();ap.add_argument('--output',type=Path,required=True)
|
| 26 |
-
ap.add_argument('--source',type=Path,default=ROOT/'FreiHAND/raw/data')
|
| 27 |
-
ap.add_argument('--batch-size',type=int,default=4096);ap.add_argument('--max-batches',type=int);ap.add_argument('--split',choices=['all','training','evaluation'],default='all');ap.add_argument('--sample-indices',help='Comma-separated source RGB indices for local human review');ap.add_argument('--human-reviewed',action='store_true',help='Use only after explicit user approval of local review')
|
| 28 |
-
args=ap.parse_args();assert args.batch_size>0
|
| 29 |
-
if not args.sample_indices and not args.max_batches and not args.human_reviewed:ap.error('Full conversion requires explicit human review approval first (--human-reviewed)')
|
| 30 |
-
common.ROOT=args.output;common.RELEASE='shared-v1.0'
|
| 31 |
-
# Do not mix a new sharding layout with existing production intermediates.
|
| 32 |
-
if not args.sample_indices:
|
| 33 |
-
existing=args.output/'FreiHAND'/common.RELEASE/'data'
|
| 34 |
-
for directory in existing.glob('*'):
|
| 35 |
-
if not directory.is_dir():continue
|
| 36 |
-
mp=directory/'camera/metainfo.json'
|
| 37 |
-
if not mp.exists():raise RuntimeError(f'Incomplete existing shard must be handled before rerun: {directory}')
|
| 38 |
-
previous=load(mp);start_index=int(directory.name.rsplit('_',1)[1])
|
| 39 |
-
total=130240 if directory.name.startswith('training_') else 3960
|
| 40 |
-
expected=min(args.batch_size,total-start_index)
|
| 41 |
-
if start_index%args.batch_size or previous['num_frames']!=expected:
|
| 42 |
-
raise RuntimeError(f'Existing shard layout differs from requested {args.batch_size}; archive/rebuild old intermediates before rerun: {directory}')
|
| 43 |
-
torch.set_num_threads(4)
|
| 44 |
-
model=Mano('right');count=0;summary=[]
|
| 45 |
-
for split,filename in [('training','FreiHAND_pub_v2.zip'),('evaluation','FreiHAND_pub_v2_eval.zip')]:
|
| 46 |
-
if args.split!='all' and args.split!=split:continue
|
| 47 |
-
with zipfile.ZipFile(args.source/filename) as z:
|
| 48 |
-
ks=np.asarray(json.loads(z.read(split+'_K.json')));xyz=np.asarray(json.loads(z.read(split+'_xyz.json')))
|
| 49 |
-
theta=np.asarray(json.loads(z.read(split+'_mano.json'))).reshape(-1,61)
|
| 50 |
-
n=len(ks);assert len(xyz)==len(theta)==n
|
| 51 |
-
rgbnames=sorted(s for s in z.namelist() if s.startswith(split+'/rgb/') and s.endswith('.jpg'))
|
| 52 |
-
assert len(rgbnames)==n*(4 if split=='training' else 1)
|
| 53 |
-
if args.sample_indices:
|
| 54 |
-
chosen={int(x) for x in args.sample_indices.split(',')};rgbnames=[s for s in rgbnames if int(Path(s).stem) in chosen]
|
| 55 |
-
assert rgbnames,'No selected source images'
|
| 56 |
-
for start in range(0,len(rgbnames),args.batch_size):
|
| 57 |
-
names=rgbnames[start:start+args.batch_size];ids=[int(Path(s).stem) for s in names];ix=np.asarray(ids)%n;t=len(ids)
|
| 58 |
-
seq=f'{split}_{start:08d}';source={'archive':'raw/data/'+filename}
|
| 59 |
-
v=View('FreiHAND',seq,'camera',ids,[224,224],source,kind='image',split='train' if split=='training' else 'test')
|
| 60 |
-
v.m['split_scheme']='FreiHAND_official_train_evaluation'
|
| 61 |
-
v.m['split_source_locator']={'archive':'raw/data/'+filename,'member_prefix':split+'/'}
|
| 62 |
-
v.m['schema_version']='hand-warehouse/1.0';v.m['storage_revision']='lossless-video-2026-09-18'
|
| 63 |
-
v.m['sampling']['type']='independent' if t>1 else 'single'
|
| 64 |
-
v.m['sampling']['shard_max_images']=args.batch_size
|
| 65 |
-
v.m['sampling']['selection']='all released RGB images, sorted by source RGB index; all background variants retained'
|
| 66 |
-
for f,i,base,name in zip(v.frames,ids,ix,names):
|
| 67 |
-
f.update(sample_id=f'FreiHAND/{split}/{i:08d}',image_variant={'base_sample_id':int(base),'variant_index':int(i//n)})
|
| 68 |
-
f['source_locator'].update(member=name,annotation_index=int(base))
|
| 69 |
-
jpg=b''.join(z.read(s) for s in names);path=v.p/'observation/rgb.mkv';path.parent.mkdir(parents=True,exist_ok=True)
|
| 70 |
-
ff(['-f','image2pipe','-framerate','1','-c:v','mjpeg','-i','pipe:0','-c:v','copy',str(path)],jpg)
|
| 71 |
-
assert ff(['-i',str(path),'-c:v','copy','-f','image2pipe','pipe:1'])==jpg
|
| 72 |
-
decoded=ff(['-f','image2pipe','-c:v','mjpeg','-i','pipe:0','-f','rawvideo','-pix_fmt','rgb24','pipe:1'],jpg)
|
| 73 |
-
assert len(decoded)==t*224*224*3
|
| 74 |
-
assert ff(['-i',str(path),'-f','rawvideo','-pix_fmt','rgb24','pipe:1'])==decoded
|
| 75 |
-
# FFmpeg reports the actual source pixel format without printing image data.
|
| 76 |
-
info=subprocess.run([FF,'-hide_banner','-i',str(path)],capture_output=True).stderr.decode(errors='replace')
|
| 77 |
-
import re
|
| 78 |
-
pix=re.search(r'Video: mjpeg[^\n]*?\b(yuvj?\d+p)\b',info)
|
| 79 |
-
if not pix: raise RuntimeError('Unrecognized JPEG pixel format: '+info)
|
| 80 |
-
v.add('rgb','observation/rgb.mkv','rgb/uint8/v1',['T','height','width','channel'],np.ones(t,bool),
|
| 81 |
-
storage=storage('mkv/mjpeg_copy/v1','mjpeg',pix.group(1),[224,224],True,{'mode':'stream_copy'}),storage_fps=1,timebase_role='index_only')
|
| 82 |
-
v.checks.append({'test':'all_rgb_packets_and_decoded_pixels_exact','frames':t})
|
| 83 |
-
v.intrinsic(ks[ix]);v.m['components']['intrinsic']['source_locator'].update(member=split+'_K.json',index_ref='camera/frames.jsonl:source_locator.annotation_index')
|
| 84 |
-
kp=np.full((t,2,21,3),np.nan);kp[:,1]=xyz[ix];valid=np.zeros((t,2,21),bool);valid[:,1]=True
|
| 85 |
-
v.array('keypoints_xyz','annotation/keypoints/xyz.pt','keypoints/xyz/v1',kp,valid,['T','hand','joint','coordinate'],unit='m',coordinate_frame='camera',keypoint_schema='mano21/v1')
|
| 86 |
-
v.m['components']['keypoints_xyz']['source_locator'].update(member=split+'_xyz.json',index_ref='camera/frames.jsonl:source_locator.annotation_index')
|
| 87 |
-
a=theta[ix];pose=a[:,:48].copy();pose[:,3:]+=model.data['hands_mean'];beta=a[:,48:58]
|
| 88 |
-
verts,joints,_=model.geometry(pose,beta)
|
| 89 |
-
focal=(ks[ix,0,0]+ks[ix,1,1])/2
|
| 90 |
-
root=np.concatenate([a[:,58:60]-ks[ix,:2,2],focal[:,None]],axis=1)/a[:,60,None]
|
| 91 |
-
translation=root-joints[:,9];motion=np.full((t,2,61),np.nan);motion[:,1]=np.concatenate([pose,beta,translation],axis=1)
|
| 92 |
-
valid=np.zeros((t,2),bool);valid[:,1]=True
|
| 93 |
-
v.array('mano','annotation/mano/motion.pt','mano/axis_angle61/v1',motion,valid,['T','hand','parameter'],unit='m',coordinate_frame='camera',angle_unit='rad',model_profile={'version':'MANO-v1.2','flat_hand_mean':True,'left_shapedirs_fix':False},method='Add MANO nonflat mean; recover source camera root from uv/scale; subtract posed middle MCP. No new fitting.')
|
| 94 |
-
v.m['components']['mano']['source_locator'].update(member=split+'_mano.json',index_ref='camera/frames.jsonl:source_locator.annotation_index')
|
| 95 |
-
_,restored,_=model.geometry(motion[:,1,:48],motion[:,1,48:58],motion[:,1,58:])
|
| 96 |
-
assert np.max(np.abs(restored[:,9]-root))<2e-6
|
| 97 |
-
masks=[];records=[]
|
| 98 |
-
for frame,(i,base) in enumerate(zip(ids,ix)):
|
| 99 |
-
member=f'training/mask/{base:08d}.jpg' if split=='training' else f'evaluation/segmap/{i:08d}.png'
|
| 100 |
-
arr=np.asarray(Image.open(io.BytesIO(z.read(member))))
|
| 101 |
-
if split=='training':
|
| 102 |
-
assert arr.shape==(224,224,3) and np.array_equal(arr[:,:,0],arr[:,:,1]) and np.array_equal(arr[:,:,0],arr[:,:,2])
|
| 103 |
-
arr=arr[:,:,0].astype(np.uint16)
|
| 104 |
-
else:
|
| 105 |
-
assert arr.shape==(224,224)
|
| 106 |
-
arr=arr.astype(np.uint16);arr[arr==0]=65534
|
| 107 |
-
records.append({'frame_index':frame,'labels':[dict(mask_value=int(c),category_id='background' if c==65534 else 'hand',entity_id=None if c==65534 else 'hand_right',part_id=None,source_instance_id=0 if c==65534 else int(c)) for c in np.unique(arr)]})
|
| 108 |
-
masks.append(arr)
|
| 109 |
-
pix='gray' if split=='training' else 'gray16le';raw=np.asarray(masks,dtype=np.uint8 if pix=='gray' else '<u2').tobytes();path=v.p/'annotation/segment/mask.mkv';path.parent.mkdir(parents=True,exist_ok=True)
|
| 110 |
-
ff(['-f','rawvideo','-pixel_format',pix,'-video_size','224x224','-framerate','1','-i','pipe:0','-c:v','ffv1','-level','3',str(path)],raw)
|
| 111 |
-
assert ff(['-i',str(path),'-f','rawvideo','-pix_fmt',pix,'pipe:1'])==raw
|
| 112 |
-
schema='segment/foreground_intensity/v1' if split=='training' else 'segment/uint16_labels/v1'
|
| 113 |
-
v.add('segment','annotation/segment/mask.mkv',schema,['T','height','width'],np.ones(t,bool),storage=storage('mkv/uint16_ffv1/v1','ffv1',pix,[224,224],split=='training',{'level':3}),storage_fps=1,timebase_role='index_only',coverage={'kind':'selected_entities','entities':['hand_right']})
|
| 114 |
-
seg=v.m['components']['segment'];seg['source_locator'].update(member_pattern='training/mask/{annotation_index:08d}.jpg' if split=='training' else 'evaluation/segmap/{source_frame_id:08d}.png')
|
| 115 |
-
if split=='training':seg.update(segmentation_type='semantic',value_range=[0,255],normalization_scale=1/255,foreground_category='hand',entity_id='hand_right')
|
| 116 |
-
else:
|
| 117 |
-
seg.update(segmentation_type='semantic',mapping_ref='annotation/segment/instances.jsonl');lines(v.p/'annotation/segment/instances.jsonl',records)
|
| 118 |
-
v.checks.extend([{'test':'all_mask_values_exact','frames':t},{'test':'MANO_middle_MCP_root_recovery','max_m':float(np.max(np.abs(restored[:,9]-root)))}])
|
| 119 |
-
v.finish();summary.append({'sequence':seq,'frames':t});count+=1
|
| 120 |
-
save(v.root.parent/'tmp/production/conversion_progress.json',{'complete':False,'batches':summary})
|
| 121 |
-
if args.max_batches and count>=args.max_batches:return
|
| 122 |
-
save(v.root.parent/'tmp/production/conversion_progress.json',{'complete':args.split=='all' and not args.sample_indices,'split_selection':args.split,'batches':summary})
|
| 123 |
-
if __name__=='__main__':main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
RHD/shared-v1.0/script/{convert_rhd_full.py → convert_rhd.py}
RENAMED
|
@@ -1,9 +1,7 @@
|
|
| 1 |
-
"""
|
| 2 |
-
from
|
| 3 |
-
from
|
| 4 |
-
import
|
| 5 |
-
import random,html,hashlib
|
| 6 |
-
BASE=Path('E:/hand-datasets/RHD');RELEASE='shared-v1.0'
|
| 7 |
|
| 8 |
def media(v,name,path,raw,pix,size,profile,codec='ffv1',options=None):
|
| 9 |
dst=v.p/path;dst.parent.mkdir(parents=True,exist_ok=True);options=options or ['-level','3']
|
|
@@ -14,18 +12,21 @@ def media(v,name,path,raw,pix,size,profile,codec='ffv1',options=None):
|
|
| 14 |
return storage(profile,codec,actual_pix,size,False,options),restored
|
| 15 |
|
| 16 |
def main():
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
order=load(WORK/'distribution/hand-warehouse-1.0/schema.json')['keypoints']['rhd21/v1']['source_index_map_per_hand'];reports=[]
|
| 22 |
-
with zipfile.ZipFile(BASE/'raw/data/RHD_v1-1.zip') as z:
|
| 23 |
for split,total in [('training',41258),('evaluation',2728)]:
|
| 24 |
member=next(n for n in z.namelist() if n.endswith(f'{split}/anno_{split}.pickle'));prefix=member.rsplit('/',1)[0]
|
| 25 |
anno=Restricted(io.BytesIO(z.read(member)),encoding='latin1').load();all_ids=sorted(anno);assert len(all_ids)==total
|
| 26 |
for offset in range(0,total,512):
|
| 27 |
ids=all_ids[offset:offset+512];t=len(ids)
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
v.m.update(schema_version='hand-warehouse/1.0',storage_revision='lossless-video-2026-09-18',split_scheme='RHD_official_training_evaluation',split_source_locator={'archive':'raw/data/RHD_v1-1.zip','member_prefix':prefix},sample_type='image')
|
| 30 |
v.m['sampling'].update(type='independent',selection='all source independent images sorted by source ID',shard_max_images=512)
|
| 31 |
for row,i in zip(v.frames,ids):row.update(sample_id=f'RHD/{split}/{i:05d}');row['source_locator'].update(annotation_index=i,member=f'{prefix}/color/{i:05d}.png')
|
|
@@ -57,11 +58,10 @@ def main():
|
|
| 57 |
xyz=torch.load(v.p/'annotation/keypoints/xyz.pt',weights_only=True).numpy();uv=torch.load(v.p/'annotation/keypoints/uv.pt',weights_only=True).numpy();K=torch.load(v.p/'camera/intrinsic.pt',weights_only=True).numpy()
|
| 58 |
projected=xyz@K[:,None].transpose(0,1,3,2);projected=projected[...,:2]/projected[...,2:];errors=np.linalg.norm(projected-uv,axis=-1)
|
| 59 |
v.checks.append({'test':'native_xyz_K_projection_vs_uv','max_pixel':float(errors.max()),'median_pixel':float(np.median(errors))});v.finish()
|
| 60 |
-
reports.append({'split':split,'
|
| 61 |
-
save(
|
| 62 |
-
save(
|
| 63 |
-
assert sum(
|
| 64 |
-
save(
|
| 65 |
-
|
| 66 |
-
print('RHD full conversion and random report complete; awaiting human review; no upload.',flush=True)
|
| 67 |
if __name__=='__main__':main()
|
|
|
|
| 1 |
+
"""Convert the official RHD ZIP into the adjacent shared-v1.0 release."""
|
| 2 |
+
from rhd_common import *
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import argparse, io, zipfile
|
|
|
|
|
|
|
| 5 |
|
| 6 |
def media(v,name,path,raw,pix,size,profile,codec='ffv1',options=None):
|
| 7 |
dst=v.p/path;dst.parent.mkdir(parents=True,exist_ok=True);options=options or ['-level','3']
|
|
|
|
| 12 |
return storage(profile,codec,actual_pix,size,False,options),restored
|
| 13 |
|
| 14 |
def main():
|
| 15 |
+
argparse.ArgumentParser(description='Convert RHD raw into the adjacent shared-v1.0 release.').parse_args()
|
| 16 |
+
torch.set_num_threads(4);root=RELEASE_ROOT
|
| 17 |
+
order=load(root/'doc/schema.json')['keypoints']['rhd21/v1']['source_index_map_per_hand'];reports=[]
|
| 18 |
+
with zipfile.ZipFile(RAW_ROOT/'RHD_v1-1.zip') as z:
|
|
|
|
|
|
|
| 19 |
for split,total in [('training',41258),('evaluation',2728)]:
|
| 20 |
member=next(n for n in z.namelist() if n.endswith(f'{split}/anno_{split}.pickle'));prefix=member.rsplit('/',1)[0]
|
| 21 |
anno=Restricted(io.BytesIO(z.read(member)),encoding='latin1').load();all_ids=sorted(anno);assert len(all_ids)==total
|
| 22 |
for offset in range(0,total,512):
|
| 23 |
ids=all_ids[offset:offset+512];t=len(ids)
|
| 24 |
+
sequence=f'{split}_{offset:08d}';complete=root/'data'/sequence/'camera/metainfo.json'
|
| 25 |
+
if complete.is_file():
|
| 26 |
+
meta=load(complete);required=['observation/rgb.mkv','observation/depth.mkv','observation/depth_valid.mkv','annotation/segment/mask.mkv','annotation/keypoints/xyz.pt','annotation/keypoints/uv.pt','camera/intrinsic.pt','camera/frames.jsonl']
|
| 27 |
+
if meta.get('num_frames')!=t or not all((complete.parent/path).is_file() for path in required):raise RuntimeError(f'Existing shard is incomplete: {complete.parent}')
|
| 28 |
+
reports.append({'split':split,'frames':t,'sequence':sequence,'status':'already_complete'});continue
|
| 29 |
+
v=View('RHD',sequence,'camera',ids,[320,320],{'archive':'raw/data/RHD_v1-1.zip','annotation':member},kind='image',split='train' if split=='training' else 'test')
|
| 30 |
v.m.update(schema_version='hand-warehouse/1.0',storage_revision='lossless-video-2026-09-18',split_scheme='RHD_official_training_evaluation',split_source_locator={'archive':'raw/data/RHD_v1-1.zip','member_prefix':prefix},sample_type='image')
|
| 31 |
v.m['sampling'].update(type='independent',selection='all source independent images sorted by source ID',shard_max_images=512)
|
| 32 |
for row,i in zip(v.frames,ids):row.update(sample_id=f'RHD/{split}/{i:05d}');row['source_locator'].update(annotation_index=i,member=f'{prefix}/color/{i:05d}.png')
|
|
|
|
| 58 |
xyz=torch.load(v.p/'annotation/keypoints/xyz.pt',weights_only=True).numpy();uv=torch.load(v.p/'annotation/keypoints/uv.pt',weights_only=True).numpy();K=torch.load(v.p/'camera/intrinsic.pt',weights_only=True).numpy()
|
| 59 |
projected=xyz@K[:,None].transpose(0,1,3,2);projected=projected[...,:2]/projected[...,2:];errors=np.linalg.norm(projected-uv,axis=-1)
|
| 60 |
v.checks.append({'test':'native_xyz_K_projection_vs_uv','max_pixel':float(errors.max()),'median_pixel':float(np.median(errors))});v.finish()
|
| 61 |
+
reports.append({'split':split,'frames':t,'sequence':sequence,'status':'converted','rgb_candidate_sizes':sizes,'selected_rgb_profile':rgbstore['profile'],'max_projection_difference_pixels':float(errors.max()),'depth_float32_bits_exact':True,'media_roundtrip_exact':True})
|
| 62 |
+
save(TMP_ROOT/'conversion_progress.json',{'complete':False,'images':sum(r['frames'] for r in reports),'shards':len(reports)})
|
| 63 |
+
save(TMP_ROOT/'conversion_progress.json',{'complete':True,'images':sum(r['frames'] for r in reports),'shards':len(reports)})
|
| 64 |
+
assert sum(r['frames'] for r in reports)==43986
|
| 65 |
+
save(TMP_ROOT/'full_checks.json',{'passed':True,'shards':reports})
|
| 66 |
+
print('RHD conversion complete. Run validate_rhd.py, then render_full_random_review.py.',flush=True)
|
|
|
|
| 67 |
if __name__=='__main__':main()
|
RHD/shared-v1.0/script/pilot_build.py
DELETED
|
@@ -1,209 +0,0 @@
|
|
| 1 |
-
"""Small, source-traceable dataset pilot. Originals are copied, never edited.
|
| 2 |
-
|
| 3 |
-
Run with Python + numpy + torch + Pillow + opencv and imageio-ffmpeg.
|
| 4 |
-
Optional runtime installed at tmp/pilot-runtime. Outputs: hand-datasets/.
|
| 5 |
-
"""
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
import argparse, codecs, collections, csv, io, json, pickle, shutil, subprocess, sys, zipfile
|
| 8 |
-
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tmp/pilot-runtime'))
|
| 9 |
-
import numpy as np
|
| 10 |
-
import torch
|
| 11 |
-
from PIL import Image, ImageDraw
|
| 12 |
-
import cv2
|
| 13 |
-
from pilot_fetch import ROOT, sha
|
| 14 |
-
|
| 15 |
-
WORK=ROOT.parent
|
| 16 |
-
OLD=WORK/'datasets'
|
| 17 |
-
sys.path.insert(0,str(WORK/'tmp/pilot-runtime'))
|
| 18 |
-
import imageio_ffmpeg
|
| 19 |
-
FF=imageio_ffmpeg.get_ffmpeg_exe()
|
| 20 |
-
N=16
|
| 21 |
-
|
| 22 |
-
def save(p,value):
|
| 23 |
-
p.parent.mkdir(parents=True,exist_ok=True)
|
| 24 |
-
p.write_text(json.dumps(value,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
|
| 25 |
-
def lines(p,rows):
|
| 26 |
-
p.parent.mkdir(parents=True,exist_ok=True)
|
| 27 |
-
p.write_text(''.join(json.dumps(x,ensure_ascii=False,allow_nan=False)+'\n' for x in rows),encoding='utf-8')
|
| 28 |
-
def tensor(p,a):
|
| 29 |
-
p.parent.mkdir(parents=True,exist_ok=True);torch.save(torch.as_tensor(np.asarray(a).copy()),p)
|
| 30 |
-
def load(p):return json.loads(p.read_text(encoding='utf-8'))
|
| 31 |
-
|
| 32 |
-
class Restricted(pickle.Unpickler):
|
| 33 |
-
def find_class(self,module,name):
|
| 34 |
-
allowed={('numpy.core.multiarray','_reconstruct'):np.core.multiarray._reconstruct,
|
| 35 |
-
('numpy._core.multiarray','_reconstruct'):np.core.multiarray._reconstruct,
|
| 36 |
-
('numpy','ndarray'):np.ndarray,('numpy','dtype'):np.dtype,
|
| 37 |
-
('numpy.core.numeric','_frombuffer'):np.core.numeric._frombuffer,
|
| 38 |
-
('numpy._core.numeric','_frombuffer'):np.core.numeric._frombuffer,
|
| 39 |
-
('_codecs','encode'):codecs.encode,
|
| 40 |
-
('collections','OrderedDict'):collections.OrderedDict,
|
| 41 |
-
('torch._utils','_rebuild_tensor_v2'):torch._utils._rebuild_tensor_v2,
|
| 42 |
-
('torch.storage','_load_from_bytes'):lambda b:torch.load(io.BytesIO(b),map_location='cpu',weights_only=True)}
|
| 43 |
-
if (module,name) not in allowed:raise pickle.UnpicklingError(f'Unsupported class: {module}.{name}')
|
| 44 |
-
return allowed[(module,name)]
|
| 45 |
-
def read_pickle(p):
|
| 46 |
-
with p.open('rb') as f:return Restricted(f,encoding='latin1').load()
|
| 47 |
-
|
| 48 |
-
class Build:
|
| 49 |
-
def __init__(self,name):
|
| 50 |
-
self.name=name;self.base=ROOT/name;self.out=self.base/'pilot-v0';self.refs=[];self.views=[];self.checks=[]
|
| 51 |
-
for p in ['raw/doc','raw/script','raw/data','pilot-v0/doc','pilot-v0/script','pilot-v0/data']:(self.base/p).mkdir(parents=True,exist_ok=True)
|
| 52 |
-
def copy(self,src):
|
| 53 |
-
rel=src.relative_to(OLD/self.name);dst=self.base/'raw/data/local_subset'/rel
|
| 54 |
-
dst.parent.mkdir(parents=True,exist_ok=True)
|
| 55 |
-
if not dst.exists():shutil.copyfile(src,dst)
|
| 56 |
-
source_hash=sha(src);assert sha(dst)==source_hash
|
| 57 |
-
self.refs.append({'source':str(src),'stored':str(dst.relative_to(self.base)), 'sha256':source_hash,'bytes':src.stat().st_size,'kind':'historical_extracted_file_copy','official_archive_verified':False})
|
| 58 |
-
return dst
|
| 59 |
-
def view(self,seq,cam,ids,**meta):
|
| 60 |
-
p=self.out/'data'/seq/cam;p.mkdir(parents=True,exist_ok=True)
|
| 61 |
-
m={'schema_version':'pilot-v0','dataset':self.name,'sequence_id':seq,'camera_id':cam,'num_frames':len(ids),'fps':None,'split':None,'view_type':None,'time_semantics':'unknown','missing_modalities':{},**meta}
|
| 62 |
-
self.views.append((p,m))
|
| 63 |
-
lines(p/'frames.jsonl',[{'frame_index':i,'source_frame_id':str(s),'timestamp_ns':None,'clock_domain':None} for i,s in enumerate(ids)])
|
| 64 |
-
return p,m
|
| 65 |
-
def video(self,p,arrays):
|
| 66 |
-
a=np.stack(arrays);h,w=a.shape[1:3]
|
| 67 |
-
pixel='rgb24' if a.ndim==4 else ('gray16le' if a.dtype==np.uint16 else 'gray')
|
| 68 |
-
if pixel=='gray16le':a=a.astype('<u2')
|
| 69 |
-
a=np.ascontiguousarray(a);p.parent.mkdir(parents=True,exist_ok=True)
|
| 70 |
-
command=[FF,'-hide_banner','-loglevel','error','-y','-f','rawvideo','-pixel_format',pixel,'-video_size',f'{w}x{h}','-framerate','1','-i','pipe:0','-an','-c:v','ffv1','-level','3','-g','1',str(p)]
|
| 71 |
-
subprocess.run(command,input=a.tobytes(),check=True,capture_output=True)
|
| 72 |
-
decoded=subprocess.run([FF,'-v','error','-i',str(p),'-f','rawvideo','-pix_fmt',pixel,'pipe:1'],check=True,capture_output=True).stdout
|
| 73 |
-
assert decoded==a.tobytes(),f'Lossless roundtrip failed: {p}'
|
| 74 |
-
self.checks.append({'file':str(p.relative_to(self.out)),'test':'decode_all_frames_pixel_exact','passed':True,'frames':len(a),'dtype':str(a.dtype),'shape':list(a.shape)})
|
| 75 |
-
return {'codec':'FFV1','pixel_format':pixel,'container_fps':1,'container_time_is_capture_time':False}
|
| 76 |
-
def finish(self,notes):
|
| 77 |
-
for p,m in self.views:save(p/'metainfo.json',m)
|
| 78 |
-
save(self.base/'raw/doc/local_subset_manifest.json',self.refs)
|
| 79 |
-
report={'dataset':self.name,'views':len(self.views),'observations':sum(m['num_frames'] for _,m in self.views),'checks':self.checks,'notes':notes,'status':'partial' if notes else 'passed'}
|
| 80 |
-
save(self.out/'doc/report.json',report)
|
| 81 |
-
for script in ['pilot_build.py','pilot_fetch.py']:
|
| 82 |
-
shutil.copyfile(WORK/'scripts'/script,self.out/'script'/script)
|
| 83 |
-
(self.out/'script/README.md').write_text('执行入口:工作区 scripts/pilot_build.py --dataset '+self.name+'。此目录为脚本快照;脚本当前依赖工作区的 datasets 与 tmp/pilot-runtime,尚不是独立发布包。\n',encoding='utf-8')
|
| 84 |
-
files=[{'path':str(p.relative_to(self.out)), 'bytes':p.stat().st_size,'sha256':sha(p)} for p in sorted((self.out/'data').rglob('*')) if p.is_file()]
|
| 85 |
-
save(self.out/'doc/output_manifest.json',files)
|
| 86 |
-
print(json.dumps(report,ensure_ascii=False),flush=True)
|
| 87 |
-
return report
|
| 88 |
-
|
| 89 |
-
def h2o():
|
| 90 |
-
b=Build('H2O');src=OLD/'H2O/subject4_ego/h1/0/cam4';ids=list(range(N))
|
| 91 |
-
p,m=b.view('subject4_h1_0','cam4',ids,split='test',view_type='ego',time_semantics='ordered_source_frames; acquisition FPS not yet verified')
|
| 92 |
-
for folder in ['rgb','depth','hand_pose','hand_pose_mano','cam_pose']:
|
| 93 |
-
for i in ids:b.copy(src/folder/f'{i:06d}.{ "png" if folder in ["rgb","depth"] else "txt"}')
|
| 94 |
-
intr=np.loadtxt(b.copy(src/'cam_intrinsics.txt'));fx,fy,cx,cy,w,h=intr
|
| 95 |
-
tensor(p/'camera/intrinsic.pt',np.array([[fx,0,cx],[0,fy,cy],[0,0,1]],np.float32))
|
| 96 |
-
ext=np.stack([np.loadtxt(src/'cam_pose'/f'{i:06d}.txt').reshape(4,4) for i in ids])
|
| 97 |
-
tensor(p/'camera/extrinsic.pt',np.linalg.inv(ext).astype(np.float32))
|
| 98 |
-
m['camera']={'model':'pinhole','width':int(w),'height':int(h),'extrinsic':'T_camera_from_world','source_extrinsic':'T_world_from_camera','unit':'m','distortion':'not supplied in selected intrinsics'}
|
| 99 |
-
a=np.stack([np.loadtxt(src/'hand_pose_mano'/f'{i:06d}.txt').reshape(2,62) for i in ids])
|
| 100 |
-
valid=a[:,:,0]==1;motion=np.concatenate([a[:,:,4:52],a[:,:,52:62],a[:,:,1:4]],axis=-1).astype(np.float32)
|
| 101 |
-
motion[~valid]=np.nan;tensor(p/'annotation/mano/motion.pt',motion);tensor(p/'annotation/mano/valid_flag.pt',valid)
|
| 102 |
-
m['mano']={'layout':['pose_axis_angle:48','betas:10','translation:3'],'shape':[N,2,61],'slots':['left','right'],'coordinate_frame':'camera','translation_unit':'m','flat_hand_mean':True,'model_version':'not supplied; MANO model not bundled','valid_flag':'source annotation flag, not visibility','geometry_validation':'not_tested; model unavailable'}
|
| 103 |
-
joints=np.stack([np.loadtxt(src/'hand_pose'/f'{i:06d}.txt').reshape(2,64) for i in ids]);tensor(p/'annotation/keypoints/xyz.pt',joints[:,:,1:].reshape(N,2,21,3).astype(np.float32));tensor(p/'annotation/keypoints/valid_flag.pt',joints[:,:,0]==1)
|
| 104 |
-
rgb=[np.asarray(Image.open(src/'rgb'/f'{i:06d}.png').convert('RGB')) for i in ids]
|
| 105 |
-
depth=[np.asarray(Image.open(src/'depth'/f'{i:06d}.png'),dtype=np.uint16) for i in ids]
|
| 106 |
-
m['rgb']=b.video(p/'observation/rgb.mkv',rgb);m['depth']={**b.video(p/'observation/depth.mkv',depth),'unit':'mm','scale_to_meters':0.001,'invalid_value':0,'rgb_registration':'not_tested'}
|
| 107 |
-
m['missing_modalities']={'object':'not present in selected historical subset','segmentation':'no native mask in selected subset'}
|
| 108 |
-
# Independent check: 3D keypoint projections must be finite where the source flags valid.
|
| 109 |
-
xyz=joints[:,:,1:].reshape(N,2,21,3);projection=xyz@np.array([[fx,0,cx],[0,fy,cy],[0,0,1]]).T
|
| 110 |
-
uv=projection[...,:2]/projection[...,2:];assert np.isfinite(uv[joints[:,:,0]==1]).all()
|
| 111 |
-
image=Image.fromarray(rgb[0]);draw=ImageDraw.Draw(image)
|
| 112 |
-
for side in range(2):
|
| 113 |
-
for u,v in uv[0,side]:draw.ellipse((u-3,v-3,u+3,v+3),fill=('red' if side==0 else 'cyan'))
|
| 114 |
-
image.save(b.out/'doc/keypoints_overlay.png')
|
| 115 |
-
return b.finish(['MANO geometry not rendered; model asset unavailable. RGB-depth registration not tested. No native segmentation or object input in subset.'])
|
| 116 |
-
|
| 117 |
-
def visor():
|
| 118 |
-
b=Build('VISOR');raw=b.base/'raw/data/GroundTruth-SparseAnnotations';jp=raw/'annotations/train/P01_03.json';zp=raw/'rgb_frames/train/P01/P01_03.zip'
|
| 119 |
-
source=load(jp);annotations=source['video_annotations'][:N]
|
| 120 |
-
ids=[x['image']['name'] for x in annotations];p,m=b.view('P01_03','ego',ids,split='train',view_type='ego',time_semantics='sparse_annotations; use source frame IDs; MKV timestamps are storage indices')
|
| 121 |
-
rgbs=[];masks=[];records=[]
|
| 122 |
-
with zipfile.ZipFile(zp) as z:
|
| 123 |
-
assert z.testzip() is None
|
| 124 |
-
for i,frame in enumerate(annotations):
|
| 125 |
-
rgb=np.asarray(Image.open(io.BytesIO(z.read(frame['image']['name']))).convert('RGB'));rgbs.append(rgb)
|
| 126 |
-
mask=np.zeros((1080,1920),np.uint16);entities=[]
|
| 127 |
-
for value,entity in enumerate(frame['annotations'],1):
|
| 128 |
-
# Same polygon rasterization primitive and integer conversion as official VISOR-VIS.
|
| 129 |
-
polygons=[np.asarray(poly,dtype=np.int32) for poly in entity['segments'] if len(poly)>=3]
|
| 130 |
-
if polygons:cv2.fillPoly(mask,polygons,int(value))
|
| 131 |
-
entities.append({'mask_value':value,'instance_id':entity['id'],'track_id':None,'source':{k:v for k,v in entity.items() if k!='segments'}})
|
| 132 |
-
if mask.shape!=rgb.shape[:2]:mask=cv2.resize(mask,(rgb.shape[1],rgb.shape[0]),interpolation=cv2.INTER_NEAREST)
|
| 133 |
-
masks.append(mask);records.append({'frame_index':i,'source_frame_id':frame['image']['name'],'subsequence':frame['image']['subsequence'],'annotation_valid':True,'instances':entities})
|
| 134 |
-
assert set(np.unique(mask)) <= {0,*[x['mask_value'] for x in entities]}
|
| 135 |
-
m['rgb']=b.video(p/'observation/rgb.mkv',rgbs);m['segmentation']={**b.video(p/'annotation/segmentation/mask.mkv',masks),'provenance':'native_sparse_polygon_rasterized','background_value':0,'background_semantics':'unlabeled/background; source is not globally exhaustive','ignore_value':None,'polygon_canvas':[1920,1080],'overlap_policy':'source annotation order; last polygon wins','track_id':'unknown; no heuristic tracking'}
|
| 136 |
-
lines(p/'annotation/segmentation/instances.jsonl',records)
|
| 137 |
-
m['missing_modalities']={'mano':'not supplied','depth':'not supplied','camera':'not supplied','object_pose_mesh':'not supplied'}
|
| 138 |
-
im=rgbs[2].copy();mask=masks[2];colors=np.array([[0,0,0],[240,70,70],[70,240,90],[70,100,240],[230,190,60],[150,80,200]],np.uint8)
|
| 139 |
-
used=mask>0;im[used]=(im[used]*0.55+colors[mask[used]%len(colors)]*0.45).astype(np.uint8)
|
| 140 |
-
Image.fromarray(im).save(b.out/'doc/segmentation_overlay.png')
|
| 141 |
-
b.checks.append({'test':'official_zip_crc_all_members','passed':True,'members':len(zipfile.ZipFile(zp).namelist())})
|
| 142 |
-
b.checks.append({'test':'all_mask_values_resolve_to_frame_instances','passed':True})
|
| 143 |
-
return b.finish([])
|
| 144 |
-
|
| 145 |
-
def rhd():
|
| 146 |
-
b=Build('RHD');src=OLD/'RHD/RHD_published_v2/evaluation';ann=read_pickle(b.copy(src/'anno_evaluation.pickle'))
|
| 147 |
-
for i in range(N):
|
| 148 |
-
p,m=b.view(f'evaluation_{i:05d}','camera',[i],split='evaluation',time_semantics='independent_image')
|
| 149 |
-
rgb=np.asarray(Image.open(b.copy(src/'color'/f'{i:05d}.png')).convert('RGB'))
|
| 150 |
-
depth=np.asarray(Image.open(b.copy(src/'depth'/f'{i:05d}.png')).convert('RGB'),dtype=np.uint16)
|
| 151 |
-
code=depth[:,:,0]*256+depth[:,:,1]
|
| 152 |
-
m['rgb']=b.video(p/'observation/rgb.mkv',[rgb]);m['depth']={**b.video(p/'observation/depth.mkv',[code]),'encoding':'source R*256+G','metric_unit':None,'metric_conversion_status':'not_tested; preserved integer code only'}
|
| 153 |
-
tensor(p/'camera/intrinsic.pt',ann[i]['K']);tensor(p/'annotation/keypoints/xyz.pt',ann[i]['xyz'].reshape(1,2,21,3));tensor(p/'annotation/keypoints/uv.pt',ann[i]['uv_vis'][:,:2].reshape(1,2,21,2));tensor(p/'annotation/keypoints/visible.pt',(ann[i]['uv_vis'][:,2]==1).reshape(1,2,21))
|
| 154 |
-
m['keypoints']={'unit':'m','layout':'source 42-joint order reshaped as 2x21','hand_order':['left','right'],'joint_order':'official RHD: wrist then thumb/index/middle/ring/pinky, fingers tip-to-palm','definition_reference':'raw/doc/dataset_README.txt','visibility':'per joint; invisible does not mean unannotated'}
|
| 155 |
-
m['missing_modalities']={'mano':'not supplied by source','segmentation':'omitted by historical downloader','extrinsic':'not supplied in selected annotations'}
|
| 156 |
-
return b.finish(['Depth metric conversion pending; segmentation absent from historical input.'])
|
| 157 |
-
|
| 158 |
-
def freihand():
|
| 159 |
-
b=Build('FreiHAND');src=OLD/'FreiHAND';K=load(b.copy(src/'training_K.json'));mano=load(b.copy(src/'training_mano.json'));scale=load(b.copy(src/'training_scale.json'))
|
| 160 |
-
for base in range(4):
|
| 161 |
-
for variant in range(4):
|
| 162 |
-
i=base+variant*32560;p,m=b.view(f'training_{base:08d}',f'variant_{variant}',[i],split='training',time_semantics='independent_image',base_sample_id=str(base),variant_id=variant)
|
| 163 |
-
m['camera_group_semantics']='image_variant_not_physical_camera';m['physical_camera_id']=None
|
| 164 |
-
rgb=np.asarray(Image.open(b.copy(src/'training/rgb'/f'{i:08d}.jpg')).convert('RGB'));m['rgb']=b.video(p/'observation/rgb.mkv',[rgb])
|
| 165 |
-
tensor(p/'camera/intrinsic.pt',np.asarray(K[base],np.float32));tensor(p/'annotation/mano/source_theta.pt',np.asarray(mano[base],np.float32));tensor(p/'annotation/mano/source_scale.pt',np.asarray(scale[base],np.float32))
|
| 166 |
-
m['mano']={'source_theta_layout':['pose48','shape10','uv_root2','scale1'],'motion_status':'not_generated','reason':'To recover MANO translation, official code subtracts posed joint 9 from backprojected root. Requires correct MANO model; last three source values are not translation.'}
|
| 167 |
-
m['missing_modalities']={'depth':'not supplied','segmentation':'not present in historical input','extrinsic':'not supplied','normalized_mano':'model dependency unresolved'}
|
| 168 |
-
return b.finish(['Preserved source MANO theta; no misleading motion.pt produced. Correct model needed for normalized translation.'])
|
| 169 |
-
|
| 170 |
-
def hoi4d():
|
| 171 |
-
b=Build('HOI4D');rel=Path('ZY20210800001/H1/C20/N18/S286/s01/T1');src=OLD/'HOI4D/Hand_pose/handpose_left_hand'/rel
|
| 172 |
-
files=sorted(src.glob('*.pickle'),key=lambda p:int(p.stem))[:N];ids=[x.stem for x in files]
|
| 173 |
-
p,m=b.view('H1_C20_N18_S286_s01_T1','ZY20210800001',ids,view_type='ego',time_semantics='annotation_frame_ids_only')
|
| 174 |
-
a=np.full((len(ids),2,61),np.nan,np.float32);v=np.zeros((len(ids),2),bool);uv=np.full((len(ids),2,21,2),np.nan,np.float32)
|
| 175 |
-
for i,frame in enumerate(ids):
|
| 176 |
-
for side,folder in enumerate(['handpose_left_hand','handpose_right_hand']):
|
| 177 |
-
f=OLD/'HOI4D/Hand_pose'/folder/rel/(frame+'.pickle')
|
| 178 |
-
if not f.exists():continue
|
| 179 |
-
x=read_pickle(b.copy(f));a[i,side]=np.concatenate([x['poseCoeff'].reshape(-1),x['beta'].reshape(-1),x['trans'].reshape(-1)]);v[i,side]=True;uv[i,side]=x['kps2D']
|
| 180 |
-
tensor(p/'annotation/mano/motion.pt',a);tensor(p/'annotation/mano/valid_flag.pt',v);tensor(p/'annotation/keypoints/uv.pt',uv)
|
| 181 |
-
tensor(p/'camera/intrinsic.pt',np.load(b.copy(OLD/'HOI4D/camera_params/ZY20210800001/intrin.npy'),allow_pickle=False))
|
| 182 |
-
m['mano']={'layout':['pose_axis_angle48','betas10','translation3'],'slots':['left','right'],'translation_unit':'m','coordinate_frame':'camera','flat_hand_mean':True,'valid_flag':'source file present and parsed; not visibility','geometry_validation':'not_tested'}
|
| 183 |
-
m['missing_modalities']={'rgb':'not downloaded','depth':'not downloaded','segmentation':'not downloaded','extrinsic':'not available in selected subset','object':'not available in selected subset'}
|
| 184 |
-
return b.finish(['Annotation-only mini; no matching RGB/depth/segmentation downloaded. MANO geometry not rendered.'])
|
| 185 |
-
|
| 186 |
-
def reinterhand():
|
| 187 |
-
b=Build('ReInterHand');src=next(p for p in sorted((OLD/'ReInterHand').glob('m--*')) if (p/'mano_fits/params').exists());files=sorted((src/'mano_fits/params').glob('*_left.json'))[:N];ids=[x.stem.rsplit('_',1)[0] for x in files]
|
| 188 |
-
# Capture-level poses have no established camera transform in current local subset.
|
| 189 |
-
p,m=b.view(src.name,'source_unresolved',ids,time_semantics='capture_annotations_only; not a camera observation')
|
| 190 |
-
rows=[]
|
| 191 |
-
for frame in ids:
|
| 192 |
-
row={'source_frame_id':frame,'hands':{}}
|
| 193 |
-
for side in ['left','right']:
|
| 194 |
-
f=src/'mano_fits/params'/f'{frame}_{side}.json'
|
| 195 |
-
if f.exists():row['hands'][side]=load(b.copy(f))
|
| 196 |
-
rows.append(row)
|
| 197 |
-
lines(p/'annotation/mano/source_parameters.jsonl',rows)
|
| 198 |
-
m['missing_modalities']={'rgb':'not extracted from incomplete archive set','camera':'not available','normalized_mano':'source-to-camera mapping unresolved'}
|
| 199 |
-
m['not_a_real_camera']=True
|
| 200 |
-
return b.finish(['Source-only annotation sample. source_unresolved is an explicit staging group, not an invented camera.'])
|
| 201 |
-
|
| 202 |
-
def main():
|
| 203 |
-
parser=argparse.ArgumentParser();parser.add_argument('--dataset',nargs='*',default=['VISOR','H2O','RHD','FreiHAND','HOI4D','ReInterHand']);args=parser.parse_args()
|
| 204 |
-
funcs={'VISOR':visor,'H2O':h2o,'RHD':rhd,'FreiHAND':freihand,'HOI4D':hoi4d,'ReInterHand':reinterhand}
|
| 205 |
-
for name in args.dataset:
|
| 206 |
-
try:funcs[name]()
|
| 207 |
-
except Exception as e:
|
| 208 |
-
save(ROOT/name/'pilot-v0/doc/build_error.json',{'error':str(e)});raise
|
| 209 |
-
if __name__=='__main__':main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
RHD/shared-v1.0/script/pilot_fetch.py
DELETED
|
@@ -1,63 +0,0 @@
|
|
| 1 |
-
"""Download bounded official pilot inputs; keep archives intact. No upstream code execution."""
|
| 2 |
-
from pathlib import Path
|
| 3 |
-
import concurrent.futures, hashlib, json, requests
|
| 4 |
-
|
| 5 |
-
ROOT = Path(__file__).resolve().parents[1] / 'hand-datasets'
|
| 6 |
-
REFS = {
|
| 7 |
-
'Dex-YCB': ('NVlabs/dex-ycb-toolkit', ['README.md','dex_ycb_toolkit/dex_ycb.py','dex_ycb_toolkit/sequence_loader.py']),
|
| 8 |
-
'VISOR': ('epic-kitchens/VISOR-VIS', ['README.md','vis.py']),
|
| 9 |
-
'H2O': ('taeinkwon/h2odataset', ['README.md','download_script.py']),
|
| 10 |
-
'HOI4D': ('leolyliu/HOI4D-Instructions', ['README.md','utils/parse_2Dmask_img.py','utils/color_map.py']),
|
| 11 |
-
'ARCTIC': ('zc-alexfan/arctic', ['docs/data/README.md','docs/data/data_doc.md']),
|
| 12 |
-
'FreiHAND': ('lmb-freiburg/freihand', ['README.md','utils/model.py','utils/fh_utils.py','view_samples.py']),
|
| 13 |
-
'RHD': ('lmb-freiburg/hand3d', ['README.md','create_binary_db.py']),
|
| 14 |
-
'HOT3D': ('facebookresearch/hot3d', ['README.md','hot3d/data_loaders/loader_hand_poses.py']),
|
| 15 |
-
'OakInk2': ('oakink/OakInk2', ['README.md']),
|
| 16 |
-
'ReInterHand': ('facebookresearch/InterWild', ['tool/ReInterHand/download/download_checksum_framelist.py','tool/ReInterHand/download/download_ego_per_frame.py','tool/ReInterHand/download/download_mano_fits.py']),
|
| 17 |
-
}
|
| 18 |
-
BASE='https://data.bris.ac.uk/datasets/2v6cgv1x04ol22qp9rm9x2j6a7/'
|
| 19 |
-
|
| 20 |
-
def sha(p):
|
| 21 |
-
h=hashlib.sha256()
|
| 22 |
-
with p.open('rb') as f:
|
| 23 |
-
for b in iter(lambda:f.read(1024*1024),b''):h.update(b)
|
| 24 |
-
return h.hexdigest()
|
| 25 |
-
|
| 26 |
-
def fetch(dataset, url, relative, limit=30_000_000):
|
| 27 |
-
p=ROOT/dataset/'raw'/relative;p.parent.mkdir(parents=True,exist_ok=True)
|
| 28 |
-
receipt=p.with_name(p.name+'.receipt.json')
|
| 29 |
-
if p.exists() and receipt.exists():
|
| 30 |
-
info=json.loads(receipt.read_text()); assert sha(p)==info['sha256'];return info
|
| 31 |
-
part=p.with_name(p.name+'.part')
|
| 32 |
-
with requests.get(url,stream=True,headers={'Accept-Encoding':'identity'},timeout=(15,40)) as r:
|
| 33 |
-
r.raise_for_status(); expected=int(r.headers.get('Content-Length',0))
|
| 34 |
-
if expected>limit:raise ValueError(f'File exceeds pilot limit: {expected}')
|
| 35 |
-
size=0
|
| 36 |
-
with part.open('wb') as f:
|
| 37 |
-
for chunk in r.iter_content(1024*1024):
|
| 38 |
-
size+=len(chunk)
|
| 39 |
-
if size>limit:raise ValueError('Stream exceeds pilot limit')
|
| 40 |
-
f.write(chunk)
|
| 41 |
-
if expected and not r.headers.get('Content-Encoding') and size!=expected:raise ValueError('Incomplete transfer')
|
| 42 |
-
part.replace(p)
|
| 43 |
-
info={'url':url,'path':str(p.relative_to(ROOT/dataset)), 'bytes':size,'sha256':sha(p),'official_checksum':None,'verification':'HTTP success; content length where supplied; locally computed SHA256'}
|
| 44 |
-
receipt.write_text(json.dumps(info,indent=2),encoding='utf-8');return info
|
| 45 |
-
|
| 46 |
-
def reference(item):
|
| 47 |
-
name,(repo,paths)=item;results=[]
|
| 48 |
-
for section in ['raw/doc','raw/script','raw/data','pilot-v0/doc','pilot-v0/script','pilot-v0/data']:(ROOT/name/section).mkdir(parents=True,exist_ok=True)
|
| 49 |
-
for path in paths:
|
| 50 |
-
try:results.append(fetch(name,f'https://raw.githubusercontent.com/{repo}/HEAD/{path}',('script/' if path.endswith('.py') else 'doc/')+path))
|
| 51 |
-
except Exception as e:results.append({'path':path,'error':str(e)})
|
| 52 |
-
return name,results
|
| 53 |
-
|
| 54 |
-
def main():
|
| 55 |
-
results=dict(concurrent.futures.ThreadPoolExecutor(6).map(reference,REFS.items()))
|
| 56 |
-
for path in ['GroundTruth-SparseAnnotations/annotations/train/P01_03.json','GroundTruth-SparseAnnotations/rgb_frames/train/P01/P01_03.zip','EPIC_100_noun_classes_v2.csv','frame_mapping.json']:
|
| 57 |
-
try:results['VISOR'].append(fetch('VISOR',BASE+path,'data/'+path))
|
| 58 |
-
except Exception as e:results['VISOR'].append({'path':path,'error':str(e)})
|
| 59 |
-
for name,rows in results.items():
|
| 60 |
-
(ROOT/name/'raw/doc/download_manifest.json').write_text(json.dumps(rows,indent=2),encoding='utf-8')
|
| 61 |
-
print(name,[(r.get('path'),r.get('bytes',r.get('error'))) for r in rows],flush=True)
|
| 62 |
-
|
| 63 |
-
if __name__=='__main__':main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
RHD/shared-v1.0/script/pilot_mano.py
DELETED
|
@@ -1,87 +0,0 @@
|
|
| 1 |
-
"""Local licensed MANO model dependency; never copies models into shared outputs."""
|
| 2 |
-
from pilot_build import *
|
| 3 |
-
from types import SimpleNamespace
|
| 4 |
-
import smplx
|
| 5 |
-
|
| 6 |
-
class StoredState:
|
| 7 |
-
def __setstate__(self,state):self.__dict__.update(state)
|
| 8 |
-
class ModelReader(Restricted):
|
| 9 |
-
def find_class(self,module,name):
|
| 10 |
-
if (module,name) in [('chumpy.ch','Ch'),('chumpy.reordering','Select'),('scipy.sparse.csc','csc_matrix')]:return StoredState
|
| 11 |
-
if (module,name)==('__builtin__','set'):return set
|
| 12 |
-
return super().find_class(module,name)
|
| 13 |
-
|
| 14 |
-
def model_data(side):
|
| 15 |
-
p=WORK/'tmp/pilot-models'/f'MANO_{side.upper()}.pkl'
|
| 16 |
-
with p.open('rb') as f:d=ModelReader(f,encoding='latin1').load()
|
| 17 |
-
# Materialize only the two known serialized structures; execute no Chumpy code.
|
| 18 |
-
s=d['shapedirs']
|
| 19 |
-
if isinstance(s,StoredState):d['shapedirs']=s.a.x.reshape(-1)[s.idxs].reshape(s.preferred_shape)
|
| 20 |
-
sparse=d['J_regressor'];dense=np.zeros(sparse._shape)
|
| 21 |
-
for col in range(sparse._shape[1]):
|
| 22 |
-
a,z=sparse.indptr[col:col+2];dense[sparse.indices[a:z],col]=sparse.data[a:z]
|
| 23 |
-
d['J_regressor']=dense
|
| 24 |
-
assert d['shapedirs'].shape==(778,3,10) and dense.shape==(16,778)
|
| 25 |
-
return d
|
| 26 |
-
|
| 27 |
-
class Mano:
|
| 28 |
-
def __init__(self,side):
|
| 29 |
-
self.side=side
|
| 30 |
-
self.data=model_data(side)
|
| 31 |
-
self.layer=smplx.MANO(model_path=str(WORK/'tmp/pilot-models'),data_struct=SimpleNamespace(**self.data),is_rhand=side=='right',use_pca=False,flat_hand_mean=True)
|
| 32 |
-
def geometry(self,pose,betas,translation=None,keypoint_convention='freihand'):
|
| 33 |
-
pose=torch.as_tensor(np.asarray(pose).copy(),dtype=torch.float32).reshape(-1,48);betas=torch.as_tensor(np.asarray(betas).copy(),dtype=torch.float32).reshape(-1,10)
|
| 34 |
-
with torch.no_grad():o=self.layer(global_orient=pose[:,:3],hand_pose=pose[:,3:],betas=betas)
|
| 35 |
-
v=o.vertices.numpy();j=o.joints.numpy()[:,:16]
|
| 36 |
-
if translation is not None:
|
| 37 |
-
t=np.asarray(translation).reshape(-1,1,3);v=v+t;j=j+t
|
| 38 |
-
# Standard wrist + thumb,index,middle,ring,pinky proximal-to-distal order.
|
| 39 |
-
coords=[]
|
| 40 |
-
for k in [0,13,14,15,1,2,3,4,5,6,10,11,12,7,8,9]:coords.append(j[:,k])
|
| 41 |
-
out=np.stack([j[:,0],j[:,13],j[:,14],j[:,15],v[:,744],j[:,1],j[:,2],j[:,3],v[:,320],j[:,4],j[:,5],j[:,6],v[:,443],j[:,10],j[:,11],j[:,12],v[:,555],j[:,7],j[:,8],j[:,9],v[:,672]],axis=1)
|
| 42 |
-
if keypoint_convention=='manopth':out[:,[4,8,12,16,20]]=v[:,[745,317,444 if self.side=='right' else 445,556,673]]
|
| 43 |
-
return v,out,j
|
| 44 |
-
|
| 45 |
-
def freihand_normalize():
|
| 46 |
-
base=ROOT/'FreiHAND/pilot-v0';model=Mano('right');reports=[]
|
| 47 |
-
for meta_file in sorted((base/'data').rglob('metainfo.json')):
|
| 48 |
-
p=meta_file.parent;m=load(meta_file);theta=torch.load(p/'annotation/mano/source_theta.pt',weights_only=True).numpy().reshape(1,61)
|
| 49 |
-
K=torch.load(p/'camera/intrinsic.pt',weights_only=True).numpy();focal=(K[0,0]+K[1,1])/2
|
| 50 |
-
root=np.r_[(theta[0,58:60]-K[:2,2]),focal]/theta[0,60]
|
| 51 |
-
pose=theta[:,:48].copy();pose[:,3:]+=model.data['hands_mean']
|
| 52 |
-
_,_,j=model.geometry(pose,theta[:,48:58]);translation=root-j[0,4]
|
| 53 |
-
motion=np.full((1,2,61),np.nan,np.float32);motion[0,1]=np.r_[pose[0],theta[0,48:58],translation]
|
| 54 |
-
tensor(p/'annotation/mano/motion.pt',motion);tensor(p/'annotation/mano/valid_flag.pt',[[False,True]])
|
| 55 |
-
_,keypoints,_=model.geometry(pose,theta[:,48:58],translation)
|
| 56 |
-
assert np.allclose(keypoints[0,9],root,atol=1e-6)
|
| 57 |
-
m['mano']={'layout':['pose_axis_angle48','betas10','translation3'],'slots':['left','right'],'coordinate_frame':'camera','translation_unit':'m','flat_hand_mean':True,'model_version':'MANO v1.2','conversion':'source non-flat mean added to finger pose; official orthographic root recovery minus posed MANO joint 4 (21-joint index9)','valid_flag':'right-hand source annotation available; left not supplied'}
|
| 58 |
-
m['missing_modalities'].pop('normalized_mano',None);save(meta_file,m)
|
| 59 |
-
reports.append({'path':str(p.relative_to(base)),'root_recovery_error_m':float(np.linalg.norm(keypoints[0,9]-root))})
|
| 60 |
-
save(base/'doc/mano_validation.json',{'status':'passed_algebraic_root_check','model_sha256':sha(WORK/'tmp/pilot-models/MANO_RIGHT.pkl'),'samples':reports,'limit':'No independent 3D ground truth currently in input; algebraic check does not prove fit accuracy.'})
|
| 61 |
-
print('FreiHAND normalized',len(reports))
|
| 62 |
-
|
| 63 |
-
def validate_mano(name):
|
| 64 |
-
base=ROOT/name/'pilot-v0';models=[Mano('left'),Mano('right')];summaries=[]
|
| 65 |
-
for mp in (base/'data').rglob('metainfo.json'):
|
| 66 |
-
p=mp.parent;motionp=p/'annotation/mano/motion.pt'
|
| 67 |
-
if not motionp.exists():continue
|
| 68 |
-
a=torch.load(motionp,weights_only=True).numpy();valid=torch.load(p/'annotation/mano/valid_flag.pt',weights_only=True).numpy();K=torch.load(p/'camera/intrinsic.pt',weights_only=True).numpy();pred=np.full((len(a),2,21,3),np.nan,np.float32)
|
| 69 |
-
for side,model in enumerate(models):
|
| 70 |
-
ix=np.flatnonzero(valid[:,side])
|
| 71 |
-
if len(ix):_,pred[ix,side],_=model.geometry(a[ix,side,:48],a[ix,side,48:58],a[ix,side,58:],keypoint_convention='manopth')
|
| 72 |
-
tensor(p/'annotation/mano/derived_keypoints.pt',pred)
|
| 73 |
-
uv=pred@K.T;uv=uv[...,:2]/uv[...,2:]
|
| 74 |
-
row={'sequence':str(p.relative_to(base)),'keypoint_convention':'official manopth, including handedness-specific fingertip vertices','finite_valid_geometry':bool(np.isfinite(pred[valid]).all())}
|
| 75 |
-
target=p/('annotation/keypoints/xyz.pt' if name=='H2O' else 'annotation/keypoints/uv.pt')
|
| 76 |
-
if target.exists():
|
| 77 |
-
gt=torch.load(target,weights_only=True).numpy();err=np.linalg.norm((pred if name=='H2O' else uv)-gt,axis=-1);good=np.isfinite(err)&valid[:,:,None]
|
| 78 |
-
row['mean_error']=float(err[good].mean());row['max_error']=float(err[good].max());row['unit']='m' if name=='H2O' else 'pixels'
|
| 79 |
-
summaries.append(row)
|
| 80 |
-
meta=load(p/'metainfo.json');meta['mano']['geometry_validation']='measured against source keypoints; see doc/mano_validation.json';meta['mano']['model_version']='MANO v1.2'
|
| 81 |
-
meta['mano']['derived_keypoints_convention']='official manopth 21 joints, including side-specific fingertip vertices'
|
| 82 |
-
save(p/'metainfo.json',meta)
|
| 83 |
-
save(base/'doc/mano_validation.json',{'status':'measured_not_auto_accepted','samples':summaries,'model_sha256':{s:sha(WORK/'tmp/pilot-models'/f'MANO_{s.upper()}.pkl') for s in ['left','right']}})
|
| 84 |
-
print(name,summaries)
|
| 85 |
-
|
| 86 |
-
if __name__=='__main__':
|
| 87 |
-
freihand_normalize();validate_mano('H2O');validate_mano('HOI4D')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
RHD/shared-v1.0/script/pilot_rhd_lossless.py
DELETED
|
@@ -1,79 +0,0 @@
|
|
| 1 |
-
"""RHD bounded raw-to-contract pilot, with lossless media and local human review."""
|
| 2 |
-
from convert_freihand_lossless import View,ff,storage
|
| 3 |
-
from sequence_pilot_common import *
|
| 4 |
-
import sequence_pilot_common as common
|
| 5 |
-
import random,html,hashlib
|
| 6 |
-
BASE=Path('E:/hand-datasets/RHD');RELEASE='shared-v1.0'
|
| 7 |
-
|
| 8 |
-
def media(v,name,path,raw,pix,size,profile,codec='ffv1',options=None):
|
| 9 |
-
dst=v.p/path;dst.parent.mkdir(parents=True,exist_ok=True);options=options or ['-level','3']
|
| 10 |
-
ff(['-f','rawvideo','-pixel_format',pix,'-video_size',f'{size[0]}x{size[1]}','-framerate','1','-i','pipe:0','-c:v',codec,*options,str(dst)],raw)
|
| 11 |
-
restored=ff(['-i',str(dst),'-f','rawvideo','-pix_fmt',pix,'pipe:1']);assert restored==raw,name
|
| 12 |
-
v.checks.append({'test':'all_media_bytes_exact','component':name,'frames':v.T})
|
| 13 |
-
actual_pix='bgr0' if codec=='ffv1' and pix=='rgb24' else ('gbrp' if codec=='libx264rgb' else pix)
|
| 14 |
-
return storage(profile,codec,actual_pix,size,False,options),restored
|
| 15 |
-
|
| 16 |
-
def main():
|
| 17 |
-
common.ROOT=Path('E:/hand-datasets');common.RELEASE=RELEASE
|
| 18 |
-
contract=load(WORK/'distribution/hand-warehouse-1.0/schema.json');order=contract['keypoints']['rhd21/v1']['source_index_map_per_hand']
|
| 19 |
-
root=BASE/RELEASE;out=root/'doc/validation';out.mkdir(parents=True,exist_ok=True);cards=[];reports=[];rng=random.Random(20260918)
|
| 20 |
-
with zipfile.ZipFile(BASE/'raw/data/RHD_v1-1.zip') as z:
|
| 21 |
-
for split in ['training','evaluation']:
|
| 22 |
-
member=next(n for n in z.namelist() if n.endswith(f'{split}/anno_{split}.pickle'));prefix=member.rsplit('/',1)[0]
|
| 23 |
-
anno=Restricted(io.BytesIO(z.read(member)),encoding='latin1').load();rank=sorted(anno,key=lambda i:np.asarray(anno[i]['uv_vis'])[:,2].sum())
|
| 24 |
-
ids=list(dict.fromkeys(rank[:2]+rank[-2:]+rng.sample(sorted(anno),12)))[:12];t=len(ids)
|
| 25 |
-
v=View('RHD',split+'_review','camera',ids,[320,320],{'archive':'raw/data/RHD_v1-1.zip','annotation':member},kind='image',split='train' if split=='training' else 'test')
|
| 26 |
-
v.m.update(schema_version='hand-warehouse/1.0',storage_revision='lossless-video-2026-09-18',split_scheme='RHD_official_training_evaluation',split_source_locator={'archive':'raw/data/RHD_v1-1.zip','member_prefix':prefix},sample_type='image')
|
| 27 |
-
v.m['sampling'].update(type='independent',selection='2 lowest and 2 highest source visibility counts plus seeded random unique images, total 12 per split',seed=20260918)
|
| 28 |
-
for row,i in zip(v.frames,ids):row.update(sample_id=f'RHD/{split}/{i:05d}');row['source_locator'].update(annotation_index=i,member=f'{prefix}/color/{i:05d}.png')
|
| 29 |
-
rgb=np.stack([np.asarray(Image.open(io.BytesIO(z.read(f'{prefix}/color/{i:05d}.png'))).convert('RGB')) for i in ids])
|
| 30 |
-
rgbstore,_=media(v,'rgb','observation/rgb.mkv',rgb.tobytes(),'rgb24',[320,320],'mkv/ffv1_rgb/v1')
|
| 31 |
-
other=v.p/'observation/rgb_candidate.mkv';candidate,_=media(v,'rgb_candidate','observation/rgb_candidate.mkv',rgb.tobytes(),'rgb24',[320,320],'mkv/h264_rgb_lossless/v1','libx264rgb',['-crf','0','-preset','medium','-g','32'])
|
| 32 |
-
candidate['pixel_format']='gbrp'
|
| 33 |
-
sizes={'ffv1':(v.p/'observation/rgb.mkv').stat().st_size,'h264_rgb_lossless':other.stat().st_size}
|
| 34 |
-
if other.stat().st_size<(v.p/'observation/rgb.mkv').stat().st_size:other.replace(v.p/'observation/rgb.mkv');rgbstore=candidate
|
| 35 |
-
else:other.unlink()
|
| 36 |
-
v.add('rgb','observation/rgb.mkv','rgb/uint8/v1',['T','height','width','channel'],np.ones(t,bool),storage=rgbstore,storage_fps=1,timebase_role='index_only')
|
| 37 |
-
v.intrinsic(np.stack([anno[i]['K'] for i in ids]))
|
| 38 |
-
for key,stem,n,unit in [('xyz','xyz',3,'m'),('uv_vis','uv',2,'pixel')]:
|
| 39 |
-
a=np.stack([np.asarray(anno[i][key])[...,:n].reshape(2,21,n)[:,order] for i in ids]);v.array('keypoints_'+stem,'annotation/keypoints/'+stem+'.pt','keypoints/'+stem+'/v1',a,np.ones((t,2,21),bool),['T','hand','joint','coordinate'],unit=unit,keypoint_schema='rhd21/v1',coordinate_frame='camera' if n==3 else 'rgb_image',method='Keep both supplied hands including invisible points; reorder tip-to-palm to registered proximal-to-tip order',source_index_map=order)
|
| 40 |
-
vis=np.stack([np.asarray(anno[i]['uv_vis'])[:,2].reshape(2,21)[:,order].astype(bool) for i in ids]);tensor(v.p/'annotation/keypoints/visibility.pt',vis)
|
| 41 |
-
attribute={'data_ref':'annotation/keypoints/visibility.pt','axes':['T','hand','joint'],'dtype':'bool','visibility_type':'bool','meaning':'source per-keypoint visibility','valid':True,'provenance':{'kind':'format_conversion','method':'native uv_vis visibility reordered with coordinates'},'source_locator':v.source}
|
| 42 |
-
for k in ['keypoints_xyz','keypoints_uv']:v.m['components'][k]['attributes']={'visibility':attribute}
|
| 43 |
-
deps=[];masks=[];mapping=[]
|
| 44 |
-
for fi,i in enumerate(ids):
|
| 45 |
-
a=np.asarray(Image.open(io.BytesIO(z.read(f'{prefix}/depth/{i:05d}.png'))),dtype=np.uint16);code=a[:,:,0]*256+a[:,:,1];deps.append(code.astype(np.float32)/65535*5)
|
| 46 |
-
mask=np.asarray(Image.open(io.BytesIO(z.read(f'{prefix}/mask/{i:05d}.png')))).astype(np.uint16);assert mask.max()<=33;mask[mask==0]=65534;masks.append(mask)
|
| 47 |
-
mapping.append({'frame_index':fi,'labels':[{'mask_value':int(c),'category_id':'background' if c==65534 else ('person' if c==1 else 'hand'),'entity_id':None if c in [65534,1] else ('hand_left' if c<=17 else 'hand_right'),'part_id':None,'source_instance_id':0 if c==65534 else int(c),'source_attributes':{'native_region_code':0 if c==65534 else int(c)}} for c in np.unique(mask)]})
|
| 48 |
-
depth=np.stack(deps).astype('<f4');bits=depth.view('<u4');packed=np.concatenate([(bits&65535).astype('<u2'),(bits>>16).astype('<u2')],axis=2)
|
| 49 |
-
ds,decoded=media(v,'depth','observation/depth.mkv',packed.tobytes(),'gray16le',[640,320],'mkv/depth_float32_bits/v1');u=np.frombuffer(decoded,'<u2').reshape(t,320,640);back=(u[:,:,:320].astype('<u4')|(u[:,:,320:].astype('<u4')<<16)).view('<f4');assert back.tobytes()==depth.tobytes()
|
| 50 |
-
vs,_=media(v,'depth_valid','observation/depth_valid.mkv',np.ones((t,320,320),np.uint8).tobytes(),'gray',[320,320],'mkv/bool_ffv1/v1')
|
| 51 |
-
v.m['components']['depth']={'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'],'storage':ds,'valid_storage':vs,'unit':'m','depth_type':'z','depth_origin':'rendered','coordinate_frame':'current_rgb_camera','pixel_grid':'current_rgb','storage_fps':1,'timebase_role':'index_only','provenance':{'kind':'format_conversion','method':'Official code (R*256+G)/65535*5 m; preserve complete float32 bits; source supplies every pixel, no additional invalid-pixel convention inferred'},'source_locator':{**v.source,'member_pattern':prefix+'/depth/{source_frame_id:05d}.png'}}
|
| 52 |
-
masks=np.stack(masks).astype('<u2');ms,_=media(v,'segment','annotation/segment/mask.mkv',masks.tobytes(),'gray16le',[320,320],'mkv/uint16_ffv1/v1');lines(v.p/'annotation/segment/instances.jsonl',mapping)
|
| 53 |
-
v.add('segment','annotation/segment/mask.mkv','segment/uint16_labels/v1',['T','height','width'],np.ones(t,bool),storage=ms,storage_fps=1,timebase_role='index_only',segmentation_type='semantic',mapping_ref='annotation/segment/instances.jsonl',coverage={'kind':'full','scope':'official rendered background, person and both hand regions'},method='Native codes preserved; source 0 background mapped to 65534; native fine-region codes retained without merging')
|
| 54 |
-
xyz=torch.load(v.p/'annotation/keypoints/xyz.pt',weights_only=True).numpy();uv=torch.load(v.p/'annotation/keypoints/uv.pt',weights_only=True).numpy();K=torch.load(v.p/'camera/intrinsic.pt',weights_only=True).numpy()
|
| 55 |
-
projected=xyz@K[:,None].transpose(0,1,3,2);projected=projected[...,:2]/projected[...,2:];errors=np.linalg.norm(projected-uv,axis=-1)
|
| 56 |
-
v.checks.append({'test':'native_xyz_K_projection_vs_uv','max_pixel':float(errors.max()),'median_pixel':float(np.median(errors))});v.finish()
|
| 57 |
-
reports.append({'split':split,'selected_ids':ids,'rgb_candidate_sizes':sizes,'selected_rgb_profile':rgbstore['profile'],'max_projection_difference_pixels':float(errors.max()),'depth_float32_bits_exact':True,'media_roundtrip_exact':True})
|
| 58 |
-
# Read the actual saved RGB and masks, rather than render only the input arrays.
|
| 59 |
-
br=ff(['-i',str(v.p/'observation/rgb.mkv'),'-f','rawvideo','-pix_fmt','rgb24','pipe:1']);rgb=np.frombuffer(br,np.uint8).reshape(t,320,320,3)
|
| 60 |
-
bm=ff(['-i',str(v.p/'annotation/segment/mask.mkv'),'-f','rawvideo','-pix_fmt','gray16le','pipe:1']);masks=np.frombuffer(bm,'<u2').reshape(t,320,320)
|
| 61 |
-
for j,i in enumerate(ids):
|
| 62 |
-
original=rgb[j];seg=original.copy();colored=np.zeros_like(seg);colored[(masks[j]>=2)&(masks[j]<=17)]=[255,90,70];colored[(masks[j]>=18)&(masks[j]<=33)]=[30,180,255];active=colored.any(-1);seg[active]=(0.5*seg[active]+0.5*colored[active]).astype(np.uint8)
|
| 63 |
-
kpic=original.copy();ppic=original.copy()
|
| 64 |
-
for hand,color in [(0,(255,90,70)),(1,(30,180,255))]:
|
| 65 |
-
for joint in range(21):
|
| 66 |
-
x,y=uv[j,hand,joint];px,py=projected[j,hand,joint]
|
| 67 |
-
if abs(x)<10000 and abs(y)<10000:cv2.circle(kpic,(round(float(x)),round(float(y))),3,color,-1 if vis[j,hand,joint] else 1)
|
| 68 |
-
if abs(px)<10000 and abs(py)<10000:cv2.circle(ppic,(round(float(px)),round(float(py))),3,color,1)
|
| 69 |
-
dep=back[j];lo,hi=np.percentile(dep,[2,98]);display=np.clip((dep-lo)/max(hi-lo,1e-6),0,1);depthpic=cv2.cvtColor(cv2.applyColorMap((display*255).astype(np.uint8),cv2.COLORMAP_VIRIDIS),cv2.COLOR_BGR2RGB)
|
| 70 |
-
canvas=Image.new('RGB',(1600,346),'white');draw=ImageDraw.Draw(canvas)
|
| 71 |
-
for c,(a,label) in enumerate(zip([original,seg,kpic,ppic,depthpic],['RGB','Segmentation: L red / R blue','Native UV: hollow=invisible','XYZ projected with K','Z depth: per-image contrast'])):canvas.paste(Image.fromarray(a),(c*320,26));draw.text((c*320+4,6),label,fill='black')
|
| 72 |
-
name=f'{split}_{i:05d}.png';canvas.save(out/name);cards.append(f'<section><h2>{split}/{i:05d}</h2><p>Source visible joints: {int(vis[j].sum())}/42. Depth display range: {lo:.3f}–{hi:.3f} m.</p><img src="{name}"></section>')
|
| 73 |
-
save(out/'evidence.json',{'human_review':'pending','full_processing':'not_started','sampling_seed':20260918,'reports':reports})
|
| 74 |
-
page='<!doctype html><meta charset="utf-8"><title>RHD 小规模人工核验</title><style>body{font:16px system-ui;margin:30px;background:#f5f6f8}section{background:white;padding:16px;margin:20px 0}img{max-width:100%}</style><h1>RHD:24 张 raw→share 转换核验</h1><p>训练与评估各12张,包含可见性极端和随机样本。独立图片不是视频序列。尚待人工确认,不进行全量处理或上传。</p><p>从左至右:RGB、左右手分割、原生2D关键点、3D点经相机投影、米制z深度可视化。红=左手,蓝=右手;2D空心点表示源标注不可见,仍保留坐标。深度图逐图拉伸对比度,颜色不能跨图直接比较米数。</p><p>检查双手身份、关键点顺序与UV/XYZ对应、分割边缘和深度轮廓。MANO、物体等源未提供的组件缺省。</p>'+''.join(cards)
|
| 75 |
-
(out/'index.html').write_text(page,encoding='utf8')
|
| 76 |
-
for name in ['CONTRACT.md','schema.json']:shutil.copyfile(WORK/'distribution/hand-warehouse-1.0'/name,root/'doc'/name)
|
| 77 |
-
(root/'script').mkdir(exist_ok=True);shutil.copyfile(__file__,root/'script'/Path(__file__).name)
|
| 78 |
-
print(out/'index.html',flush=True)
|
| 79 |
-
if __name__=='__main__':main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
RHD/shared-v1.0/script/{review_rhd_full_random.py → render_full_random_review.py}
RENAMED
|
@@ -1,11 +1,12 @@
|
|
| 1 |
-
"""
|
| 2 |
-
from
|
| 3 |
-
from
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
|
| 7 |
def main():
|
| 8 |
-
|
|
|
|
| 9 |
for mp in sorted((root/'data').glob('*/*/metainfo.json')):
|
| 10 |
m=load(mp);p=mp.parent;view=p.relative_to(root).as_posix();split='training' if m['split']=='train' else 'evaluation';t=m['num_frames']
|
| 11 |
rows=[json.loads(l) for l in (p/'camera/frames.jsonl').read_text().splitlines()];assert len(rows)==t;frames_by_view[view]=rows
|
|
@@ -29,7 +30,7 @@ def main():
|
|
| 29 |
for split in ['training','evaluation']:
|
| 30 |
for view,i in rng.sample(pools[split],12):chosen.setdefault(view,[]).append(i)
|
| 31 |
out=root/'doc/validation/full_random';out.mkdir(parents=True,exist_ok=True)
|
| 32 |
-
with zipfile.ZipFile(
|
| 33 |
for view in sorted(chosen):
|
| 34 |
p=root/view;m=load(p/'metainfo.json');split='training' if m['split']=='train' else 'evaluation';indices=sorted(chosen[view]);t=len(indices);rows=[frames_by_view[view][i] for i in indices];ids=[int(f['source_frame_id']) for f in rows]
|
| 35 |
print('Random review',view,indices,flush=True)
|
|
@@ -66,10 +67,5 @@ def main():
|
|
| 66 |
page='<!doctype html><meta charset="utf-8"><title>RHD 全量随机抽查</title><style>body{font:16px system-ui;margin:30px;background:#f5f6f8}section{background:white;padding:16px;margin:20px 0}img{max-width:100%}</style><h1>RHD 全量产物随机抽查:24 张</h1><p>直接从全量产物读取,训练与评估各随机12张;种子20260918。分层等额抽样,不能据此估计总体错误率。RGB、mask及深度重新与 raw 对比通过,人工确认待完成。</p><p>依次为 RGB、左右手分割、原生 UV(空心=不可见)、XYZ 投影、逐图拉伸的 z 深度。颜色:红左手、蓝右手。</p>'+''.join(cards)
|
| 67 |
(out/'index.html').write_text(page,encoding='utf8')
|
| 68 |
(out/'REPORT.md').write_text('# RHD 全量随机抽查\n\n[离线预览](index.html) · [抽样清单](samples.json)\n\n全量 43,986 张,训练与评估各随机选 12 张;分层等额、固定种子20260918,无放回抽样。直接读取已完成的分片,不复用试点。所选 RGB、mask 和 float32 深度逐值/逐比特与 raw 对应数据匹配。\n\n**人工确认待完成,未上传。** 检查左右手身份、分割轮廓、UV/XYZ投影及深度;本报告不替代全量数值验证。\n',encoding='utf8')
|
| 69 |
-
checks=load(BASE/'tmp/production/full_checks.json');assert checks['passed']
|
| 70 |
-
e=load(root/'doc/validation/evidence.json');e['full_processing']={'automated':'passed','counts':counts,'shards':len(frames_by_view),'full_random_review':'pending','report_ref':'full_random/REPORT.md'};save(root/'doc/validation/evidence.json',e)
|
| 71 |
-
with (root/'doc/validation/REPORT.md').open('a',encoding='utf8') as f:f.write('\n\n全量自动检查已通过:43,986 张。额外人工核验请看 [全量随机抽查](full_random/REPORT.md),当前待确认。\n')
|
| 72 |
-
for name in ['convert_rhd_full.py','review_rhd_full_random.py']:shutil.copyfile(WORK/'scripts'/name,root/'script'/name)
|
| 73 |
-
state=load(WORK/'tmp/dataset-work-state.json');state['active']['RHD']['stage']='awaiting_full_random_review';save(WORK/'tmp/dataset-work-state.json',state)
|
| 74 |
print(out/'index.html',flush=True)
|
| 75 |
if __name__=='__main__':main()
|
|
|
|
| 1 |
+
"""Regenerate the fixed-seed RHD full-release visual review; never uploads."""
|
| 2 |
+
from rhd_common import *
|
| 3 |
+
from PIL import Image, ImageDraw
|
| 4 |
+
import argparse, cv2, html, random, zipfile
|
| 5 |
+
root=RELEASE_ROOT
|
| 6 |
|
| 7 |
def main():
|
| 8 |
+
argparse.ArgumentParser(description='Render RHD full_random from the adjacent shared-v1.0 release.').parse_args()
|
| 9 |
+
registry=load(root/'doc/schema.json');pools={'training':[],'evaluation':[]};frames_by_view={};counts={'training':0,'evaluation':0};seen=set();cards=[];records=[]
|
| 10 |
for mp in sorted((root/'data').glob('*/*/metainfo.json')):
|
| 11 |
m=load(mp);p=mp.parent;view=p.relative_to(root).as_posix();split='training' if m['split']=='train' else 'evaluation';t=m['num_frames']
|
| 12 |
rows=[json.loads(l) for l in (p/'camera/frames.jsonl').read_text().splitlines()];assert len(rows)==t;frames_by_view[view]=rows
|
|
|
|
| 30 |
for split in ['training','evaluation']:
|
| 31 |
for view,i in rng.sample(pools[split],12):chosen.setdefault(view,[]).append(i)
|
| 32 |
out=root/'doc/validation/full_random';out.mkdir(parents=True,exist_ok=True)
|
| 33 |
+
with zipfile.ZipFile(RAW_ROOT/'RHD_v1-1.zip') as z:
|
| 34 |
for view in sorted(chosen):
|
| 35 |
p=root/view;m=load(p/'metainfo.json');split='training' if m['split']=='train' else 'evaluation';indices=sorted(chosen[view]);t=len(indices);rows=[frames_by_view[view][i] for i in indices];ids=[int(f['source_frame_id']) for f in rows]
|
| 36 |
print('Random review',view,indices,flush=True)
|
|
|
|
| 67 |
page='<!doctype html><meta charset="utf-8"><title>RHD 全量随机抽查</title><style>body{font:16px system-ui;margin:30px;background:#f5f6f8}section{background:white;padding:16px;margin:20px 0}img{max-width:100%}</style><h1>RHD 全量产物随机抽查:24 张</h1><p>直接从全量产物读取,训练与评估各随机12张;种子20260918。分层等额抽样,不能据此估计总体错误率。RGB、mask及深度重新与 raw 对比通过,人工确认待完成。</p><p>依次为 RGB、左右手分割、原生 UV(空心=不可见)、XYZ 投影、逐图拉伸的 z 深度。颜色:红左手、蓝右手。</p>'+''.join(cards)
|
| 68 |
(out/'index.html').write_text(page,encoding='utf8')
|
| 69 |
(out/'REPORT.md').write_text('# RHD 全量随机抽查\n\n[离线预览](index.html) · [抽样清单](samples.json)\n\n全量 43,986 张,训练与评估各随机选 12 张;分层等额、固定种子20260918,无放回抽样。直接读取已完成的分片,不复用试点。所选 RGB、mask 和 float32 深度逐值/逐比特与 raw 对应数据匹配。\n\n**人工确认待完成,未上传。** 检查左右手身份、分割轮廓、UV/XYZ投影及深度;本报告不替代全量数值验证。\n',encoding='utf8')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
print(out/'index.html',flush=True)
|
| 71 |
if __name__=='__main__':main()
|
RHD/shared-v1.0/script/rhd_common.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared helpers for the published RHD shared-v1.0 tools."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import codecs, collections, hashlib, io, json, pickle, subprocess
|
| 4 |
+
|
| 5 |
+
import imageio_ffmpeg
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
SCRIPT_DIR = Path(__file__).resolve().parent
|
| 10 |
+
RELEASE_ROOT = SCRIPT_DIR.parent
|
| 11 |
+
DATASET_ROOT = RELEASE_ROOT.parent
|
| 12 |
+
RAW_ROOT = DATASET_ROOT / "raw" / "data"
|
| 13 |
+
TMP_ROOT = DATASET_ROOT / "tmp" / "rhd-tools"
|
| 14 |
+
FFMPEG = imageio_ffmpeg.get_ffmpeg_exe()
|
| 15 |
+
FF = FFMPEG
|
| 16 |
+
|
| 17 |
+
def load(path):
|
| 18 |
+
return json.loads(Path(path).read_text(encoding="utf-8"))
|
| 19 |
+
|
| 20 |
+
def save(path, value):
|
| 21 |
+
path = Path(path); path.parent.mkdir(parents=True, exist_ok=True)
|
| 22 |
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
| 23 |
+
tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False), encoding="utf-8")
|
| 24 |
+
tmp.replace(path)
|
| 25 |
+
|
| 26 |
+
def write_jsonl(path, rows):
|
| 27 |
+
path = Path(path); path.parent.mkdir(parents=True, exist_ok=True)
|
| 28 |
+
path.write_text("".join(json.dumps(x, ensure_ascii=False, allow_nan=False) + "\n" for x in rows), encoding="utf-8")
|
| 29 |
+
|
| 30 |
+
def save_tensor(path, value):
|
| 31 |
+
path = Path(path); path.parent.mkdir(parents=True, exist_ok=True)
|
| 32 |
+
torch.save(torch.as_tensor(np.asarray(value).copy()), path)
|
| 33 |
+
|
| 34 |
+
lines = write_jsonl
|
| 35 |
+
tensor = save_tensor
|
| 36 |
+
|
| 37 |
+
def ffmpeg(args, data=None):
|
| 38 |
+
result = subprocess.run([FFMPEG, "-v", "error", "-y", *map(str, args)], input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 39 |
+
if result.returncode:
|
| 40 |
+
raise RuntimeError(result.stderr.decode(errors="replace"))
|
| 41 |
+
return result.stdout
|
| 42 |
+
|
| 43 |
+
def storage(profile, codec, pixel_format, size, source_lossy, parameters):
|
| 44 |
+
version = ffmpeg(["-version"]).decode().splitlines()[0]
|
| 45 |
+
return {"profile": profile, "codec": codec, "pixel_format": pixel_format,
|
| 46 |
+
"encoded_size": size, "source_lossy": source_lossy,
|
| 47 |
+
"decoder": version, "encoder_parameters": parameters}
|
| 48 |
+
|
| 49 |
+
class RestrictedUnpickler(pickle.Unpickler):
|
| 50 |
+
def find_class(self, module, name):
|
| 51 |
+
allowed = {
|
| 52 |
+
("numpy.core.multiarray", "_reconstruct"): np.core.multiarray._reconstruct,
|
| 53 |
+
("numpy._core.multiarray", "_reconstruct"): np.core.multiarray._reconstruct,
|
| 54 |
+
("numpy", "ndarray"): np.ndarray, ("numpy", "dtype"): np.dtype,
|
| 55 |
+
("numpy.core.numeric", "_frombuffer"): np.core.numeric._frombuffer,
|
| 56 |
+
("numpy._core.numeric", "_frombuffer"): np.core.numeric._frombuffer,
|
| 57 |
+
("_codecs", "encode"): codecs.encode,
|
| 58 |
+
("collections", "OrderedDict"): collections.OrderedDict,
|
| 59 |
+
}
|
| 60 |
+
if (module, name) not in allowed:
|
| 61 |
+
raise pickle.UnpicklingError(f"Unsupported class: {module}.{name}")
|
| 62 |
+
return allowed[(module, name)]
|
| 63 |
+
|
| 64 |
+
Restricted = RestrictedUnpickler
|
| 65 |
+
|
| 66 |
+
class View:
|
| 67 |
+
def __init__(self, dataset, sequence, camera, frame_ids, size, source, kind="image", split="unknown"):
|
| 68 |
+
assert dataset == "RHD" and camera == "camera" and kind == "image"
|
| 69 |
+
self.root = RELEASE_ROOT
|
| 70 |
+
self.path = RELEASE_ROOT / "data" / sequence / camera
|
| 71 |
+
self.path.mkdir(parents=True, exist_ok=True)
|
| 72 |
+
self.count = len(frame_ids)
|
| 73 |
+
archive = Path(source["archive"]).name
|
| 74 |
+
self.source = dict(source)
|
| 75 |
+
self.checks = []
|
| 76 |
+
self.meta = {
|
| 77 |
+
"schema_version": "hand-warehouse/1.0", "dataset_id": "RHD",
|
| 78 |
+
"release_id": "shared-v1.0", "sequence_id": sequence, "camera_id": "camera",
|
| 79 |
+
"sample_type": "image", "num_frames": self.count,
|
| 80 |
+
"hand_slots": ["left", "right"], "split": split,
|
| 81 |
+
"split_scheme": "RHD_official_training_evaluation",
|
| 82 |
+
"split_source_locator": {"archive": "raw/data/" + archive, "member_prefix": split + "/"},
|
| 83 |
+
"sampling": {"type": "independent", "source_fps": None, "frames_ref": "camera/frames.jsonl",
|
| 84 |
+
"shard_max_images": 512,
|
| 85 |
+
"selection": "all source independent images sorted by source ID"},
|
| 86 |
+
"camera": {"model": "unknown", "schema_id": None, "image_size": size},
|
| 87 |
+
"components": {}, "storage_revision": "lossless-video-2026-09-18"}
|
| 88 |
+
self.frames = [{"frame_index": i, "source_frame_id": str(fid), "timestamp_ns": None,
|
| 89 |
+
"clock_domain": None, "source_locator": {**self.source, "source_frame_id": str(fid)}}
|
| 90 |
+
for i, fid in enumerate(frame_ids)]
|
| 91 |
+
|
| 92 |
+
@property
|
| 93 |
+
def p(self): return self.path
|
| 94 |
+
@property
|
| 95 |
+
def T(self): return self.count
|
| 96 |
+
@property
|
| 97 |
+
def m(self): return self.meta
|
| 98 |
+
|
| 99 |
+
def add(self, name, ref, schema, axes, valid, method="source values retained", **metadata):
|
| 100 |
+
valid_ref = Path(ref).with_name(Path(ref).stem + "_valid.pt").as_posix()
|
| 101 |
+
save_tensor(self.path / valid_ref, valid)
|
| 102 |
+
self.meta["components"][name] = {
|
| 103 |
+
"available": True, "schema_id": schema, "data_ref": ref, "axes": axes,
|
| 104 |
+
"valid_ref": valid_ref, "valid_axes": axes[:np.asarray(valid).ndim],
|
| 105 |
+
"provenance": {"kind": "format_conversion", "method": method},
|
| 106 |
+
"source_locator": dict(self.source), **metadata}
|
| 107 |
+
|
| 108 |
+
def array(self, name, ref, schema, value, valid, axes, **metadata):
|
| 109 |
+
value = np.asarray(value, np.float32).copy(); valid = np.asarray(valid, bool)
|
| 110 |
+
assert value.shape[:valid.ndim] == valid.shape and value.shape[0] == self.count
|
| 111 |
+
assert np.isfinite(value[valid]).all()
|
| 112 |
+
value[~valid] = np.nan; save_tensor(self.path / ref, value)
|
| 113 |
+
self.add(name, ref, schema, axes, valid, **metadata)
|
| 114 |
+
restored = torch.load(self.path / ref, map_location="cpu", weights_only=True).numpy()
|
| 115 |
+
assert np.array_equal(restored, value, equal_nan=True)
|
| 116 |
+
self.checks.append({"test": "tensor_serialization_exact", "file": ref,
|
| 117 |
+
"shape": list(value.shape), "valid_count": int(valid.sum())})
|
| 118 |
+
|
| 119 |
+
def intrinsic(self, value):
|
| 120 |
+
self.meta["camera"].update(model="pinhole", schema_id="camera/pinhole/v1")
|
| 121 |
+
self.array("intrinsic", "camera/intrinsic.pt", "camera/pinhole/v1", value,
|
| 122 |
+
np.ones(self.count, bool), ["T", "row", "column"])
|
| 123 |
+
|
| 124 |
+
def finish(self):
|
| 125 |
+
write_jsonl(self.path / "camera/frames.jsonl", self.frames)
|
| 126 |
+
save(self.path / "metainfo.json", self.meta)
|
| 127 |
+
save(TMP_ROOT / "checks" / f'{self.meta["sequence_id"]}__camera.checks.json',
|
| 128 |
+
{"checks": self.checks, "frames": self.count, "input": self.source})
|
| 129 |
+
|
| 130 |
+
def sha256(path):
|
| 131 |
+
h = hashlib.sha256()
|
| 132 |
+
with Path(path).open("rb") as stream:
|
| 133 |
+
for block in iter(lambda: stream.read(8 << 20), b""): h.update(block)
|
| 134 |
+
return h.hexdigest()
|
| 135 |
+
|
RHD/shared-v1.0/script/sequence_pilot_common.py
DELETED
|
@@ -1,53 +0,0 @@
|
|
| 1 |
-
"""Whole-selection conversion utilities. Never reads previous pilot outputs."""
|
| 2 |
-
from pilot_build import *
|
| 3 |
-
import hashlib
|
| 4 |
-
|
| 5 |
-
RELEASE='shared-sequence-v1.1'
|
| 6 |
-
|
| 7 |
-
class View:
|
| 8 |
-
def __init__(self,dataset,seq,cam,ids,size,source,kind='video',sampling='dense',split='unknown'):
|
| 9 |
-
self.root=ROOT/dataset/RELEASE;self.p=self.root/'data'/seq/cam
|
| 10 |
-
self.p.mkdir(parents=True,exist_ok=True);self.T=len(ids);self.source=source;self.checks=[]
|
| 11 |
-
self.m={'schema_version':'hand-warehouse/1.1','dataset_id':dataset,'release_id':RELEASE,'sequence_id':seq,'camera_id':cam,'sample_type':kind,'num_frames':self.T,'hand_slots':['left','right'],'sampling':{'type':'single' if kind=='image' else sampling,'source_fps':None,'frames_ref':'camera/frames.jsonl'},'camera':{'model':'unknown','schema_id':None,'image_size':size},'components':{},'split':split}
|
| 12 |
-
self.frames=[{'frame_index':i,'source_frame_id':str(fid),'timestamp_ns':None,'clock_domain':None,'source_locator':{**source,'source_frame_id':str(fid)}} for i,fid in enumerate(ids)]
|
| 13 |
-
def add(self,name,path,schema,axes,valid,method='source values retained',**kw):
|
| 14 |
-
vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix()
|
| 15 |
-
tensor(self.p/vp,valid)
|
| 16 |
-
self.m['components'][name]={'available':True,'schema_id':schema,'data_ref':path,'axes':axes,'valid_ref':vp,'valid_axes':axes[:valid.ndim],'provenance':{'kind':'format_conversion','method':method},'source_locator':self.source,**kw}
|
| 17 |
-
def array(self,name,path,schema,a,valid,axes,**kw):
|
| 18 |
-
a=np.asarray(a,np.float32).copy();valid=np.asarray(valid,bool)
|
| 19 |
-
assert a.shape[:valid.ndim]==valid.shape and a.shape[0]==self.T
|
| 20 |
-
assert np.isfinite(a[valid]).all(),name
|
| 21 |
-
a[~valid]=np.nan;tensor(self.p/path,a);self.add(name,path,schema,axes,valid,**kw)
|
| 22 |
-
restored=torch.load(self.p/path,map_location='cpu',weights_only=True).numpy()
|
| 23 |
-
for index in range(self.T):assert np.array_equal(restored[index],a[index],equal_nan=True)
|
| 24 |
-
self.checks.append({'test':'tensor_serialization_exact','file':path,'shape':list(a.shape),'valid_count':int(valid.sum())})
|
| 25 |
-
def video(self,name,path,iterator,mask=False,**kw):
|
| 26 |
-
w,h=self.m['camera']['image_size'];pix='gray16le' if mask else 'rgb24';dtype='<u2' if mask else 'uint8'
|
| 27 |
-
dst=self.p/path;dst.parent.mkdir(parents=True,exist_ok=True);hashes=[]
|
| 28 |
-
proc=subprocess.Popen([FF,'-v','error','-y','-f','rawvideo','-pixel_format',pix,'-video_size',f'{w}x{h}','-framerate','1','-i','pipe:0','-c:v','ffv1','-level','3','-g','1',str(dst)],stdin=subprocess.PIPE)
|
| 29 |
-
try:
|
| 30 |
-
for frame in iterator:
|
| 31 |
-
a=np.asarray(frame,dtype=dtype);assert a.shape==((h,w) if mask else (h,w,3));b=a.tobytes();hashes.append(hashlib.sha256(b).hexdigest());proc.stdin.write(b)
|
| 32 |
-
finally:proc.stdin.close()
|
| 33 |
-
assert proc.wait()==0 and len(hashes)==self.T
|
| 34 |
-
proc=subprocess.Popen([FF,'-v','error','-i',str(dst),'-f','rawvideo','-pix_fmt',pix,'pipe:1'],stdout=subprocess.PIPE)
|
| 35 |
-
nbytes=w*h*(2 if mask else 3)
|
| 36 |
-
for digest in hashes:
|
| 37 |
-
b=proc.stdout.read(nbytes);assert len(b)==nbytes and hashlib.sha256(b).hexdigest()==digest,'video roundtrip'
|
| 38 |
-
assert not proc.stdout.read(1);assert proc.wait()==0
|
| 39 |
-
self.checks.append({'test':'all_frames_pixel_exact_roundtrip','file':path,'frames':self.T})
|
| 40 |
-
self.add(name,path,'segment/uint16_labels/v1' if mask else 'rgb/uint8/v1',['T','height','width'] if mask else ['T','height','width','channel'],np.ones(self.T,bool),storage_fps=1,timebase_role='index_only',**kw)
|
| 41 |
-
def intrinsic(self,K):
|
| 42 |
-
self.m['camera'].update(model='pinhole',schema_id='camera/pinhole/v1')
|
| 43 |
-
self.array('intrinsic','camera/intrinsic.pt','camera/pinhole/v1',np.broadcast_to(K,(self.T,3,3)),np.ones(self.T,bool),['T','row','column'])
|
| 44 |
-
def finish(self):
|
| 45 |
-
lines(self.p/'camera/frames.jsonl',self.frames);save(self.p/'metainfo.json',self.m)
|
| 46 |
-
save(self.root/'doc'/f'{self.m["sequence_id"]}__{self.m["camera_id"]}.checks.json',{'checks':self.checks,'frames':self.T,'input':self.source})
|
| 47 |
-
print('Converted',self.m['dataset_id'],self.m['sequence_id'],self.m['camera_id'],self.T,flush=True)
|
| 48 |
-
|
| 49 |
-
def snapshot(dataset,scripts):
|
| 50 |
-
out=ROOT/dataset/RELEASE/'script';out.mkdir(parents=True,exist_ok=True)
|
| 51 |
-
names={'sequence_pilot_common.py','pilot_build.py','pilot_fetch.py','pilot_mano.py','pilot_hot_normalize.py','audit_source_fields.py',*scripts}
|
| 52 |
-
names.update(p.name for p in (WORK/'scripts').glob('sequence_pilot_*.py'))
|
| 53 |
-
for name in names:shutil.copyfile(WORK/'scripts'/name,out/name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
RHD/shared-v1.0/script/sequence_pilot_images.py
DELETED
|
@@ -1,53 +0,0 @@
|
|
| 1 |
-
"""Independent image batches converted directly from official ZIP members."""
|
| 2 |
-
from sequence_pilot_common import *
|
| 3 |
-
from pilot_mano import Mano
|
| 4 |
-
|
| 5 |
-
def freihand_joints(model,vertices):
|
| 6 |
-
j=model.data['J_regressor']@vertices
|
| 7 |
-
return np.stack([j[0],j[13],j[14],j[15],vertices[744],j[1],j[2],j[3],vertices[320],j[4],j[5],j[6],vertices[443],j[10],j[11],j[12],vertices[555],j[7],j[8],j[9],vertices[672]])
|
| 8 |
-
|
| 9 |
-
def frame_segment(v,mask,mapping,kind='semantic'):
|
| 10 |
-
lines(v.p/'annotation/segment/instances.jsonl',[{'frame_index':0,'labels':mapping}])
|
| 11 |
-
v.video('segment','annotation/segment/mask.mkv',[mask],mask=True,segmentation_type=kind,mapping_ref='annotation/segment/instances.jsonl',coverage={'kind':'full','scope':'native released label map'})
|
| 12 |
-
|
| 13 |
-
def freihand():
|
| 14 |
-
path=ROOT/'FreiHAND/raw/data/FreiHAND_pub_v2_eval.zip';model=Mano('right')
|
| 15 |
-
with zipfile.ZipFile(path) as z:
|
| 16 |
-
assert z.testzip() is None
|
| 17 |
-
K=json.loads(z.read('evaluation_K.json'));xyz=json.loads(z.read('evaluation_xyz.json'));theta=json.loads(z.read('evaluation_mano.json'))
|
| 18 |
-
for i in range(16):
|
| 19 |
-
rgb=np.asarray(Image.open(io.BytesIO(z.read(f'evaluation/rgb/{i:08d}.jpg'))).convert('RGB'));v=View('FreiHAND',f'evaluation_{i:08d}','camera',[i],[rgb.shape[1],rgb.shape[0]],{'archive':str(path.relative_to(WORK)),'sample_index':i},kind='image',split='test');v.video('rgb','observation/rgb.mkv',[rgb]);v.intrinsic(K[i])
|
| 20 |
-
kp=np.full((1,2,21,3),np.nan);kp[0,1]=xyz[i];valid=np.zeros((1,2,21),bool);valid[0,1]=True
|
| 21 |
-
v.array('keypoints_xyz','annotation/keypoints/xyz.pt','keypoints/xyz/v1',kp,valid,['T','hand','joint','coordinate'],unit='m',coordinate_frame='camera',keypoint_schema='mano21/v1')
|
| 22 |
-
a=np.asarray(theta[i]).reshape(-1);pose=a[:48].copy();pose[3:]+=model.data['hands_mean'];beta=a[48:58];verts,_,_=model.geometry(pose,beta);root=np.r_[a[58:60]-np.asarray(K[i])[:2,2],(K[i][0][0]+K[i][1][1])/2]/a[60];t=root-freihand_joints(model,verts[0])[9];motion=np.full((1,2,61),np.nan);motion[0,1]=np.r_[pose,beta,t]
|
| 23 |
-
v.array('mano','annotation/mano/motion.pt','mano/axis_angle61/v1',motion,[[False,True]],['T','hand','parameter'],unit='m',coordinate_frame='camera',angle_unit='rad',model_profile={'version':'MANO-v1.2','flat_hand_mean':True,'left_shapedirs_fix':False},method='nonflat mean expansion; native xyz middle MCP root alignment')
|
| 24 |
-
verts,_,_=model.geometry(pose,beta,t);pred=freihand_joints(model,verts[0]);err=np.linalg.norm(pred-np.asarray(xyz[i]),axis=-1);v.checks.append({'test':'MANO_vs_native_xyz','max_m':float(err.max()),'mean_m':float(err.mean())})
|
| 25 |
-
if err.max()>.001:v.m['semantic_review_required']=['MANO reconstruction discrepancy exceeds 1mm; inspect source model compatibility before accepting MANO component']
|
| 26 |
-
raw=np.asarray(Image.open(io.BytesIO(z.read(f'evaluation/segmap/{i:08d}.png'))));assert raw.ndim==2;mask=raw.astype(np.uint16);mask[raw==0]=65534
|
| 27 |
-
mappings=[{'mask_value':int(c),'category_id':'background' if c==65534 else f'freihand_label_{int(c)}','entity_id':None,'part_id':None,'source_instance_id':0 if c==65534 else int(c)} for c in np.unique(mask)]
|
| 28 |
-
v.m.setdefault('semantic_review_required',[]).append('segmap foreground codes preserved exactly; source part/category names require verification before cross-dataset semantic training')
|
| 29 |
-
frame_segment(v,mask,mappings);v.finish()
|
| 30 |
-
snapshot('FreiHAND',['sequence_pilot_images.py','pilot_mano.py'])
|
| 31 |
-
|
| 32 |
-
def rhd():
|
| 33 |
-
path=ROOT/'RHD/raw/data/RHD_v1-1.zip'
|
| 34 |
-
with zipfile.ZipFile(path) as z:
|
| 35 |
-
name=next(n for n in z.namelist() if n.endswith('evaluation/anno_evaluation.pickle'));prefix=name.rsplit('/',1)[0];a=Restricted(io.BytesIO(z.read(name)),encoding='latin1').load()
|
| 36 |
-
# Inspect official depth example, do not assume ray distance.
|
| 37 |
-
example=next(n for n in z.namelist() if n.endswith('view_samples.py'));text=z.read(example).decode();save(ROOT/'RHD'/RELEASE/'doc/depth_source.json',{'member':example,'source':text})
|
| 38 |
-
assert '2**16 - 1' in text and '5.0' in text
|
| 39 |
-
for i in range(16):
|
| 40 |
-
rgb=np.asarray(Image.open(io.BytesIO(z.read(f'{prefix}/color/{i:05d}.png'))).convert('RGB'));v=View('RHD',f'evaluation_{i:05d}','camera',[i],[320,320],{'archive':str(path.relative_to(WORK)),'annotation':name,'sample_index':i},kind='image',split='test');v.video('rgb','observation/rgb.mkv',[rgb]);v.intrinsic(a[i]['K'])
|
| 41 |
-
order=load(WORK/'schemas/hand-warehouse-1.1.json')['keypoints']['rhd21/v1']['source_index_map_per_hand']
|
| 42 |
-
for key,stem,n,unit in [('xyz','xyz',3,'m'),('uv_vis','uv',2,'pixel')]:
|
| 43 |
-
arr=np.asarray(a[i][key])[...,:n].reshape(1,2,21,n)[:,:,order];v.array('keypoints_'+stem,'annotation/keypoints/'+stem+'.pt','keypoints/'+stem+'/v1',arr,np.ones((1,2,21),bool),['T','hand','joint','coordinate'],unit=unit,keypoint_schema='rhd21/v1',coordinate_frame='camera' if n==3 else 'rgb_image',method='source tip-to-palm reordered to registered palm-to-tip order',source_index_map=order)
|
| 44 |
-
tensor(v.p/'annotation/keypoints/visibility.pt',a[i]['uv_vis'][:,2].reshape(1,2,21)[:,:,order].astype(bool));v.add('keypoints_visibility','annotation/keypoints/visibility.pt','visibility/bool/v1',['T','hand','joint'],np.ones((1,2,21),bool))
|
| 45 |
-
dep=np.asarray(Image.open(io.BytesIO(z.read(f'{prefix}/depth/{i:05d}.png'))),dtype=np.uint16);code=dep[:,:,0]*256+dep[:,:,1];depth=code.astype(np.float32)/65535*5
|
| 46 |
-
v.array('depth','observation/depth.pt','depth/z_float32/v1',depth[None],np.ones((1,320,320),bool),['T','height','width'],unit='m',depth_type='z',depth_origin='synthetic',method='official example: (R*256+G)/65535*5 metres')
|
| 47 |
-
raw=np.asarray(Image.open(io.BytesIO(z.read(f'{prefix}/mask/{i:05d}.png'))));mask=raw.astype(np.uint16);mask[raw==0]=65534
|
| 48 |
-
mappings=[{'mask_value':int(c),'category_id':'background' if c==65534 else ('person' if c==1 else 'hand'),'entity_id':None if c in [65534,1] else ('hand_left' if c<18 else 'hand_right'),'part_id':None if c in [65534,1] else f'rhd_{int(c)}','source_instance_id':0 if c==65534 else int(c)} for c in np.unique(mask)];frame_segment(v,mask,mappings)
|
| 49 |
-
p=np.asarray(a[i]['xyz'])@np.asarray(a[i]['K']).T;uv=p[:,:2]/p[:,2:];err=np.linalg.norm(uv-a[i]['uv_vis'][:,:2],axis=-1);v.checks.append({'test':'native_xyz_K_vs_uv','max_pixel':float(err.max()),'mean_pixel':float(err.mean())});v.finish()
|
| 50 |
-
snapshot('RHD',['sequence_pilot_images.py','pilot_mano.py'])
|
| 51 |
-
|
| 52 |
-
if __name__=='__main__':
|
| 53 |
-
p=argparse.ArgumentParser();p.add_argument('dataset',choices=['RHD','FreiHAND']);a=p.parse_args();{'RHD':rhd,'FreiHAND':freihand}[a.dataset]()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
RHD/shared-v1.0/script/validate_rhd.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Validate the adjacent RHD shared-v1.0 tree and fingerprint its current bytes."""
|
| 2 |
+
import argparse, hashlib, json
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from rhd_common import RELEASE_ROOT, TMP_ROOT, load, save
|
| 6 |
+
|
| 7 |
+
def main():
|
| 8 |
+
argparse.ArgumentParser(description='Validate the adjacent RHD shared-v1.0 release.').parse_args()
|
| 9 |
+
registry=load(RELEASE_ROOT/'doc/schema.json');counts={'training':0,'evaluation':0};seen=set();views=0
|
| 10 |
+
for path in sorted((RELEASE_ROOT/'data').glob('*/*/metainfo.json')):
|
| 11 |
+
meta=load(path);base=path.parent;total=meta['num_frames'];views+=1
|
| 12 |
+
for key in ['schema_version','split_scheme','split_source_locator','sampling','camera','components']:assert key in meta,(path,key)
|
| 13 |
+
assert meta['schema_version']=='hand-warehouse/1.0' and meta['dataset_id']=='RHD'
|
| 14 |
+
frames=[json.loads(line) for line in (base/'camera/frames.jsonl').read_text(encoding='utf-8').splitlines()]
|
| 15 |
+
assert len(frames)==total
|
| 16 |
+
for index,frame in enumerate(frames):
|
| 17 |
+
assert frame['frame_index']==index and frame['sample_id'] not in seen
|
| 18 |
+
seen.add(frame['sample_id']);split=frame['sample_id'].split('/')[1];counts[split]+=1
|
| 19 |
+
assert frame['source_locator']['annotation_index']==int(frame['source_frame_id'])
|
| 20 |
+
for name,component in meta['components'].items():
|
| 21 |
+
spec=registry['components'][component['schema_id']]
|
| 22 |
+
for key in ['available','data_ref','valid_ref','axes','valid_axes','provenance','source_locator',*spec.get('required_metadata',[])]:assert key in component,(path,name,key)
|
| 23 |
+
assert (base/component['data_ref']).is_file() and (base/component['valid_ref']).is_file()
|
| 24 |
+
if component['data_ref'].endswith('.pt'):
|
| 25 |
+
value=torch.load(base/component['data_ref'],weights_only=True).numpy();valid=torch.load(base/component['valid_ref'],weights_only=True).numpy()
|
| 26 |
+
assert value.dtype==np.float32 and valid.dtype==bool
|
| 27 |
+
assert list(value.shape)==[total if axis=='T' else axis for axis in spec['shape']]
|
| 28 |
+
assert list(valid.shape)==[total if axis=='T' else axis for axis in spec['valid_shape']]
|
| 29 |
+
assert np.isfinite(value[valid]).all()
|
| 30 |
+
else:
|
| 31 |
+
assert component['storage']['profile'] in spec['allowed_storage_profiles']
|
| 32 |
+
for key in registry['video_metadata']['required']:assert key in component['storage'],(name,key)
|
| 33 |
+
for attribute in component.get('attributes',{}).values():assert (base/attribute['data_ref']).is_file()
|
| 34 |
+
assert counts=={'training':41258,'evaluation':2728},counts
|
| 35 |
+
result={'passed':True,'views':views,'counts':counts,'schema_version':'hand-warehouse/1.0','scope':'current content and layout; does not independently prove official source correctness or visual quality'}
|
| 36 |
+
save(TMP_ROOT/'acceptance.json',result);manifest=[]
|
| 37 |
+
for path in sorted(RELEASE_ROOT.rglob('*')):
|
| 38 |
+
if not path.is_file() or '.cache' in path.parts:continue
|
| 39 |
+
digest=hashlib.sha256()
|
| 40 |
+
with path.open('rb') as stream:
|
| 41 |
+
for block in iter(lambda:stream.read(8<<20),b''):digest.update(block)
|
| 42 |
+
manifest.append({'path':path.relative_to(RELEASE_ROOT).as_posix(),'size':path.stat().st_size,'sha256':digest.hexdigest()})
|
| 43 |
+
save(TMP_ROOT/'files.sha256.json',{'scope':result['scope'],'files':manifest,'bytes':sum(x['size'] for x in manifest)})
|
| 44 |
+
print(json.dumps(result,ensure_ascii=False))
|
| 45 |
+
|
| 46 |
+
if __name__=='__main__':main()
|