Simplify FreiHAND shared-v1.0 scripts
Browse files- FreiHAND/shared-v1.0/script/archive_freihand_review.py +0 -59
- FreiHAND/shared-v1.0/script/convert_freihand_lossless.py +0 -123
- FreiHAND/shared-v1.0/script/freihand_production_preflight.py +0 -42
- FreiHAND/shared-v1.0/script/pilot_build.py +0 -209
- FreiHAND/shared-v1.0/script/pilot_fetch.py +0 -63
- FreiHAND/shared-v1.0/script/pilot_mano.py +0 -87
- FreiHAND/shared-v1.0/script/render_freihand_full_random_review.py +0 -71
- FreiHAND/shared-v1.0/script/render_freihand_review.py +0 -47
- FreiHAND/shared-v1.0/script/run_freihand_local.py +0 -23
- FreiHAND/shared-v1.0/script/sequence_pilot_common.py +0 -53
- FreiHAND/shared-v1.0/script/sequence_pilot_images.py +0 -53
- FreiHAND/shared-v1.0/script/validate_freihand_release.py +0 -45
FreiHAND/shared-v1.0/script/archive_freihand_review.py
DELETED
|
@@ -1,59 +0,0 @@
|
|
| 1 |
-
"""Archive a distributable human review report, not console/progress logs."""
|
| 2 |
-
from pathlib import Path
|
| 3 |
-
import json,hashlib,shutil,re
|
| 4 |
-
WORK=Path(__file__).resolve().parents[1]
|
| 5 |
-
OUT=Path('E:/hand-datasets/FreiHAND/shared-v1.0/doc/validation')
|
| 6 |
-
|
| 7 |
-
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
|
| 8 |
-
def main():
|
| 9 |
-
OUT.mkdir(parents=True,exist_ok=True)
|
| 10 |
-
source=OUT if (OUT/'index.html').exists() else WORK/'tmp/manual-review/preview'
|
| 11 |
-
for p in source.iterdir():
|
| 12 |
-
if (p.name=='index.html' or p.suffix.lower() in ['.png','.jpg']) and p.resolve()!=(OUT/p.name).resolve():shutil.copyfile(p,OUT/p.name)
|
| 13 |
-
rows=[];snapshots=[];tests=set()
|
| 14 |
-
root=WORK/'tmp/manual-review/FreiHAND'
|
| 15 |
-
for mp in sorted((root/'shared-v1.0/data').glob('*/*/metainfo.json')):
|
| 16 |
-
m=json.loads(mp.read_text());frames=[json.loads(l) for l in (mp.parent/'camera/frames.jsonl').read_text().splitlines()]
|
| 17 |
-
checks=json.loads((root/'tmp/production/checks'/f'{m["sequence_id"]}__{m["camera_id"]}.checks.json').read_text())
|
| 18 |
-
tests.update(c['test'] for c in checks['checks'])
|
| 19 |
-
for f in frames:rows.append((f['sample_id'],f['source_locator']['annotation_index'],f['image_variant']['variant_index']))
|
| 20 |
-
snapshots.append({'sample_ids':[f['sample_id'] for f in frames],'converted_files_sha256':{p.relative_to(mp.parent).as_posix():sha(p) for p in sorted(mp.parent.rglob('*')) if p.is_file()}})
|
| 21 |
-
assert len(rows)==15
|
| 22 |
-
evidence={'dataset':'FreiHAND','release':'shared-v1.0','schema_version':'hand-warehouse/1.0','scope':'15 selected images, not full release','human_review':'pending','full_release_validation':'not_completed','automated_checks_observed':sorted(tests),'preview_mask_vs_raw':'15 selected frames passed exact decoded-value comparison after native-bit-depth fix','scripts_sha256':{n:sha(WORK/'scripts'/n) for n in ['convert_freihand_lossless.py','render_freihand_review.py']},'reviewed_sample_snapshots':snapshots}
|
| 23 |
-
(OUT/'evidence.json').write_text(json.dumps(evidence,ensure_ascii=False,indent=2),encoding='utf8')
|
| 24 |
-
report='''# FreiHAND 核验报告(待人工确认)
|
| 25 |
-
|
| 26 |
-
[打开离线核验页面](index.html) · [核验范围与文件摘要](evidence.json)
|
| 27 |
-
|
| 28 |
-
## 当前结论
|
| 29 |
-
|
| 30 |
-
- 小样本转换自动检查通过;15 张预览的 mask 已与 raw 解码数值逐像素核对。
|
| 31 |
-
- **人工确认:待确认。全量验收:未完成。此报告不代表整套数据已通过验收。**
|
| 32 |
-
- 在人工确认前,全量转换及上传保持暂停。确认后应记录核验人、日期、结论和问题处理结果;全量完成后补充全量验收范围与结果。
|
| 33 |
-
|
| 34 |
-
## 范围和检查方法
|
| 35 |
-
|
| 36 |
-
12 张训练图覆盖三个基础样本的全部四种背景版本,另含三张评估图。选择是有目的的抽查,不是随机统计质量估计。FreiHAND 为独立图片,这里不验证视频时序。
|
| 37 |
-
|
| 38 |
-
自动检查包括 RGB 原 JPEG 码流及固定解码路径的像素一致性、分割值一致性、规范数组序列化和 MANO 根位置恢复。页面依次展示 RGB、分割叠加、源 XYZ 投影与转换 MANO 投影;可单独打开原 JPEG。人工检查关注图片/标注对应、左右手、方向、尺度、投影与分割边缘。
|
| 39 |
-
|
| 40 |
-
## 已知问题与边界
|
| 41 |
-
|
| 42 |
-
预览曾错误地让 FFmpeg 将 gray8 扩展为 gray16,强度被放大 257 倍,造成荧光绿色叠加。已改为按存储位深解码,再在数组中拓宽类型;15 个预览重新核对通过。该问题在预览读取端,保存的 mask 未因此改变。
|
| 43 |
-
|
| 44 |
-
MANO 拟合与原生 XYZ 允许存在源标注残差,不能要求完全重合。训练 JPEG mask 保留灰度,不二值化;评估区域图仅确认手/背景类别,不猜测细分手指名称。源 JSON 到规范 float32 的舍入与视频无损编码是两件事。
|
| 45 |
-
|
| 46 |
-
本报告只绑定 evidence.json 中的样本产物和脚本摘要;后续全量产物需另行验收,不能直接继承“通过”。HTML 和配图均为相对链接,下载整个 validation 目录即可离线查看,无需原始包、Python 或模型权重。配图仅为核验展示,不替代 observation 中的视频数据。
|
| 47 |
-
|
| 48 |
-
## 样本清单
|
| 49 |
-
|
| 50 |
-
| 样本 ID | 原标注索引 | 背景版本 |
|
| 51 |
-
|---|---:|---:|
|
| 52 |
-
'''
|
| 53 |
-
for sid,idx,var in rows:report+=f'| {sid} | {idx} | {var} |\n'
|
| 54 |
-
(OUT/'REPORT.md').write_text(report,encoding='utf8')
|
| 55 |
-
# Check every local dependency of the offline HTML.
|
| 56 |
-
text=(OUT/'index.html').read_text(encoding='utf8')
|
| 57 |
-
for ref in re.findall(r'(?:src|href)="([^"]+)"',text):assert (OUT/ref).is_file(),ref
|
| 58 |
-
print('Archived report with 15 samples; all HTML links resolve:',OUT)
|
| 59 |
-
if __name__=='__main__':main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
FreiHAND/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()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
FreiHAND/shared-v1.0/script/freihand_production_preflight.py
DELETED
|
@@ -1,42 +0,0 @@
|
|
| 1 |
-
"""Verify complete FreiHAND source archives before production conversion.
|
| 2 |
-
Reads archives in place; does not extract or delete source files.
|
| 3 |
-
"""
|
| 4 |
-
from pathlib import Path
|
| 5 |
-
import hashlib, json, zipfile, time
|
| 6 |
-
ROOT=Path(__file__).resolve().parents[1]
|
| 7 |
-
SOURCE=ROOT/'hand-datasets/FreiHAND/raw/data'
|
| 8 |
-
OUT=ROOT/'tmp/freihand-production/freihand-production-preflight.json'
|
| 9 |
-
|
| 10 |
-
def main():
|
| 11 |
-
OUT.parent.mkdir(parents=True,exist_ok=True)
|
| 12 |
-
report={'status':'checking','archives':[], 'target':'E:/hand-datasets/FreiHAND',
|
| 13 |
-
'release':'shared-v1.0','storage_revision':'lossless-video-2026-09-18'}
|
| 14 |
-
for filename in ['FreiHAND_pub_v2.zip','FreiHAND_pub_v2_eval.zip']:
|
| 15 |
-
p=SOURCE/filename
|
| 16 |
-
h=hashlib.sha256()
|
| 17 |
-
with p.open('rb') as f:
|
| 18 |
-
for block in iter(lambda:f.read(8*1024*1024),b''): h.update(block)
|
| 19 |
-
with zipfile.ZipFile(p) as z:
|
| 20 |
-
bad=z.testzip()
|
| 21 |
-
if bad: raise RuntimeError('ZIP CRC failure: '+bad)
|
| 22 |
-
names=z.namelist()
|
| 23 |
-
counts={prefix:sum(n.startswith(prefix) and not n.endswith('/') for n in names)
|
| 24 |
-
for prefix in ['training/rgb/','training/mask/','evaluation/rgb/','evaluation/segmap/','evaluation/anno/']}
|
| 25 |
-
arrays={n:len(json.loads(z.read(n))) for n in names if n in [
|
| 26 |
-
'training_K.json','training_mano.json','training_xyz.json',
|
| 27 |
-
'evaluation_K.json','evaluation_mano.json','evaluation_xyz.json']}
|
| 28 |
-
receipt=p.with_name(p.name+'.receipt.json')
|
| 29 |
-
known=json.loads(receipt.read_text(encoding='utf-8')) if receipt.exists() else {}
|
| 30 |
-
expected=known.get('sha256')
|
| 31 |
-
if expected and expected!=h.hexdigest(): raise RuntimeError('SHA256 changed: '+filename)
|
| 32 |
-
item={'file':filename,'bytes':p.stat().st_size,'sha256':h.hexdigest(),
|
| 33 |
-
'zip_crc':'passed_all_members','member_counts':counts,'array_lengths':arrays,
|
| 34 |
-
'local_receipt_sha256_matches':bool(expected),
|
| 35 |
-
'note':'Local receipt consistency is not an independent upstream checksum.'}
|
| 36 |
-
report['archives'].append(item)
|
| 37 |
-
OUT.write_text(json.dumps(report,indent=2),encoding='utf-8')
|
| 38 |
-
print(json.dumps(item),flush=True)
|
| 39 |
-
report['status']='raw_integrity_passed'
|
| 40 |
-
report['completed_at']=time.strftime('%Y-%m-%dT%H:%M:%S%z')
|
| 41 |
-
OUT.write_text(json.dumps(report,indent=2),encoding='utf-8')
|
| 42 |
-
if __name__=='__main__':main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
FreiHAND/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()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
FreiHAND/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()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
FreiHAND/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')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
FreiHAND/shared-v1.0/script/render_freihand_full_random_review.py
DELETED
|
@@ -1,71 +0,0 @@
|
|
| 1 |
-
"""Render local human review from actual converted tensors/videos; never uploads."""
|
| 2 |
-
from sequence_pilot_images import *
|
| 3 |
-
import html, random, hashlib
|
| 4 |
-
from collections import defaultdict
|
| 5 |
-
|
| 6 |
-
def main():
|
| 7 |
-
root=Path('E:/hand-datasets/FreiHAND/shared-v1.0');out=root/'doc/validation/full_random';out.mkdir(parents=True,exist_ok=True)
|
| 8 |
-
pools=defaultdict(list);selection=defaultdict(list);sample_records=[]
|
| 9 |
-
for mp in sorted((root/'data').glob('*/*/metainfo.json')):
|
| 10 |
-
for f in [json.loads(l) for l in (mp.parent/'camera/frames.jsonl').read_text().splitlines()]:
|
| 11 |
-
stratum='evaluation' if f['sample_id'].split('/')[1]=='evaluation' else 'training_variant_'+str(f['image_variant']['variant_index'])
|
| 12 |
-
pools[stratum].append((mp.parent.relative_to(root).as_posix(),f['frame_index']))
|
| 13 |
-
seed=20260918;rng=random.Random(seed)
|
| 14 |
-
for stratum in sorted(pools):
|
| 15 |
-
for view,idx in rng.sample(pools[stratum],6):selection[view].append(idx)
|
| 16 |
-
torch.set_num_threads(4)
|
| 17 |
-
model=Mano('right');cards=[];edges=[(0,1),(1,2),(2,3),(3,4),(0,5),(5,6),(6,7),(7,8),(0,9),(9,10),(10,11),(11,12),(0,13),(13,14),(14,15),(15,16),(0,17),(17,18),(18,19),(19,20)]
|
| 18 |
-
for mp in sorted((root/'data').glob('*/*/metainfo.json')):
|
| 19 |
-
m=load(mp);p=mp.parent;view=p.relative_to(root).as_posix()
|
| 20 |
-
if view not in selection:continue
|
| 21 |
-
indices=sorted(selection[view]);t=len(indices)
|
| 22 |
-
all_rows=[json.loads(l) for l in (p/'camera/frames.jsonl').read_text().splitlines()];rows=[all_rows[i] for i in indices]
|
| 23 |
-
expression='+'.join('eq(n\\,'+str(i)+')' for i in indices)
|
| 24 |
-
print('Reading full output',view,indices,flush=True)
|
| 25 |
-
def decode(path,pix,dtype,shape):
|
| 26 |
-
b=subprocess.check_output([FF,'-v','error','-i',str(path),'-vf','select='+expression,'-vsync','0','-frames:v',str(t),'-f','rawvideo','-pix_fmt',pix,'pipe:1']);return np.frombuffer(b,dtype=dtype).reshape(shape)
|
| 27 |
-
images=decode(p/'observation/rgb.mkv','rgb24',np.uint8,(t,224,224,3))
|
| 28 |
-
# FFmpeg gray8 -> gray16 rescales intensities by 257; decode native storage
|
| 29 |
-
# first and widen numerically in NumPy to preserve labels/intensities.
|
| 30 |
-
mask_pix=m['components']['segment']['storage']['pixel_format']
|
| 31 |
-
assert mask_pix in ['gray','gray16le']
|
| 32 |
-
masks=decode(p/'annotation/segment/mask.mkv',mask_pix,np.uint8 if mask_pix=='gray' else '<u2',(t,224,224)).astype(np.uint16)
|
| 33 |
-
motion=torch.load(p/'annotation/mano/motion.pt',weights_only=True).numpy()[indices];kp=torch.load(p/'annotation/keypoints/xyz.pt',weights_only=True).numpy()[indices];ks=torch.load(p/'camera/intrinsic.pt',weights_only=True).numpy()[indices]
|
| 34 |
-
verts,_,_=model.geometry(motion[:,1,:48],motion[:,1,48:58],motion[:,1,58:]);split='training' if m['split']=='train' else 'evaluation'
|
| 35 |
-
with zipfile.ZipFile(Path('E:/hand-datasets/FreiHAND/raw/data')/('FreiHAND_pub_v2.zip' if split=='training' else 'FreiHAND_pub_v2_eval.zip')) as z:
|
| 36 |
-
for i,frame in enumerate(rows):
|
| 37 |
-
rgb=images[i].copy();parts=[rgb.copy()];mask=masks[i]
|
| 38 |
-
source_mask_member=f'training/mask/{frame["source_locator"]["annotation_index"]:08d}.jpg' if split=='training' else f'evaluation/segmap/{int(frame["source_frame_id"]):08d}.png'
|
| 39 |
-
source_mask=np.asarray(Image.open(io.BytesIO(z.read(source_mask_member))))
|
| 40 |
-
if split=='training':
|
| 41 |
-
source_mask=source_mask[:,:,0];assert mask.max()<=255
|
| 42 |
-
else:
|
| 43 |
-
source_mask=source_mask.astype(np.uint16);source_mask[source_mask==0]=65534
|
| 44 |
-
assert np.array_equal(mask,source_mask),'Preview mask differs from decoded source'
|
| 45 |
-
weight=mask/255 if split=='training' else ((mask!=65534)&(mask!=65535)&(mask!=0)).astype(float)
|
| 46 |
-
colored=rgb.astype(float)*(1-.5*weight[:,:,None])+np.array([0,255,100])*.5*weight[:,:,None];parts.append(colored.clip(0,255).astype(np.uint8))
|
| 47 |
-
xyz=kp[i,1];uv=xyz@ks[i].T;uv=uv[:,:2]/uv[:,2:];joint_im=rgb.copy()
|
| 48 |
-
for a,b in edges:cv2.line(joint_im,tuple(np.round(uv[a]).astype(int)),tuple(np.round(uv[b]).astype(int)),(255,230,0),1,cv2.LINE_AA)
|
| 49 |
-
for j,(x,y) in enumerate(uv):cv2.circle(joint_im,(round(float(x)),round(float(y))),2,(255,30,50),-1)
|
| 50 |
-
parts.append(joint_im);uv=verts[i]@ks[i].T;uv=uv[:,:2]/uv[:,2:];mesh_im=rgb.copy()
|
| 51 |
-
for face in model.data['f']:cv2.polylines(mesh_im,[np.round(uv[face]).astype(np.int32)],True,(50,220,255),1,cv2.LINE_AA)
|
| 52 |
-
parts.append(mesh_im)
|
| 53 |
-
canvas=Image.new('RGB',(896,250),'white');draw=ImageDraw.Draw(canvas)
|
| 54 |
-
for k,(im,title) in enumerate(zip(parts,['RGB (source JPEG copied)','Source segmentation','Native XYZ projected','Converted MANO projected'])):
|
| 55 |
-
canvas.paste(Image.fromarray(im),(k*224,26));draw.text((k*224+4,7),title,fill='black')
|
| 56 |
-
name=frame['sample_id'].replace('/','_')+'.png';canvas.save(out/name)
|
| 57 |
-
sample_records.append({'sample_id':frame['sample_id'],'view':view,'frame_index':frame['frame_index'],'annotation_index':frame['source_locator']['annotation_index'],'variant_index':frame['image_variant']['variant_index'],'preview':name,'rgb_decoded_sha256':hashlib.sha256(rgb.tobytes()).hexdigest(),'mask_uint16_sha256':hashlib.sha256(mask.astype('<u2').tobytes()).hexdigest(),'raw_mask_comparison':'passed'})
|
| 58 |
-
# Unmodified JPEG reference alongside the panel, for browser inspection.
|
| 59 |
-
rawname=name.replace('.png','_source.jpg');(out/rawname).write_bytes(z.read(frame['source_locator']['member']))
|
| 60 |
-
cards.append(f'<section><h2>{html.escape(frame["sample_id"])}</h2><p>Source annotation index: {frame["source_locator"]["annotation_index"]}; variant: {frame["image_variant"]["variant_index"]}. <a href="{rawname}">Original JPEG</a></p><img src="{name}" width="896"></section>')
|
| 61 |
-
text='''<!doctype html><meta charset="utf-8"><title>FreiHAND 全量随机抽查</title><style>body{font:16px system-ui;max-width:1100px;margin:32px auto;background:#f5f6f8;color:#19222f}section{background:white;padding:16px;margin:20px 0;border-radius:8px}img{max-width:100%;height:auto}li{margin:8px 0}</style><h1>FreiHAND:全量产物随机抽查</h1><p>从完整 134,200 张产物中分层随机选取 30 张:四种训练背景版本及评估集各 6 张。随机种子 20260918;分层等额抽样,不按全体样本占比加权,不能估计总体错误率。尚待人工确认。每行依次为 RGB、分割叠加、源 XYZ 投影、转换 MANO 投影。原始 JPEG 可单独打开。</p><ul><li>检查图片与标注是否同一只手、同一姿态;左右手、镜像、坐标尺度与相机方向是否合理。</li><li>检查分割边缘、前景范围和训练背景变体的对应关系;训练灰度保留原强度,未阈值化。</li><li>检查关键点顺序与投影;MANO 是拟合标注,不能要求与源 XYZ 完全重合。明显整体偏移、缩放或旋转须反馈。</li><li>检查原图细节是否一致。此页面用于视觉检查,编码数值一致性由转换器逐值验证。</li><li>请确认这份全量随机抽查结果,或指出样本 ID 和问题;确认前不上传。</li></ul>'''+''.join(cards)
|
| 62 |
-
(out/'index.html').write_text(text,encoding='utf8')
|
| 63 |
-
save(out/'samples.json',{'seed':seed,'method':'Python random.Random; sample without replacement separately in each sorted stratum; 6 per stratum','population_sizes':{k:len(v) for k,v in pools.items()},'human_review':'pending','source':'actual completed shared-v1.0 data, not pilot outputs','samples':sample_records})
|
| 64 |
-
assert len(sample_records)==30 and len({x['sample_id'] for x in sample_records})==30
|
| 65 |
-
report='# FreiHAND 全量产物随机抽查报告\n\n[打开离线预览](index.html) · [抽样清单及可复现参数](samples.json)\n\n全量共 134,200 张;按训练背景版本 0–3 与评估集分成五层,各随机抽取 6 张,共 30 张,种子为 20260918。属于分层等额随机抽样,不是总体均匀抽样,不据此估计全量错误率。样本来自已完成的 4096 张分片产物,直接读取其视频、相机及标注数组,未重新转换试点。\n\n每个选中 mask 均再次与 raw 对应帧逐值比较,通过后生成图。关键点和 MANO 使用全量产物数组投影;MANO 拟合不要求与源关键点无残差。自动检查通过不代表人工确认通过。\n\n**人工确认:待确认。尚未上传。**\n\n检查图片与标注对应、背景版本、分割边缘、关键点顺序及 MANO 投影;反馈样本 ID 即可。HTML 及配图使用相对链接,可下载后离线查看。\n'
|
| 66 |
-
(out/'REPORT.md').write_text(report,encoding='utf8')
|
| 67 |
-
parent_report=root/'doc/validation/REPORT.md';parent_text=parent_report.read_text(encoding='utf8')
|
| 68 |
-
if 'full_random/REPORT.md' not in parent_text:parent_report.write_text(parent_text+'\n\n## 全量随机抽查\n\n[查看独立随机抽查报告](full_random/REPORT.md) · [打开 30 张随机样本预览](full_random/index.html)。本次从全量产物抽取,人工确认待完成。\n',encoding='utf8')
|
| 69 |
-
evidence=root/'doc/validation/evidence.json';d=load(evidence);d['full_release_validation']['random_review_ref']='full_random/samples.json';save(evidence,d)
|
| 70 |
-
print(out/'index.html')
|
| 71 |
-
if __name__=='__main__':main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
FreiHAND/shared-v1.0/script/render_freihand_review.py
DELETED
|
@@ -1,47 +0,0 @@
|
|
| 1 |
-
"""Render local human review from actual converted tensors/videos; never uploads."""
|
| 2 |
-
from sequence_pilot_images import *
|
| 3 |
-
import html
|
| 4 |
-
|
| 5 |
-
def main():
|
| 6 |
-
root=WORK/'tmp/manual-review/FreiHAND/shared-v1.0';out=Path('E:/hand-datasets/FreiHAND/shared-v1.0/doc/validation');out.mkdir(parents=True,exist_ok=True)
|
| 7 |
-
model=Mano('right');cards=[];edges=[(0,1),(1,2),(2,3),(3,4),(0,5),(5,6),(6,7),(7,8),(0,9),(9,10),(10,11),(11,12),(0,13),(13,14),(14,15),(15,16),(0,17),(17,18),(18,19),(19,20)]
|
| 8 |
-
for mp in sorted((root/'data').glob('*/*/metainfo.json')):
|
| 9 |
-
m=load(mp);p=mp.parent;t=m['num_frames'];rows=[json.loads(l) for l in (p/'camera/frames.jsonl').read_text().splitlines()]
|
| 10 |
-
def decode(path,pix,dtype,shape):
|
| 11 |
-
b=subprocess.check_output([FF,'-v','error','-i',str(path),'-f','rawvideo','-pix_fmt',pix,'pipe:1']);return np.frombuffer(b,dtype=dtype).reshape(shape)
|
| 12 |
-
images=decode(p/'observation/rgb.mkv','rgb24',np.uint8,(t,224,224,3))
|
| 13 |
-
# FFmpeg gray8 -> gray16 rescales intensities by 257; decode native storage
|
| 14 |
-
# first and widen numerically in NumPy to preserve labels/intensities.
|
| 15 |
-
mask_pix=m['components']['segment']['storage']['pixel_format']
|
| 16 |
-
assert mask_pix in ['gray','gray16le']
|
| 17 |
-
masks=decode(p/'annotation/segment/mask.mkv',mask_pix,np.uint8 if mask_pix=='gray' else '<u2',(t,224,224)).astype(np.uint16)
|
| 18 |
-
motion=torch.load(p/'annotation/mano/motion.pt',weights_only=True).numpy();kp=torch.load(p/'annotation/keypoints/xyz.pt',weights_only=True).numpy();ks=torch.load(p/'camera/intrinsic.pt',weights_only=True).numpy()
|
| 19 |
-
verts,_,_=model.geometry(motion[:,1,:48],motion[:,1,48:58],motion[:,1,58:]);split='training' if m['split']=='train' else 'evaluation'
|
| 20 |
-
with zipfile.ZipFile(Path('E:/hand-datasets/FreiHAND/raw/data')/('FreiHAND_pub_v2.zip' if split=='training' else 'FreiHAND_pub_v2_eval.zip')) as z:
|
| 21 |
-
for i,frame in enumerate(rows):
|
| 22 |
-
rgb=images[i].copy();parts=[rgb.copy()];mask=masks[i]
|
| 23 |
-
source_mask_member=f'training/mask/{frame["source_locator"]["annotation_index"]:08d}.jpg' if split=='training' else f'evaluation/segmap/{int(frame["source_frame_id"]):08d}.png'
|
| 24 |
-
source_mask=np.asarray(Image.open(io.BytesIO(z.read(source_mask_member))))
|
| 25 |
-
if split=='training':
|
| 26 |
-
source_mask=source_mask[:,:,0];assert mask.max()<=255
|
| 27 |
-
else:
|
| 28 |
-
source_mask=source_mask.astype(np.uint16);source_mask[source_mask==0]=65534
|
| 29 |
-
assert np.array_equal(mask,source_mask),'Preview mask differs from decoded source'
|
| 30 |
-
weight=mask/255 if split=='training' else ((mask!=65534)&(mask!=65535)&(mask!=0)).astype(float)
|
| 31 |
-
colored=rgb.astype(float)*(1-.5*weight[:,:,None])+np.array([0,255,100])*.5*weight[:,:,None];parts.append(colored.clip(0,255).astype(np.uint8))
|
| 32 |
-
xyz=kp[i,1];uv=xyz@ks[i].T;uv=uv[:,:2]/uv[:,2:];joint_im=rgb.copy()
|
| 33 |
-
for a,b in edges:cv2.line(joint_im,tuple(np.round(uv[a]).astype(int)),tuple(np.round(uv[b]).astype(int)),(255,230,0),1,cv2.LINE_AA)
|
| 34 |
-
for j,(x,y) in enumerate(uv):cv2.circle(joint_im,(round(float(x)),round(float(y))),2,(255,30,50),-1)
|
| 35 |
-
parts.append(joint_im);uv=verts[i]@ks[i].T;uv=uv[:,:2]/uv[:,2:];mesh_im=rgb.copy()
|
| 36 |
-
for face in model.data['f']:cv2.polylines(mesh_im,[np.round(uv[face]).astype(np.int32)],True,(50,220,255),1,cv2.LINE_AA)
|
| 37 |
-
parts.append(mesh_im)
|
| 38 |
-
canvas=Image.new('RGB',(896,250),'white');draw=ImageDraw.Draw(canvas)
|
| 39 |
-
for k,(im,title) in enumerate(zip(parts,['RGB (source JPEG copied)','Source segmentation','Native XYZ projected','Converted MANO projected'])):
|
| 40 |
-
canvas.paste(Image.fromarray(im),(k*224,26));draw.text((k*224+4,7),title,fill='black')
|
| 41 |
-
name=frame['sample_id'].replace('/','_')+'.png';canvas.save(out/name)
|
| 42 |
-
# Unmodified JPEG reference alongside the panel, for browser inspection.
|
| 43 |
-
rawname=name.replace('.png','_source.jpg');(out/rawname).write_bytes(z.read(frame['source_locator']['member']))
|
| 44 |
-
cards.append(f'<section><h2>{html.escape(frame["sample_id"])}</h2><p>Source annotation index: {frame["source_locator"]["annotation_index"]}; variant: {frame["image_variant"]["variant_index"]}. <a href="{rawname}">Original JPEG</a></p><img src="{name}" width="896"></section>')
|
| 45 |
-
text='''<!doctype html><meta charset="utf-8"><title>FreiHAND 本地人工核验</title><style>body{font:16px system-ui;max-width:1100px;margin:32px auto;background:#f5f6f8;color:#19222f}section{background:white;padding:16px;margin:20px 0;border-radius:8px}img{max-width:100%;height:auto}li{margin:8px 0}</style><h1>FreiHAND:预处理前本地人工核验</h1><p>15 个实际转换样本;尚未人工验收,不代表全量质量通过。每行依次为 RGB、分割叠加、源 XYZ 投影、转换 MANO 投影。原始 JPEG 可单独打开。</p><ul><li>检查图片与标注是否同一只手、同一姿态;左右手、镜像、坐标尺度与相机方向是否合理。</li><li>检查分割边缘、前景范围和训练背景变体的对应关系;训练灰度保留原强度,未阈值化。</li><li>检查关键点顺序与投影;MANO 是拟合标注,不能要求与源 XYZ 完全重合。明显整体偏移��缩放或旋转须反馈。</li><li>检查原图细节是否一致。此页面用于视觉检查,编码数值一致性由转换器逐值验证。</li><li>请在对话中明确通过或指出样本 ID 和问题;通过前不恢复全量转换,不上传。</li></ul>'''+''.join(cards)
|
| 46 |
-
(out/'index.html').write_text(text,encoding='utf8');print(out/'index.html')
|
| 47 |
-
if __name__=='__main__':main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
FreiHAND/shared-v1.0/script/run_freihand_local.py
DELETED
|
@@ -1,23 +0,0 @@
|
|
| 1 |
-
"""Approved full FreiHAND conversion followed by local acceptance; no upload or raw deletion."""
|
| 2 |
-
from pathlib import Path
|
| 3 |
-
import subprocess,sys,json,shutil,datetime
|
| 4 |
-
WORK=Path(__file__).resolve().parents[1]
|
| 5 |
-
BASE=Path('E:/hand-datasets/FreiHAND');RELEASE=BASE/'shared-v1.0'
|
| 6 |
-
|
| 7 |
-
def main():
|
| 8 |
-
evidence=RELEASE/'doc/validation/evidence.json'
|
| 9 |
-
assert json.loads(evidence.read_text(encoding='utf8'))['human_review']=='approved'
|
| 10 |
-
subprocess.run([sys.executable,str(WORK/'scripts/convert_freihand_lossless.py'),'--output','E:/hand-datasets','--source',str(BASE/'raw/data'),'--batch-size','4096','--human-reviewed'],check=True,cwd=WORK)
|
| 11 |
-
subprocess.run([sys.executable,str(WORK/'scripts/validate_freihand_release.py'),str(RELEASE)],check=True,cwd=WORK)
|
| 12 |
-
result=json.loads((BASE/'tmp/production/acceptance.json').read_text())
|
| 13 |
-
assert result['passed'] and result['full_release'] and result['views']==33
|
| 14 |
-
d=json.loads(evidence.read_text(encoding='utf8'));d['full_release_validation']={'automated':'passed','views':result['views'],'counts':result['counts'],'completed_at_local':datetime.datetime.now().isoformat(timespec='seconds'),'full_release_spot_review':'pending','upload':'not_started'}
|
| 15 |
-
evidence.write_text(json.dumps(d,ensure_ascii=False,indent=2),encoding='utf8')
|
| 16 |
-
with (RELEASE/'doc/validation/REPORT.md').open('a',encoding='utf8') as f:
|
| 17 |
-
f.write('\n\n## 全量自动验收\n\n4096 张上限的 33 个分片已完成转换及本地自动验收:130,240 张训练图片、3,960 张评估图片。逐批 RGB 码流/像素及 mask 数值核对通过,数组与规范登记、帧索引和样本唯一性检查通过。\n\n全量追加人工抽查尚未完成,尚未上传。小样本人工通过不替代此步骤。运行日志仍只放 tmp。\n')
|
| 18 |
-
target=RELEASE/'script';target.mkdir(exist_ok=True)
|
| 19 |
-
for name in ['convert_freihand_lossless.py','validate_freihand_release.py','render_freihand_review.py','archive_freihand_review.py','run_freihand_local.py','render_freihand_full_random_review.py','sequence_pilot_images.py','sequence_pilot_common.py','pilot_build.py','pilot_fetch.py','pilot_mano.py']:shutil.copyfile(WORK/'scripts'/name,target/name)
|
| 20 |
-
for name in ['CONTRACT.md','schema.json']:shutil.copyfile(WORK/'distribution/hand-warehouse-1.0'/name,RELEASE/'doc'/name)
|
| 21 |
-
subprocess.run([sys.executable,str(WORK/'scripts/render_freihand_full_random_review.py')],check=True,cwd=WORK)
|
| 22 |
-
print('LOCAL_FULL_ACCEPTANCE_PASSED: 33 shards; upload not started; raw retained.',flush=True)
|
| 23 |
-
if __name__=='__main__':main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
FreiHAND/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)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
FreiHAND/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]()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
FreiHAND/shared-v1.0/script/validate_freihand_release.py
DELETED
|
@@ -1,45 +0,0 @@
|
|
| 1 |
-
"""Check the exact v1.0 registry and FreiHAND release counts; hash all payload files."""
|
| 2 |
-
from sequence_pilot_common import *
|
| 3 |
-
|
| 4 |
-
def main():
|
| 5 |
-
p=argparse.ArgumentParser();p.add_argument('release',type=Path);p.add_argument('--partial',action='store_true');a=p.parse_args()
|
| 6 |
-
registry=load(WORK/'distribution/hand-warehouse-1.0/schema.json');counts={'training':0,'evaluation':0};seen=set();views=0
|
| 7 |
-
for path in sorted((a.release/'data').glob('*/*/metainfo.json')):
|
| 8 |
-
m=load(path);base=path.parent;t=m['num_frames'];views+=1
|
| 9 |
-
for key in ['schema_version','split_scheme','split_source_locator','sampling','camera','components']:assert key in m,(path,key)
|
| 10 |
-
assert m['schema_version']=='hand-warehouse/1.0'
|
| 11 |
-
frames=[json.loads(l) for l in (base/'camera/frames.jsonl').read_text().splitlines()]
|
| 12 |
-
assert len(frames)==t
|
| 13 |
-
for i,frame in enumerate(frames):
|
| 14 |
-
assert frame['frame_index']==i and frame['sample_id'] not in seen
|
| 15 |
-
seen.add(frame['sample_id']);counts[frame['sample_id'].split('/')[1]]+=1
|
| 16 |
-
assert frame['source_locator']['annotation_index']==int(frame['source_frame_id'])%(32560 if frame['sample_id'].split('/')[1]=='training' else 3960)
|
| 17 |
-
for name,c in m['components'].items():
|
| 18 |
-
definition=registry['components'][c['schema_id']]
|
| 19 |
-
for key in ['available','data_ref','axes','valid_ref','valid_axes','provenance','source_locator',*definition.get('required_metadata',[])]:assert key in c,(path,name,key)
|
| 20 |
-
assert (base/c['data_ref']).is_file()
|
| 21 |
-
valid=torch.load(base/c['valid_ref'],weights_only=True).numpy();assert valid.dtype==bool
|
| 22 |
-
shape=[t if x=='T' else x for x in definition['valid_shape']];assert list(valid.shape)==shape
|
| 23 |
-
if c['data_ref'].endswith('.pt'):
|
| 24 |
-
arr=torch.load(base/c['data_ref'],weights_only=True).numpy()
|
| 25 |
-
assert arr.dtype==np.float32
|
| 26 |
-
assert list(arr.shape)==[t if x=='T' else x for x in definition['shape']]
|
| 27 |
-
assert np.isfinite(arr[valid]).all() and np.isnan(arr[~valid]).all()
|
| 28 |
-
else:
|
| 29 |
-
assert c['storage']['profile'] in definition['allowed_storage_profiles']
|
| 30 |
-
for key in registry['video_metadata']['required']:assert key in c['storage'],(name,key)
|
| 31 |
-
checks=load((a.release.parent/'tmp/production/checks')/f'{m["sequence_id"]}__{m["camera_id"]}.checks.json')['checks']
|
| 32 |
-
assert any(c['test']=='all_rgb_packets_and_decoded_pixels_exact' for c in checks)
|
| 33 |
-
assert any(c['test']=='all_mask_values_exact' for c in checks)
|
| 34 |
-
if not a.partial:assert counts=={'training':130240,'evaluation':3960},counts
|
| 35 |
-
results={'passed':True,'full_release':not a.partial,'views':views,'counts':counts,'schema_version':'hand-warehouse/1.0'}
|
| 36 |
-
report=a.release.parent/'tmp/production';report.mkdir(parents=True,exist_ok=True)
|
| 37 |
-
save(report/'acceptance.json',results)
|
| 38 |
-
manifest=[]
|
| 39 |
-
for path in sorted(a.release.rglob('*')):
|
| 40 |
-
if not path.is_file() or path.name=='files.sha256.json' or '.cache' in path.parts:continue
|
| 41 |
-
b=path.read_bytes();manifest.append({'path':path.relative_to(a.release).as_posix(),'size':len(b),'sha256':hashlib.sha256(b).hexdigest(),'git_blob_sha1':hashlib.sha1(b'blob '+str(len(b)).encode()+b'\0'+b).hexdigest()})
|
| 42 |
-
save(report/'files.sha256.json',{'files':manifest,'bytes':sum(x['size'] for x in manifest)})
|
| 43 |
-
print(json.dumps(results),flush=True)
|
| 44 |
-
if __name__=='__main__':main()
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|