"""Convert the official RHD ZIP into the adjacent shared-v1.0 release.""" from rhd_common import * from PIL import Image import argparse, io, zipfile def media(v,name,path,raw,pix,size,profile,codec='ffv1',options=None): dst=v.p/path;dst.parent.mkdir(parents=True,exist_ok=True);options=options or ['-level','3'] 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) restored=ff(['-i',str(dst),'-f','rawvideo','-pix_fmt',pix,'pipe:1']);assert restored==raw,name v.checks.append({'test':'all_media_bytes_exact','component':name,'frames':v.T}) actual_pix='bgr0' if codec=='ffv1' and pix=='rgb24' else ('gbrp' if codec=='libx264rgb' else pix) return storage(profile,codec,actual_pix,size,False,options),restored def main(): argparse.ArgumentParser(description='Convert RHD raw into the adjacent shared-v1.0 release.').parse_args() torch.set_num_threads(4);root=RELEASE_ROOT order=load(root/'doc/schema.json')['keypoints']['rhd21/v1']['source_index_map_per_hand'];reports=[] with zipfile.ZipFile(RAW_ROOT/'RHD_v1-1.zip') as z: for split,total in [('training',41258),('evaluation',2728)]: member=next(n for n in z.namelist() if n.endswith(f'{split}/anno_{split}.pickle'));prefix=member.rsplit('/',1)[0] anno=Restricted(io.BytesIO(z.read(member)),encoding='latin1').load();all_ids=sorted(anno);assert len(all_ids)==total for offset in range(0,total,512): ids=all_ids[offset:offset+512];t=len(ids) sequence=f'{split}_{offset:08d}';complete=root/'data'/sequence/'camera/metainfo.json' if complete.is_file(): 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'] 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}') reports.append({'split':split,'frames':t,'sequence':sequence,'status':'already_complete'});continue 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') v.m.update(schema_version='hand-warehouse/1.0',view_type='exo',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') v.m['sampling'].update(type='independent',selection='all source independent images sorted by source ID',shard_max_images=512) 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') rgb=np.stack([np.asarray(Image.open(io.BytesIO(z.read(f'{prefix}/color/{i:05d}.png'))).convert('RGB')) for i in ids]) rgbstore,_=media(v,'rgb','observation/rgb.mkv',rgb.tobytes(),'rgb24',[320,320],'mkv/ffv1_rgb/v1') 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']) candidate['pixel_format']='gbrp' sizes={'ffv1':(v.p/'observation/rgb.mkv').stat().st_size,'h264_rgb_lossless':other.stat().st_size} if other.stat().st_size<(v.p/'observation/rgb.mkv').stat().st_size:other.replace(v.p/'observation/rgb.mkv');rgbstore=candidate else:other.unlink() 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') v.intrinsic(np.stack([anno[i]['K'] for i in ids])) for key,stem,n,unit in [('xyz','xyz',3,'m'),('uv_vis','uv',2,'pixel')]: 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) 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) 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} for k in ['keypoints_xyz','keypoints_uv']:v.m['components'][k]['attributes']={'visibility':attribute} deps=[];masks=[];mapping=[] for fi,i in enumerate(ids): 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) 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) 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)]}) depth=np.stack(deps).astype('>16).astype('