#!/usr/bin/env python3 """Development audit: rank original white-rack proposals with a DINOv2 reference. No fiducial, fixed pickup pixel, or simulator object pose is used in proposal generation. A manually reviewed original-rack crop is the appearance reference. Scores are cosine similarities, not probabilities. No deployment threshold or metric-pose accuracy has yet been established. """ import argparse import csv import json from pathlib import Path import cv2 import numpy as np import torch from transformers import AutoModel def read_frame(data,episode,time): root=data/'episodes'/f'episode_{episode:06d}' stamps=list(csv.DictReader((root/'top_timestamps.csv').open())) previous=[r for r in stamps if float(r['time_sec'])<=time] stamp=previous[-1] if previous else stamps[0] cap=cv2.VideoCapture(str(root/'top.mp4'));cap.set(cv2.CAP_PROP_POS_FRAMES,int(stamp['video_frame_index'])) ok,image=cap.read();cap.release() if not ok:raise ValueError('missing frame') return image,stamp def proposals(image): hsv=cv2.cvtColor(image,cv2.COLOR_BGR2HSV) mask=cv2.inRange(hsv,(0,0,140),(180,80,255)) contours,hierarchy=cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) height,width=image.shape[:2];found=[] for contour in contours: area=cv2.contourArea(contour) if not .0005*height*width < area < .025*height*width:continue rect=cv2.minAreaRect(contour);small,large=sorted(rect[1]);aspect=large/max(small,1.) if not 1.6<=aspect<=5.5:continue x,y,w,h=cv2.boundingRect(contour) if x==0 or y==0 or x+w>=width or y+h>=height:continue # Modest contextual border; appearance, not proposal position, ranks candidates. border=max(4,round(.1*max(w,h))) bbox=[max(0,x-border),max(0,y-border),min(width,x+w+border),min(height,y+h+border)] found.append({'bbox_xyxy':bbox,'white_contour_area':area,'image_aspect':aspect}) return found def main(): p=argparse.ArgumentParser(description=__doc__) p.add_argument('--data',type=Path,required=True);p.add_argument('--encoder',type=Path,required=True) p.add_argument('--output',type=Path,required=True) args=p.parse_args();args.output.mkdir(parents=True,exist_ok=False) model=AutoModel.from_pretrained(args.encoder,local_files_only=True).to('cuda').eval() mean=torch.tensor([.485,.456,.406],device='cuda')[None,:,None,None] std=torch.tensor([.229,.224,.225],device='cuda')[None,:,None,None] def encode(crops): inputs=np.stack([cv2.cvtColor(cv2.resize(c,(224,224)),cv2.COLOR_BGR2RGB) for c in crops]) x=torch.from_numpy(inputs).permute(0,3,1,2).to(device='cuda',dtype=torch.float32)/255. with torch.inference_mode():f=model(pixel_values=(x-mean)/std).last_hidden_state[:,0] return torch.nn.functional.normalize(f,dim=-1) reference,stamp=read_frame(args.data,39,19.) ref_bbox=[610,142,682,254];x1,y1,x2,y2=ref_bbox;template=reference[y1:y2,x1:x2] ref=encode([template,cv2.rotate(template,cv2.ROTATE_180)]) cv2.imwrite(str(args.output/'reference.jpg'),template) rows=[];panels=[] for episode,time in [(39,0.),(39,19.),(38,7.5),(3,0.)]: frame,stamp=read_frame(args.data,episode,time);candidates=proposals(frame) if candidates: crops=[frame[y1:y2,x1:x2] for x1,y1,x2,y2 in (r['bbox_xyxy'] for r in candidates)] scores=(encode(crops)@ref.T).max(dim=1).values.cpu().tolist() for candidate,score in zip(candidates,scores):candidate['reference_cosine']=score candidates.sort(key=lambda x:x['reference_cosine'],reverse=True) for rank,c in enumerate(candidates[:3],1): x1,y1,x2,y2=c['bbox_xyxy'];color=(0,255,0) if rank==1 else (0,165,255) cv2.rectangle(frame,(x1,y1),(x2,y2),color,2) cv2.putText(frame,f'{rank}: {c["reference_cosine"]:.3f}',(x1,max(18,y1-5)),0,.6,color,2) tag=f'ep{episode}_top_{time:.1f}';cv2.imwrite(str(args.output/f'{tag}.jpg'),frame) tile=cv2.resize(frame,(640,360));cv2.putText(tile,tag,(5,25),0,.65,(0,0,255),2);panels.append(tile) rows.append({'episode':episode,'time_sec':float(stamp['time_sec']),'ranked_candidates':candidates}) print(json.dumps({'case':tag,'ranked_candidates':candidates[:3]}),flush=True) result={'method':'white contour proposals + DINOv2 reference CLS cosine ranking', 'reference':{'episode':39,'view':'top','time_sec':19.,'bbox_xyxy':ref_bbox}, 'accuracy_evaluated':False,'metric_pose_evaluated':False,'score_is_probability':False, 'same_reference_frame_included_as_sanity_check_not_generalization':True,'frames':rows} (args.output/'predictions.json').write_text(json.dumps(result,indent=2)+'\n') cv2.imwrite(str(args.output/'review.jpg'),np.vstack([np.hstack(panels[:2]),np.hstack(panels[2:])])) if __name__=='__main__':main()