baseball-engine / baseball_batting /camera_up_worker.py
github-actions[bot]
Automated Deploy: 8f8167dc5709c2ea13b6f4ea7a93cc50c9b953cd
7a3215f
Raw History Blame Contribute Delete
8 kB
"""Offline GeoCalib image inference in the existing isolated Torch runtime."""
import argparse
import hashlib
import numpy as np
from .camera_up_provider import WEIGHTS_SHA256
from .ingest import iter_frames
from .storage import atomic_json, read_json, sha256_file
def prepare_image(image,box,camera,max_side=960):
"""Rectify known intrinsics without rotating the optical/camera basis."""
import cv2
h,w=image.shape[:2];mask=np.ones((h,w),np.uint8)
x1,y1,x2,y2=box;pad=.1*max(x2-x1,y2-y1)
cv2.rectangle(mask,(max(0,int(x1-pad)),max(0,int(y1-pad))),
(min(w-1,int(x2+pad)),min(h-1,int(y2+pad))),0,-1)
valid=np.ones((h,w),np.uint8);focal=None
if camera:
k=np.array([[camera['fx'],0,camera['cx']],[0,camera['fy'],camera['cy']],[0,0,1]],float)
focal=float(np.sqrt(camera['fx']*camera['fy']))
virtual=np.array([[focal,0,w/2],[0,focal,h/2],[0,0,1]],float)
distortion=np.array(camera.get('distortion') or [0]*5,float)
mx,my=cv2.initUndistortRectifyMap(k,distortion,np.eye(3),virtual,(w,h),cv2.CV_32FC1)
valid=((mx>=0)&(mx<w-1)&(my>=0)&(my<h-1)).astype(np.uint8)
image=cv2.remap(image,mx,my,cv2.INTER_LINEAR)
mask=cv2.remap(mask,mx,my,cv2.INTER_NEAREST)*valid
scale=min(1.,max_side/max(h,w));size=(round(w*scale),round(h*scale))
image=cv2.resize(image,size,interpolation=cv2.INTER_AREA)
mask=cv2.resize(mask,size,interpolation=cv2.INTER_NEAREST).astype(bool)
valid=cv2.resize(valid,size,interpolation=cv2.INTER_NEAREST).astype(bool)
return image,mask,valid,None if focal is None else focal*scale
def weighted_diagnostics(error,weights,mask):
weights=np.where(mask&np.isfinite(error)&np.isfinite(weights),np.maximum(weights,0),0).astype(float)
total=weights.sum()
if not total>0:return None,0.,0
effective=float(total*total/np.sum(weights*weights))
# Learned confidence magnitudes differ between heads. Treat them as relative
# weights, not probability thresholds or calibrated visibility labels.
cells=0;h,w=mask.shape
for row in range(3):
for col in range(3):
mass=weights[row*h//3:(row+1)*h//3,col*w//3:(col+1)*w//3].sum()
cells+=int(mass>=.05*total)
return float(np.sum(error[weights>0]*weights[weights>0])/total),effective,cells
def diagnostics(result,image,mask,valid):
import cv2
def array(value):return value.detach().cpu().numpy()
vector=array(result['gravity'].vec3d)[0].astype(float)
# GeoCalib Gravity.from_rp(0,0) == [0,-1,0]: it is already
# camera-up in our x-right/y-down/z-away basis. No negation/axis swap.
vector/=np.linalg.norm(vector)
covariance=array(result['covariance'])[0,:2,:2].astype(float)
covariance_valid=bool(np.isfinite(covariance).all() and np.allclose(covariance,covariance.T,rtol=1e-3,atol=1e-7)
and np.linalg.eigvalsh((covariance+covariance.T)/2).min()>0)
uncertainty=float(np.degrees(array(result['gravity_uncertainty']).reshape(-1)[0]))
k=array(result['camera'].K)[0]
h,w=image.shape[:2];ratio=min(1.,320/max(h,w));size=(round(w*ratio),round(h*ratio))
mask=cv2.resize(mask.astype(np.uint8),size,interpolation=cv2.INTER_NEAREST).astype(bool)
valid=cv2.resize(valid.astype(np.uint8),size,interpolation=cv2.INTER_NEAREST).astype(bool)
rgb=cv2.resize(image,size,interpolation=cv2.INTER_AREA)
gray=cv2.cvtColor(rgb,cv2.COLOR_BGR2GRAY).astype(float)/255
gx=cv2.Sobel(gray,cv2.CV_64F,1,0,ksize=3);gy=cv2.Sobel(gray,cv2.CV_64F,0,1,ksize=3)
texture=float(np.mean(np.hypot(gx,gy)[mask]>.04)) if mask.any() else 0.
yy,xx=np.mgrid[:size[1],:size[0]]
rays2=np.stack([(xx/ratio-k[0,2])/k[0,0],(yy/ratio-k[1,2])/k[1,1]],-1)
predicted=vector[:2]-vector[2]*rays2
predicted/=np.maximum(np.linalg.norm(predicted,axis=-1,keepdims=True),1e-10)
observed=cv2.resize(array(result['up_field'])[0].transpose(1,2,0),size,interpolation=cv2.INTER_AREA)
observed/=np.maximum(np.linalg.norm(observed,axis=-1,keepdims=True),1e-10)
up_error=np.degrees(np.arccos(np.clip(np.sum(observed*predicted,axis=-1),-1,1)))
rays=np.concatenate([rays2,np.ones((*rays2.shape[:2],1))],-1);rays/=np.linalg.norm(rays,axis=-1,keepdims=True)
expected_latitude=np.arcsin(np.clip(rays@vector,-1+1e-6,1-1e-6))
latitude=cv2.resize(array(result['latitude_field'])[0,0],size,interpolation=cv2.INTER_AREA)
lat_error=np.degrees(np.abs(latitude-expected_latitude))
up_weight=cv2.resize(array(result['up_confidence'])[0],size,interpolation=cv2.INTER_AREA)
lat_weight=cv2.resize(array(result['latitude_confidence'])[0],size,interpolation=cv2.INTER_AREA)
up_residual,up_effective,up_cells=weighted_diagnostics(up_error,up_weight,mask)
lat_residual,lat_effective,lat_cells=weighted_diagnostics(lat_error,lat_weight,mask)
return {'up_vector':vector.tolist(),'gravity_uncertainty_deg':uncertainty,'covariance_valid':covariance_valid,
'background_fraction':float(mask.mean()),'valid_rectification_fraction':float(valid.mean()),
'texture_fraction':texture,'up_residual_deg':up_residual,'latitude_residual_deg':lat_residual,
'up_effective_pixels':up_effective,'latitude_effective_pixels':lat_effective,
'up_spatial_cells':up_cells,'latitude_spatial_cells':lat_cells}
def run(request,device='cuda'):
import torch
from geocalib import GeoCalib
if device=='cuda' and not torch.cuda.is_available():raise RuntimeError('Camera-up inference requires CUDA')
if sha256_file(request['weights'])!=WEIGHTS_SHA256:raise ValueError('Camera-up weights checksum differs')
torch.set_num_threads(2)
torch.backends.cuda.matmul.allow_tf32=False;torch.backends.cudnn.allow_tf32=False
model=GeoCalib(weights=request['weights']).eval().to(device)
frames={r['source_frame_index']:r for r in request['frames']};rows=[]
for i,_,_,image in iter_frames(request['video'],request['rotation']):
if i not in frames:continue
row=frames[i];base={'source_frame_index':i,'video_time_s':row['video_time_s'],
'image_sha256':hashlib.sha256(image.tobytes()).hexdigest()}
if row['box'] is None or row['tracking_reason'] is not None:
rows.append({**base,'reason_code':'athlete_background_mask_unavailable'});continue
try:
prepared,mask,valid,focal=prepare_image(image,row['box'],request['camera'])
tensor=torch.from_numpy(prepared[:,:,::-1].copy()).permute(2,0,1).float().to(device)/255
priors={'focal':tensor.new_tensor(focal)} if focal is not None else None
# Fix the NMF decoder's random bases per frame for reproducibility.
torch.manual_seed(0)
result=model.calibrate(tensor,camera_model='pinhole',priors=priors)
item=diagnostics(result,prepared,mask,valid)
if request['camera'] is None:
# Return lens estimates in source pixels, not the resized inference grid.
k=result['camera'].K.detach().cpu().numpy()[0].astype(float)
k[0]*=image.shape[1]/prepared.shape[1]
k[1]*=image.shape[0]/prepared.shape[0]
item['estimated_intrinsics']=k.tolist()
if item['valid_rectification_fraction']<.9:item['reason_code']='insufficient_valid_rectified_image'
rows.append({**base,**item})
del result,tensor
except (RuntimeError,ValueError,KeyError,np.linalg.LinAlgError) as error:
rows.append({**base,'reason_code':'frame_calibration_failed','error_type':type(error).__name__})
if i==max(frames):break
atomic_json(request['output'],{'frames':rows})
def main():
p=argparse.ArgumentParser();p.add_argument('--request',required=True);args=p.parse_args()
try:run(read_json(args.request));return 0
except Exception as error:print('Camera-up inference failed: '+type(error).__name__,flush=True);return 1
if __name__=='__main__':raise SystemExit(main())