FrontRear commited on
Commit
27cb3f9
·
verified ·
1 Parent(s): 714fe08

Add experimental 3D move-replace case 2

Browse files
realcase/2/move_replace_mesh_v2/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ 本版本为待审核条件草稿:移动+替换=删除 P 并在 Q 插入新资产。target mask 使用实际三维 GLB 网格按每帧 B 相机投影;未处理场景遮挡。源灯可见轮廓来自 SAM2,遮挡部分不是实测。第4组红框包含估计的笔记本后方支撑点。相机、单目尺度、目标支撑面和位置仍是估计;不代表已通过训练读取或生成视频推理。保留旧版本。
realcase/2/move_replace_mesh_v2/code/build_move_replace.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Experimental replacement conditions; preserve all prior output versions."""
3
+ import ast, json, sys, hashlib
4
+ from pathlib import Path
5
+ import numpy as np
6
+ import cv2
7
+ from PIL import Image
8
+
9
+ cv2.setNumThreads(1)
10
+ n = int(sys.argv[1]); h, w = 704, 1280
11
+ base = Path('/root/autodl-tmp/codex_user8_20261108')/str(n)/'conditions'
12
+ root = Path('/root/autodl-tmp/codex_user8_move_replace_20261109')
13
+ revision = sys.argv[2] if len(sys.argv)>2 else 'asset3d_draft'
14
+ out = root/revision/str(n)
15
+ out.mkdir(parents=True, exist_ok=False)
16
+ for sub in ['pcf','geometry/P/mask','geometry/P/wire','geometry/Q/mask','geometry/Q/wire','move_replace/labels','move_replace/joint','move_replace/target_lamp_mask']:
17
+ (out/sub).mkdir(parents=True,exist_ok=True)
18
+ for c in ['purple','green','blue','warm']:
19
+ for t in ['color','intensity']:(out/'move_replace'/'lighting'/c/t).mkdir(parents=True)
20
+ core=Path('/root/autodl-tmp/real_video_condition_repro_20261105_v1/tools/old671')
21
+ loader=Path('/root/autodl-tmp/codex_user8_20261108/bbox_dataset_original.py')
22
+ sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
23
+ assert sha(core/'bbox.py')=='843652f38bd6de91a2d4b9d940871082b3c9cc0f2dd5c1c5ebf23500e6c9c613'
24
+ assert sha(loader)=='ae76b9588a94dd5a9db511ff89182a36d48947193b6ad04e0bbf3fae48a68fca'
25
+ sys.path.insert(0,str(core));from bbox import OrientedBoundingBox,render_bbox_conditions
26
+ class Native704(ast.NodeTransformer):
27
+ def visit_Constant(self,node):
28
+ if type(node.value) is int and node.value in (352,640):return ast.copy_location(ast.Constant(value={352:704,640:1280}[node.value]),node)
29
+ return node
30
+ tree=Native704().visit(ast.parse(loader.read_text()));ast.fix_missing_locations(tree)
31
+ ns={'__name__':'native704_loader'};exec(compile(tree,str(loader),'exec'),ns);joint_frames=ns['joint_frames']
32
+ data=np.load(base/'cameras_and_boxes.npz'); a=data['w2c_A']; b=data['w2c_B']; K=data['K']; P=data['P']; psize=data['size']; rot=data['rotation']
33
+ source_mask_path=base/'observed_mask'
34
+ if revision in ('sam_source_rebuild','framed_mesh_v1','framed_mesh_v2') and n in (1,3,7):
35
+ maskrev='sam_visible_refined_v3' if n==1 and revision=='framed_mesh_v2' else ('sam_visible_refined_v2' if n==7 else 'sam_visible_refined')
36
+ source_mask_path=root/maskrev/str(n)/'mask'
37
+ case={1:'rv_pexels3_12237997_1920_1080_24fps',3:'rv_pexels1_5197240-uhd_3840_2160_25',7:'rv_pexels1_5206017-uhd_3840_2160_25'}[n]
38
+ world=np.load(Path('/root/autodl-tmp/codex_aligned_v2/samples')/case/'step3_worldpoints/vggt_raw.npz')['world_points'];gh,gw=world.shape[1:3];cloud=[]
39
+ for i in range(49):
40
+ m=cv2.imread(str(source_mask_path/f'{i:06}.png'),0)>0;yy,xx=np.where(m);assert len(xx)
41
+ pts=world[i,np.minimum((yy*gh/h).astype(int),gh-1),np.minimum((xx*gw/w).astype(int),gw-1)];z=(pts@a[i,:3,:3].T+a[i,:3,3])[:,2];z=z[np.isfinite(z)&(z>0)];assert len(z);depth=float(np.median(z))
42
+ cam=np.stack([(xx-K[i,0,2])*depth/K[i,0,0],(yy-K[i,1,2])*depth/K[i,1,1],np.full(len(xx),depth)],axis=1);p=(cam-a[i,:3,3])@a[i,:3,:3];cloud.append(p[::max(1,len(p)//10000)])
43
+ cloud=np.concatenate(cloud);lo=cloud.min(0);hi=cloud.max(0);pad=np.maximum(.03*(hi-lo),.003);lo-=pad;hi+=pad;P=(lo+hi)/2;psize=hi-lo;psize[2]=max(psize[2],.04*np.linalg.norm(psize[:2]))
44
+ hidden_anchor=None
45
+ if n==4 and revision=='framed_mesh_v2':
46
+ # User-specified amodal source: infer the obscured lower stand to the desk.
47
+ # This is an estimated anchor behind the laptop, not an observed segmentation.
48
+ xh,yh=310,540; depth_h=float((P@a[24,:3,:3].T+a[24,:3,3])[2]); kh=K[24]
49
+ cp=np.array([(xh-kh[0,2])*depth_h/kh[0,0],(yh-kh[1,2])*depth_h/kh[1,1],depth_h]);hidden_anchor=(cp-a[24,:3,3])@a[24,:3,:3]
50
+ lo=np.minimum(P-psize/2,hidden_anchor);hi=np.maximum(P+psize/2,hidden_anchor);P=(lo+hi)/2;psize=hi-lo
51
+ # Q locations are screen-space estimates, with uncalibrated depth inherited from P.
52
+ targets={1:(435,430),2:(970,320),3:(880,400),4:(1000,390),5:(146,328),6:(234,302),7:(464,498),8:(290,610)}
53
+ x,y=targets[n]; depth=float((P@a[24,:3,:3].T+a[24,:3,3])[2]);k=K[24]
54
+ camera=np.array([(x-k[0,2])*depth/k[0,0],(y-k[1,2])*depth/k[1,1],depth]);Q=(camera-a[24,:3,3])@a[24,:3,:3]
55
+ # Asset-relative dimensions come from the model bounds. Anchor its unknown absolute
56
+ # scale to the estimated projected height of the source box, not a claimed metre size.
57
+ bounds=json.loads((root/'replacement_candidates/asset_bounds.json').read_text())[str(n)]['source_bounds'];dims=np.asarray(bounds[1])-np.asarray(bounds[0]);assert np.all(dims>0)
58
+ up=-a[24,1,:3]; ref_height=float(np.abs(up@rot).dot(psize));qsize=dims*(ref_height/dims[2])
59
+ qrot=np.stack([a[24,0,:3],a[24,2,:3],-a[24,1,:3]],axis=1)
60
+ framing_scale=1.
61
+ if revision in ('framed_mesh_v1','framed_mesh_v2'):
62
+ signs=np.array([[i,j,k] for i in (-1,1) for j in (-1,1) for k in (-1,1)],np.float64)
63
+ def framed(scale):
64
+ pts=(signs*qsize*scale/2)@qrot.T+Q
65
+ for i in range(49):
66
+ cam=pts@b[i,:3,:3].T+b[i,:3,3]
67
+ if np.any(cam[:,2]<=0):return False
68
+ image=cam@K[i].T;xy=image[:,:2]/image[:,2,None]
69
+ if np.any(xy[:,0]<1) or np.any(xy[:,0]>w-2) or np.any(xy[:,1]<1) or np.any(xy[:,1]>h-2):return False
70
+ return True
71
+ if not framed(1.):
72
+ assert framed(0.), 'target center outside camera view'
73
+ low,high=0.,1.
74
+ for _ in range(32):
75
+ mid=(low+high)/2
76
+ if framed(mid):low=mid
77
+ else:high=mid
78
+ framing_scale=low;qsize*=framing_scale
79
+ np.savez_compressed(out/'cameras_and_boxes.npz',K=K,w2c_A=a,w2c_B=b,P=P,Q=Q,P_size=psize,Q_size=qsize,P_rotation=rot,Q_rotation=qrot)
80
+ meta=json.loads((base/'manifest.json').read_text());asset_path=next((root/'replacement_candidates').glob(f'{n}_asset_*.png'));asset=cv2.imread(str(asset_path),cv2.IMREAD_UNCHANGED);assert asset is not None and asset.shape[2]==4
81
+ alpha=asset[:,:,3]; yy,xx=np.where(alpha>0); alpha=alpha[yy.min():yy.max()+1,xx.min():xx.max()+1]
82
+ palette=[[0,0,0],[255,0,0],[0,0,255],[255,255,0]]
83
+ for i in range(49):
84
+ f=f'{i:06}.png'; (out/'pcf'/f).symlink_to(base/'pcf'/f)
85
+ masks={}
86
+ for name,center,size,rotation in [('P',P,psize,rot),('Q',Q,qsize,qrot)]:
87
+ obb=OrientedBoundingBox(name,center,size,rotation,np.array([255,255,255],np.uint8));lines,_,mask,_=render_bbox_conditions([obb],K[i],b[i],h,w,edge_width=3,fill_alpha=.28)
88
+ wire=((lines.max(-1)>100)&(mask>0)).astype(np.uint8)*255;masks[name]=mask>0
89
+ for sub,img in [('mask',mask),('wire',wire)]:cv2.imwrite(str(out/'geometry'/name/sub/f),img)
90
+ labels=masks['P'].astype('uint8')+2*masks['Q'].astype('uint8');cv2.imwrite(str(out/'move_replace/labels'/f),labels)
91
+ yy,xx=np.where(masks['Q']); lamp=np.zeros((h,w),np.uint8)
92
+ if len(xx):
93
+ x0,x1,y0,y1=int(xx.min()),int(xx.max()+1),int(yy.min()),int(yy.max()+1)
94
+ # Preserve reference aspect. A shrink is purely to avoid clipping its 2-D proxy.
95
+ factor=min((x1-x0)/alpha.shape[1],(y1-y0)/alpha.shape[0]);
96
+ for step in range(101):
97
+ scale=factor*(1-step/100);sw=max(1,round(alpha.shape[1]*scale));sh=max(1,round(alpha.shape[0]*scale));sx=x0+(x1-x0-sw)//2;sy=y0+(y1-y0-sh)//2
98
+ trial=np.zeros_like(lamp);trial[sy:sy+sh,sx:sx+sw]=cv2.resize(alpha,(sw,sh),interpolation=cv2.INTER_NEAREST)
99
+ if not np.any((trial>0)&~masks['Q']):lamp=trial;break
100
+ cv2.imwrite(str(out/'move_replace/target_lamp_mask'/f),lamp)
101
+ selected=lamp>0
102
+ for c,rgb in meta['color_linear_rgb_controls'].items():
103
+ for kind in ['color','intensity']:
104
+ val=np.asarray(rgb if kind=='color' else [meta['intensity_encoded']]*3,np.float32); ys,xs=np.where(selected)
105
+ left,right=(int(xs.min()),int(xs.max()+1)) if len(xs) else (0,1);top,bottom=(int(ys.min()),int(ys.max()+1)) if len(ys) else (0,1)
106
+ roi=np.zeros((bottom-top,right-left,3),np.float32);roi[selected[top:bottom,left:right]]=val
107
+ folder=out/'move_replace/lighting'/c/kind;np.savez_compressed(folder/f'{i:06}.npz',**{kind:roi},origin_xy=np.array([left,top]),full_shape_hwc=np.array([h,w,3]));full=np.zeros((h,w,3),np.uint8);full[top:bottom,left:right]=np.rint(roi*255).astype('uint8');cv2.imwrite(str(folder/f),cv2.cvtColor(full,cv2.COLOR_RGB2BGR))
108
+ if i%12==0:print(n,i,flush=True)
109
+ recipe={'schema':'pcf_bbox_factored.v003','background':'bbox_v3/pcf','labels':'bbox_v3/move_replace/labels','source_wire':'bbox_v3/geometry/P/wire','target_wire':'bbox_v3/geometry/Q/wire','palette_rgb':palette,'fill_alpha':.58,'background_alpha':.42}
110
+ (out/'move_replace/RENDER.json').write_text(json.dumps(recipe,indent=2));frames=joint_frames(str(out/'move_replace'),str(out),str(out))
111
+ for i,frame in enumerate(frames):Image.fromarray(frame).save(out/'move_replace/joint'/f'{i:06}.png',compress_level=1)
112
+ (out/'manifest.json').write_text(json.dumps({'case':n,'operation':'move_replace: remove P, insert new fixture Q','asset':asset_path.name,'target_xy_A24':targets[n],'P_world':P.tolist(),'Q_world':Q.tolist(),'P_size':psize.tolist(),'Q_size':qsize.tolist(),'Q_rotation':qrot.tolist(),'source_occluded_support_anchor_world_estimate':None if hidden_anchor is None else hidden_anchor.tolist(),'viewport_framing_scale':framing_scale,'size_note':'Q uses replacement asset bounds aspect; initial scale anchored to estimated source box height and reduced when needed to fit viewport; absolute size unverified','source_mask':str(source_mask_path),'source_mask_issues':'visual review still needed, hidden structure unobserved','target_mask':'static 2-D asset alpha fitted to estimated box; not novel-view 3-D rendering','support_and_scale':'estimated; unverified','pcf':'existing B camera with 10 degree smooth change','format':'experimental, not accepted','bbox_sha256':sha(core/'bbox.py'),'loader_sha256':sha(loader)},indent=2))
113
+ print('DONE',n,flush=True)
realcase/2/move_replace_mesh_v2/code/project_asset_mesh.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Project actual GLB geometry into each estimated B camera; experimental."""
2
+ import sys,json,hashlib
3
+ from pathlib import Path
4
+ import cv2,numpy as np
5
+ sys.path.insert(0,'/root/autodl-tmp/codex_user8_move_replace_20261109/python_deps')
6
+ import trimesh
7
+ cv2.setNumThreads(1)
8
+ n=int(sys.argv[1]); root=Path('/root/autodl-tmp/codex_user8_move_replace_20261109');rev=sys.argv[2] if len(sys.argv)>2 else 'framed_mesh_v1'; source=root/rev/str(n);out=root/('mesh_projected_framed_v2' if rev=='framed_mesh_v2' else 'mesh_projected_framed')/str(n);out.mkdir(parents=True,exist_ok=False)
9
+ for name in ['pcf','geometry']:(out/name).symlink_to(source/name,target_is_directory=True)
10
+ (out/'move_replace').mkdir();(out/'move_replace/labels').symlink_to(source/'move_replace/labels',target_is_directory=True);(out/'move_replace/joint').symlink_to(source/'move_replace/joint',target_is_directory=True)
11
+ (out/'move_replace/target_lamp_mask').mkdir()
12
+ colors={'purple':[.72,.02,1.],'green':[.02,1.,.03],'blue':[.02,.08,1.],'warm':[1.,.75,.42]}
13
+ levels={'low':1000,'medium':4000,'high':12000}
14
+ for c in colors:(out/'move_replace/lighting'/c/'color').mkdir(parents=True)
15
+ for level in levels:(out/'move_replace/intensity'/level).mkdir(parents=True)
16
+ d=np.load(source/'cameras_and_boxes.npz');scene=trimesh.load(str(root/'realcase_new_models'/f'{n}.glb'),force='scene'); mesh=scene.to_geometry(); vertices=np.asarray(mesh.vertices,np.float64);faces=np.asarray(mesh.faces,np.int32)
17
+ # glTF y-up -> Blender coordinates x, -z, y, matching recorded asset bounds.
18
+ v=np.stack([vertices[:,0],-vertices[:,2],vertices[:,1]],axis=1);lo=v.min(0);hi=v.max(0);sizes=hi-lo
19
+ scale=float(d['Q_size'][2]/sizes[2]);local=(v-(lo+hi)/2)*scale;world=local@d['Q_rotation'].T+d['Q'];outside=np.maximum(np.abs(local)-d['Q_size']/2,0).max();print('box excess',float(outside),'faces',len(faces),flush=True)
20
+ assert outside<1e-4*max(float(d['Q_size'].max()),1.)
21
+ records=[]
22
+ for i in range(49):
23
+ f=f'{i:06}'; cam=world@d['w2c_B'][i,:3,:3].T+d['w2c_B'][i,:3,3];p=cam@d['K'][i].T;uv=p[:,:2]/p[:,2,None]
24
+ good=np.isfinite(uv).all(axis=1)&(cam[:,2]>0); triangles=faces[good[faces].all(axis=1)];points=np.rint(np.clip(uv,-32760,32760)).astype(np.int32);pts=points[triangles]
25
+ vis=(pts[:,:,0].max(axis=1)>=0)&(pts[:,:,0].min(axis=1)<1280)&(pts[:,:,1].max(axis=1)>=0)&(pts[:,:,1].min(axis=1)<704);pts=pts[vis]
26
+ mask=np.zeros((704,1280),np.uint8)
27
+ for triangle in pts:cv2.fillConvexPoly(mask,triangle,255,lineType=cv2.LINE_8)
28
+ cv2.imwrite(str(out/'move_replace/target_lamp_mask'/f'{f}.png'),mask)
29
+ qbox=cv2.imread(str(source/'geometry/Q/mask'/f'{f}.png'),0)>0;sel=mask>0;outside2=int(np.count_nonzero(sel&~qbox));ys,xs=np.where(sel);left,right=(int(xs.min()),int(xs.max()+1)) if len(xs) else (0,1);top,bottom=(int(ys.min()),int(ys.max()+1)) if len(ys) else (0,1)
30
+ for typ,vals in [('color',colors),('intensity',{k:[float(np.log1p(v/100)/np.log1p(100000/100))]*3 for k,v in levels.items()})]:
31
+ for name,value in vals.items():
32
+ folder=(out/'move_replace/lighting'/name/'color') if typ=='color' else (out/'move_replace/intensity'/name);roi=np.zeros((bottom-top,right-left,3),np.float32);roi[sel[top:bottom,left:right]]=value;np.savez_compressed(folder/f'{f}.npz',**{typ:roi},origin_xy=np.array([left,top]),full_shape_hwc=np.array([704,1280,3]));full=np.zeros((704,1280,3),np.uint8);full[top:bottom,left:right]=np.rint(roi*255).astype('uint8');cv2.imwrite(str(folder/f'{f}.png'),cv2.cvtColor(full,cv2.COLOR_RGB2BGR))
33
+ records.append({'frame':i,'mask_pixels':int(sel.sum()),'outside_target_box_pixels':outside2,'visible_triangles':len(pts)})
34
+ if i%12==0:print(n,i,'pixels',int(sel.sum()),'outside',outside2,flush=True)
35
+ meta=json.loads((source/'manifest.json').read_text());meta.update({'target_mask':'actual 3-D GLB triangles projected into each B camera; no scene occlusion rendering','model_sha256':hashlib.sha256((root/'realcase_new_models'/f'{n}.glb').read_bytes()).hexdigest(),'intensity_lumens_controls_not_measured':levels,'records':records,'format':'experimental: source mask and support/scale still require review'})
36
+ (out/'manifest.json').write_text(json.dumps(meta,indent=2));print('DONE',n,flush=True)
realcase/2/move_replace_mesh_v2/conditions.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:76913c4a15595e9cdc21912fdfaaf86d18fb3f3580102b2ce39925e384f7c8c9
3
+ size 144711680
realcase/2/move_replace_mesh_v2/manifest.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "case": 2,
3
+ "status": "experimental_not_quality_accepted",
4
+ "note": "Actual GLB triangle silhouettes projected per B camera. Source depth, placement and scale estimated; no scene occlusion; missing hidden source geometry inferred only for case 4; no edited target RGB and no training-loader or model-inference acceptance. Source-mask completeness needs visual verification.",
5
+ "colors": [
6
+ "purple",
7
+ "green",
8
+ "blue",
9
+ "warm"
10
+ ],
11
+ "intensities": {
12
+ "low": 1000,
13
+ "medium": 4000,
14
+ "high": 12000
15
+ },
16
+ "source_mask_path": "/root/autodl-tmp/codex_user8_20261108/2/conditions/observed_mask",
17
+ "framing_scale": 1.0,
18
+ "frames": 49,
19
+ "resolution": [
20
+ 1280,
21
+ 704
22
+ ],
23
+ "max_target_mask_outside_box": 0,
24
+ "empty_target_frames": 0
25
+ }
realcase/2/move_replace_mesh_v2/preview_000000.jpg ADDED

Git LFS Details

  • SHA256: 2632b1151429204f0209c2fd7bfc40b0cfea7335acd99cffee424a54ab0e089c
  • Pointer size: 131 Bytes
  • Size of remote file: 128 kB
realcase/2/move_replace_mesh_v2/preview_000024.jpg ADDED

Git LFS Details

  • SHA256: 17041fc31114f403f06bdce00e2d51d802d0c37cbb18a38cb59d85ab05ae5b56
  • Pointer size: 131 Bytes
  • Size of remote file: 129 kB
realcase/2/move_replace_mesh_v2/preview_000048.jpg ADDED

Git LFS Details

  • SHA256: b5d55b1edb0b65fcd2caff79a8bd8116289fa543954345aa28af577fcfa87004
  • Pointer size: 131 Bytes
  • Size of remote file: 128 kB
realcase/2/move_replace_mesh_v2/sha256.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "conditions.tar": "76913c4a15595e9cdc21912fdfaaf86d18fb3f3580102b2ce39925e384f7c8c9",
3
+ "bytes": 144711680
4
+ }