File size: 6,507 Bytes
10ed3aa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | #!/usr/bin/env python3
"""Inspect the new reader against RGB without recomputing labels or MANO meshes.
Displays object coordinate origins and MANO translation anchors, NOT masks or
hand joints. Optional old-reader comparison checks displayed pixels exactly.
"""
import argparse
import hashlib
import json
from pathlib import Path
import subprocess
import numpy as np
from PIL import Image, ImageDraw
import torch
from hot3d_bundle import Reader, at, fields
def project(points, params, max_angle):
"""Same Fisheye624 diagnostic formula as pinned v1.0 fresh_sequence_common."""
xyz=np.asarray(points,dtype=np.float64)
uv=np.full((len(xyz),2),np.nan)
good=np.isfinite(xyz).all(1)&(xyz[:,2]>1e-6)
p=np.asarray(params);xy=xyz[good,:2]/xyz[good,2,None]
r=np.linalg.norm(xy,axis=1);th=np.arctan(r)
radial=th*(1+sum(p[3+i]*th**(2*i+2) for i in range(6)))
xy=xy*np.divide(radial,r,out=np.ones_like(r),where=r>1e-12)[:,None]
x,y=xy.T;rr=x*x+y*y
xd=x+(2*x*x+rr)*p[9]+2*x*y*p[10]+p[11]*rr+p[12]*rr*rr
yd=y+(2*y*y+rr)*p[10]+2*x*y*p[9]+p[13]*rr+p[14]*rr*rr
uv[good]=p[0]*np.stack([xd,yd],1)+p[1:3]
angle=np.arctan2(np.linalg.norm(xyz[:,:2],axis=1),xyz[:,2])
uv[angle>max_angle]=np.nan
return uv
def anchors(meta, tensors, index):
points=[];names=[];colors=[]
if 'mano' in tensors:
data,valid=tensors['mano']
for side,(name,color) in enumerate([('L trans',(255,80,110)),('R trans',(70,210,255))]):
if valid[index,side]:points.append(data[index,side,58:61]);names.append(name);colors.append(color)
for name,(data,valid) in tensors.items():
if name.startswith('object_') and name.endswith('_pose') and valid[index]:
points.append(data[index,:3,3]);names.append(name[7:-5][-5:]);colors.append((245,215,65))
return np.asarray(points).reshape(-1,3),names,colors
def draw(rgb, xy, names, colors):
image=Image.fromarray(rgb.copy());d=ImageDraw.Draw(image)
for (x,y),name,color in zip(xy,names,colors):
if not np.isfinite([x,y]).all() or not (0<=x<image.width and 0<=y<image.height):continue
x,y=int(round(x)),int(round(y))
d.ellipse((x-5,y-5,x+5,y+5),outline=color,width=3);d.text((x+7,y),name,fill=color)
return image
def run(view,video,out,source=None):
torch.set_num_threads(1);view=Path(view);out=Path(out);out.mkdir(parents=True,exist_ok=True)
reader=Reader(view);meta=reader.meta;total=meta['num_frames'];w,h=meta['camera']['image_size']
new={};old={};before=json.loads((Path(source)/'metainfo.json').read_text()) if source else None
for field in fields(meta):
if len(field['locator'])!=2:continue
name=field['locator'][1];new[name]=tuple(x.numpy() for x in reader.numeric(field))
if source:
c=at(before,field['locator']);old[name]=tuple(torch.load(Path(source)/c[k],map_location='cpu',weights_only=True).numpy() for k in ['data_ref','valid_ref'])
indices=sorted({0,1,total//4,total//2,3*total//4,total-1})
# Decode the entire original stream in order, no seek/timestamp sampling.
command=['ffmpeg','-nostdin','-v','error','-threads','1','-noautorotate','-i',str(video),
'-map','0:v:0','-fps_mode','passthrough','-f','rawvideo','-pix_fmt','rgb24','-threads','1','pipe:1']
decoded_sha=hashlib.sha256();rows=[];count=0
with (out/'decode.log').open('w') as log:
proc=subprocess.Popen(command,stdout=subprocess.PIPE,stderr=log)
try:
while True:
chunk=proc.stdout.read(w*h*3)
if not chunk:break
if len(chunk)!=w*h*3:raise ValueError('Truncated decoded frame')
decoded_sha.update(chunk)
if count in indices:
rgb=np.frombuffer(chunk,np.uint8).reshape(h,w,3)
points,names,colors=anchors(meta,new,count)
uv=project(points,new['intrinsic'][0][count],meta['camera']['max_solid_angle'])
revised=draw(rgb,uv,names,colors)
if source:
oldpoints,oldnames,oldcolors=anchors(before,old,count)
olduv=project(oldpoints,old['intrinsic'][0][count],before['camera']['max_solid_angle'])
previous=draw(rgb,olduv,oldnames,oldcolors)
if previous.tobytes()!=revised.tobytes():raise ValueError('Old/new diagnostic pixels differ')
else:previous=Image.fromarray(rgb)
panels=[Image.fromarray(rgb),previous,revised]
cell=480;scaled_h=round(h*cell/w);canvas=Image.new('RGB',(3*cell,scaled_h+70),(245,245,245));d=ImageDraw.Draw(canvas)
for col,(im,title) in enumerate(zip(panels,['RGB unchanged','v1.0 anchors' if source else 'RGB unchanged','v1.1 anchors'])):
d.text((col*cell+8,8),title,fill=(20,20,20));canvas.paste(im.resize((cell,scaled_h)),(col*cell,30))
d.text((8,scaled_h+36),f"{meta['sequence_id']} / {meta['camera_id']} frame {count}; anchors only, NOT segmentation or hand joints",fill=(20,20,20))
name=f'frame-{count:06d}.png';canvas.save(out/name)
rows.append({'frame_index':count,'path':name,'old_new_preview_pixels_equal':bool(source),'visible_anchors':len(points)})
count+=1
proc.stdout.close()
if proc.wait()!=0:raise RuntimeError('Video decoding failed; see decode.log')
finally:
if proc.poll() is None:proc.terminate();proc.wait()
if count!=total:raise ValueError(f'RGB frames {count} != metainfo {total}')
report={'sequence':meta['sequence_id'],'camera':meta['camera_id'],'decoded_frames':count,'dimensions':[w,h],
'decoded_rgb_sha256':decoded_sha.hexdigest(),'new_reader_used':True,'all_frames_decoded':True,
'source_numeric_comparison':bool(source),'panels':rows,'not_segmentation_quality_review':True}
(out/'report.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps({k:v for k,v in report.items() if k!='panels'},indent=2))
return report
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('view',type=Path)
p.add_argument('--video',type=Path);p.add_argument('--output',type=Path,required=True);p.add_argument('--source',type=Path)
a=p.parse_args();run(a.view,a.video or a.view/'observation/rgb.mkv',a.output,a.source)
if __name__=='__main__':main()
|