Download realcase/34/move_replace_mesh_v2/code/geometry_plan.py from FrontRear/VLMdataset: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/datasets/FrontRear/VLMdataset/resolve/main/realcase/34/move_replace_mesh_v2/code/geometry_plan.py
- Command line
-
hf download hf://datasets/FrontRear/VLMdataset/realcase/34/move_replace_mesh_v2/code/geometry_plan.py
-
curl -L -o geometry_plan.py https://huggingface.co/datasets/FrontRear/VLMdataset/resolve/main/realcase/34/move_replace_mesh_v2/code/geometry_plan.py
11.6 kB
| import os,sys,json,hashlib,importlib.util | |
| from pathlib import Path | |
| import numpy as np,cv2 | |
| sys.path.insert(0,'/root/autodl-tmp/codex_user8_move_replace_20261109/python_deps') | |
| import trimesh | |
| ROOT=Path('/root/autodl-tmp/kimi_realcase_20261109') | |
| ASSETS=Path('/root/autodl-tmp/codex_user8_move_replace_20261109/realcase_new_models') | |
| CORE=Path('/root/autodl-tmp/real_video_condition_repro_20261105_v1/tools/old671') | |
| sys.path.insert(0,str(CORE)) | |
| from bbox import OrientedBoundingBox,render_bbox_conditions | |
| W,H=1280,704 | |
| def sha(path): | |
| h=hashlib.sha256() | |
| with open(path,'rb') as f: | |
| for b in iter(lambda:f.read(4*1024*1024),b''):h.update(b) | |
| return h.hexdigest() | |
| def norm(v):return v/max(1e-12,np.linalg.norm(v)) | |
| def rodrigues(axis,ang): | |
| a=norm(axis);K=np.array([[0,-a[2],a[1]],[a[2],0,-a[0]],[-a[1],a[0],0]]) | |
| return np.eye(3)+np.sin(ang)*K+(1-np.cos(ang))*(K@K) | |
| def angle(R):return float(np.degrees(np.arccos(np.clip((np.trace(R)-1)/2,-1,1)))) | |
| def fit_plane(points,tol,rng): | |
| best=None | |
| for _ in range(700): | |
| p=points[rng.choice(len(points),3,replace=False)];n=norm(np.cross(p[1]-p[0],p[2]-p[0]));d=-float(n@p[0]);cnt=int((np.abs(points@n+d)<tol).sum()) | |
| if best is None or cnt>best[0]:best=(cnt,n,d) | |
| if best is None:raise RuntimeError('plane fit failed') | |
| inl=points[np.abs(points@best[1]+best[2])<tol] | |
| if len(inl)<12:raise RuntimeError(f'too few plane inliers {len(inl)}') | |
| c=inl.mean(0);_,_,vt=np.linalg.svd(inl-c,full_matrices=False);n=vt[-1];d=-float(n@c);mask=np.abs(points@n+d)<tol | |
| return n,d,mask | |
| def load_asset(n): | |
| scene=trimesh.load(str(ASSETS/f'{n}.glb'),force='scene');mesh=scene.to_geometry();v=np.asarray(mesh.vertices,np.float64);f=np.asarray(mesh.faces,np.int32) | |
| v=np.stack([v[:,0],-v[:,2],v[:,1]],1) | |
| return v,f | |
| def run(cfg): | |
| case=cfg['case_id'];num=cfg['number'];cd=ROOT/'cases'/case;sd=ROOT/'samples'/case;out=ROOT/'outputs'/str(num)/os.environ.get('REVISION',cfg.get('revision','move_replace_mesh_v1'));out.mkdir(parents=True,exist_ok=False) | |
| d=np.load(sd/'step3_worldpoints/vggt_raw.npz');wp=d['world_points'];conf=d['world_points_conf'];ext=d['extrinsic_3x4'].astype(np.float64);K=d['K'].astype(np.float64).copy();gh,gw=wp.shape[1:3];K[:,0,:]*=W/gw;K[:,1,:]*=H/gh | |
| A=np.tile(np.eye(4),(49,1,1));A[:,:3,:]=ext | |
| mask_stage=cfg.get('mask_stage',os.environ.get('MASK_STAGE','step8_sam2_candidate')) | |
| masks=[cv2.imread(str(sd/mask_stage/'mask49'/f'{i:06}.png'),0)>0 for i in range(49)] | |
| # Fit only the operator-selected support rectangle on frame 24 and save its actual inliers. | |
| x0,y0,x1,y1=cfg['support_rect_xyxy'];gx=np.clip((np.arange(x0,x1,3)*gw/W).astype(int),0,gw-1);gy=np.clip((np.arange(y0,y1,3)*gh/H).astype(int),0,gh-1);xx,yy=np.meshgrid(gx,gy) | |
| pts=wp[24,yy.ravel(),xx.ravel()];cf=conf[24,yy.ravel(),xx.ravel()];ok=np.isfinite(pts).all(1)&(cf>1e-3);pts=pts[ok];gx2=xx.ravel()[ok];gy2=yy.ravel()[ok] | |
| if len(pts)<30:raise RuntimeError(f'insufficient support points {len(pts)}') | |
| n,pd,inl=fit_plane(pts,cfg['plane_tolerance'],np.random.default_rng(20261109));ip=pts[inl] | |
| camera_center=-A[24,:3,:3].T@A[24,:3,3];pc=ip.mean(0) | |
| if n@(camera_center-pc)<0:n,pd=-n,-pd | |
| inl_ratio=float(np.mean(inl));plane_rms=float(np.sqrt(np.mean((ip@n+pd)**2))) | |
| # Vertical fixture axis: support normal for floor/desk/outdoor; wall-vertical for wall lamps. | |
| if cfg['scene_type']=='wall': | |
| up=-A[24,1,:3];up=norm(up-n*(n@up)) | |
| else:up=n.copy() | |
| xr=norm(A[24,0,:3]-up*(up@A[24,0,:3]));yr=np.cross(up,xr);R=np.stack([xr,yr,up],1) | |
| # Source visible cloud uses per-frame median lamp depth and the same A/K/mask version. | |
| clouds=[];depths=[];visible_z=[] | |
| for i,m in enumerate(masks): | |
| ys,xs=np.where(m) | |
| if not len(xs):raise RuntimeError(f'empty source mask frame {i}') | |
| step=max(1,len(xs)//6000);ys,xs=ys[::step],xs[::step];gy3=np.minimum((ys*gh/H).astype(int),gh-1);gx3=np.minimum((xs*gw/W).astype(int),gw-1);world=wp[i,gy3,gx3];cam=world@A[i,:3,:3].T+A[i,:3,3];z=cam[:,2];z=z[np.isfinite(z)&(z>0)] | |
| if not len(z):raise RuntimeError(f'no positive depth frame {i}') | |
| depth=float(np.median(z));depths.append(depth);zz=np.full(len(xs),depth);cp=np.stack([(xs-K[i,0,2])*zz/K[i,0,0],(ys-K[i,1,2])*zz/K[i,1,1],zz],1);world=(cp-A[i,:3,3])@A[i,:3,:3];clouds.append(world) | |
| cloud=np.concatenate(clouds);local=cloud@R;visible_lo=local.min(0);visible_hi=local.max(0);visible_height=float(visible_hi[2]-visible_lo[2]);amodal=None | |
| lo,hi=visible_lo.copy(),visible_hi.copy() | |
| if cfg['scene_type']=='outdoor' or cfg.get('estimate_hidden_base',False): | |
| # Estimate only the out-of-frame base: vertically intersect the lowest visible pole region with the fitted ground. | |
| cutoff=np.percentile(local[:,2],12);pole=local[local[:,2]<=cutoff];low_world=(pole@R.T).mean(0);base=base=low_world-up*((up@low_world+pd)/(up@up)) | |
| lo=np.minimum(lo,(base@R)-np.array([.04*visible_height,.04*visible_height,0.]));hi=np.maximum(hi,base@R) | |
| amodal={'estimated_base_world':base.tolist(),'method':'vertical intersection of lowest visible pole region with estimated ground plane','observed':False,'uncertainty':'base shape and exact ground contact are not visible in the source frames'} | |
| pad=np.maximum(.025*(hi-lo),1e-4);lo-=pad;hi+=pad;P=(lo+hi)@R.T/2 if False else ((lo+hi)/2)@R.T;psize=hi-lo | |
| # Replacement mesh and dimensions, explicitly relative rather than metric truth. | |
| vertices,faces=load_asset(cfg['asset_number']);dims=vertices.min(0)*0+(vertices.max(0)-vertices.min(0));height_reference=psize[2] if cfg.get('asset_height_reference')=='P_size_z' else visible_height;qsize=dims*(height_reference*cfg['asset_height_scale']/dims[2]) | |
| if cfg['scene_type']=='wall': | |
| qz=up;qy=n;qx=norm(np.cross(qy,qz));qrot=np.stack([qx,qy,qz],1) | |
| else:qrot=R.copy() | |
| # Ray/plane intersection at the operator-chosen A24 target pixel. | |
| tx,ty=cfg['target_xy_A24'];ray_c=np.array([(tx-K[24,0,2])/K[24,0,0],(ty-K[24,1,2])/K[24,1,1],1.]);ray_w=A[24,:3,:3].T@ray_c;den=float(n@ray_w) | |
| if abs(den)<1e-9:raise RuntimeError('target ray parallel to support') | |
| lam=-(n@camera_center+pd)/den | |
| if lam<=0:raise RuntimeError('target support intersection behind camera') | |
| mount=camera_center+lam*ray_w | |
| Q=mount+n*qsize[1]/2 if cfg['scene_type']=='wall' else mount+up*qsize[2]/2 | |
| qcenter_local=(vertices-(vertices.min(0)+vertices.max(0))/2)*(qsize/dims);qworld=qcenter_local@qrot.T+Q | |
| # Fixed world asset inside Q OBB by construction. | |
| excess=float(np.maximum(np.abs(qcenter_local)-qsize/2,0).max());assert excess<1e-7 | |
| # Two real smooth trajectories; choose the sign with better key-frame framing at 10 degrees. | |
| pivot=(P+Q)/2 | |
| def camera(deg,i,sign): | |
| u=i/48;s=u*u*(3-2*u);Rw=rodrigues(up,np.deg2rad(sign*deg)*s);ca=np.linalg.inv(A[i])[:3,3];cb=pivot+Rw@(ca-pivot);rb=A[i,:3,:3]@Rw.T;b=np.eye(4);b[:3,:3]=rb;b[:3,3]=-rb@cb;return b | |
| def framing_cost(sign): | |
| cost=0 | |
| for i in (0,24,48): | |
| B=camera(10,i,sign);cam=qworld@B[:3,:3].T+B[:3,3];uv=(cam@K[i].T);uv=uv[:,:2]/uv[:,2,None] | |
| cost+=float(np.maximum(-uv[:,0],0).sum()+np.maximum(uv[:,0]-(W-1),0).sum()+np.maximum(-uv[:,1],0).sum()+np.maximum(uv[:,1]-(H-1),0).sum()+np.maximum(.05-cam[:,2],0).sum()*1000) | |
| return cost | |
| sign=-1 if framing_cost(-1)<=framing_cost(1) else 1 | |
| versions={} | |
| for name,deg in [('small_4deg',4.),('orbit_10deg',10.)]: | |
| B=np.stack([camera(deg,i,sign) for i in range(49)]);angles=[];centers=[];jumps=[] | |
| for i in range(49): | |
| angles.append(angle(B[i,:3,:3]@A[i,:3,:3].T));centers.append(np.linalg.inv(B[i])[:3,3]) | |
| if i:jumps.append(angle(B[i,:3,:3]@B[i-1,:3,:3].T)) | |
| np.savez_compressed(out/f'cameras_and_boxes_{name}.npz',K=K,w2c_A=A,w2c_B=B,P=P,Q=Q,P_size=psize,Q_size=qsize,P_rotation=R,Q_rotation=qrot,asset_vertices_local=qcenter_local,asset_faces=faces) | |
| versions[name]={'relative_angle_deg_min':min(angles),'relative_angle_deg_max':max(angles),'max_adjacent_rotation_deg':max(jumps),'camera_center_start':centers[0].tolist(),'camera_center_mid':centers[24].tolist(),'camera_center_end':centers[-1].tolist(),'A_B_identical':bool(np.array_equal(A,B))} | |
| # Support evidence and A-view placement preview. B has no real RGB; the A overlay is geometry only. | |
| frame=cv2.imread(str(cd/'frames/024.png'));vis=frame.copy() | |
| for x,y in zip(gx2[inl],gy2[inl]): | |
| u=int(round(x*W/gw));v=int(round(y*H/gh)) | |
| if 0<=u<W and 0<=v<H:cv2.circle(vis,(u,v),1,(0,255,255),-1) | |
| cv2.rectangle(vis,(x0,y0),(x1,y1),(0,255,255),2);cv2.circle(vis,(tx,ty),7,(255,0,0),2);cv2.putText(vis,f'inliers={inl.sum()} ratio={inl_ratio:.3f} rms={plane_rms:.5g}',(12,28),cv2.FONT_HERSHEY_SIMPLEX,.6,(0,255,255),2) | |
| cv2.imwrite(str(out/'support_inliers_000024.png'),vis) | |
| # Render P/Q wires in A and actual replacement mesh silhouette in A for placement review. | |
| overlay=frame.copy();target=np.zeros((H,W),np.uint8) | |
| for center,size,rot,color in [(P,psize,R,(0,0,255)),(Q,qsize,qrot,(255,0,0))]: | |
| box=OrientedBoundingBox('box',center,size,rot,np.array([255,255,255],np.uint8));lines,_,bm,_=render_bbox_conditions([box],K[24],A[24],H,W,edge_width=3,fill_alpha=.28);wire=(lines.max(-1)>100)&(bm>0);overlay[wire]=color | |
| cam=qworld@A[24,:3,:3].T+A[24,:3,3];pr=cam@K[24].T;uv=pr[:,:2]/pr[:,2,None];pts2=np.rint(np.clip(uv,-32760,32760)).astype(np.int32) | |
| good=np.isfinite(uv).all(1)&(cam[:,2]>0);tri=faces[good[faces].all(1)] | |
| for t in tri:cv2.fillConvexPoly(target,pts2[t],255,lineType=cv2.LINE_8) | |
| sel=target>0;overlay[sel]=np.rint(.45*overlay[sel]+.55*np.array([255,0,255])).astype(np.uint8) | |
| srcsel=masks[24];overlay[srcsel]=np.rint(.7*overlay[srcsel]+.3*np.array([0,255,0])).astype(np.uint8) | |
| cv2.imwrite(str(out/'placement_A_000024.png'),overlay);cv2.imwrite(str(out/'target_mesh_A_000024.png'),target) | |
| meta={'case_id':case,'number':num,'operation':'move_replace: delete source P and insert a different GLB asset at Q','source_video_sha256':json.loads((cd/'case.json').read_text())['source_sha256'],'source_mask_version':mask_stage+'; visible only; keyframes reviewed','scene_type':cfg['scene_type'],'asset_number':cfg['asset_number'],'asset_sha256':sha(ASSETS/f"{cfg['asset_number']}.glb"),'asset_coordinate_conversion':'GLB [x,y,z] -> Blender [x,-z,y]','metric_scale_known':False,'world_unit':'relative monocular units','support':{'rect_xyxy_A24':cfg['support_rect_xyxy'],'normal_world':n.tolist(),'d':float(pd),'inliers':int(inl.sum()),'inlier_ratio':inl_ratio,'rms_world':plane_rms,'target_xy_A24':cfg['target_xy_A24'],'mount_world':mount.tolist(),'evidence_image':'support_inliers_000024.png'},'P':{'center':P.tolist(),'size':psize.tolist(),'rotation':R.tolist(),'visible_height':visible_height,'amodal_estimate':amodal},'Q':{'center':Q.tolist(),'size':qsize.tolist(),'rotation':qrot.tolist(),'relative_height_control':cfg['asset_height_scale'],'height_reference_kind':cfg.get('asset_height_reference','visible_height_along_support_normal'),'mesh_vertices_inside_obb_max_excess':excess},'camera_versions':versions,'camera_sign':sign,'uncertainty':['monocular absolute scale unknown','source depth and support plane are VGGT estimates','target mesh projection has no scene occlusion rendering','outdoor source base is amodal estimate' if cfg['scene_type']=='outdoor' else 'hidden source geometry not observed is not included in visible mask'],'status':'geometry_plan_visual_review_pending'} | |
| (out/'geometry_plan.json').write_text(json.dumps(meta,indent=2)) | |
| print(json.dumps({'case':case,'support_inlier_ratio':inl_ratio,'plane_rms':plane_rms,'P_size':psize.tolist(),'Q_size':qsize.tolist(),'camera_versions':versions,'output':str(out)}),flush=True) | |
| if __name__=='__main__': | |
| configs=json.loads((ROOT/os.environ.get('PRODUCTION_CONFIG','production_config.json')).read_text());wanted=sys.argv[1:] | |
| for cfg in configs: | |
| if wanted and str(cfg['number']) not in wanted:continue | |
| run(cfg) | |