File size: 3,523 Bytes
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
import pytest
import yaml
from pathlib import Path
from scipy.spatial.transform import Rotation
from baseball_batting.geometry import project,triangulate,barrel_from_independent_knob,to_world
from baseball_batting.motion import angular_velocity,wrapped_difference
from baseball_batting.bat3d import reconstruct_frame
from baseball_batting.temporal3d import fit_sequence

def test_independent_knob_does_not_disambiguate_two_depths():
    k=np.diag([100.,100.,1.])
    with pytest.raises(ValueError,match="ambiguous"):
        barrel_from_independent_knob([0,0,4],[0,0],k,1.)
    np.testing.assert_allclose(barrel_from_independent_knob([0,0,4],[0,0],k,1.,anchor=[0,0,5]),[0,0,5])

def test_triangulation_known_geometry_and_parallel_rejection():
    k=np.array([[800,0,320],[0,800,240],[0,0,1.]])
    a=k@np.c_[np.eye(3),np.zeros(3)];b=k@np.c_[np.eye(3),[-1,0,0]]
    point=np.array([.2,.4,4.]);pixels=np.array([project(point,k),project(point-[1,0,0],k)])
    fitted,error=triangulate(pixels,[a,b])
    np.testing.assert_allclose(fitted,point,atol=1e-8);assert error<1e-8
    with pytest.raises(ValueError,match="parallel"):triangulate([pixels[0],pixels[0]],[a,a])

def test_rotation_log_velocity_wrap_and_missing_interval():
    times=np.array([0,.02,.05,.1,.2]);r=Rotation.from_euler("y",170+times*100,degrees=True).as_matrix()
    rate=angular_velocity(r,times)
    np.testing.assert_allclose(rate[:,1],np.deg2rad(100),atol=1e-8)
    r[2]=np.nan;assert np.isnan(angular_velocity(r,times)).all()
    assert np.isclose(np.degrees(wrapped_difference(np.deg2rad(-179),np.deg2rad(179))),2)

def test_bat_multiview_known_length_and_independence():
    k=np.diag([500.,500.,1.]);cams=[k@np.c_[np.eye(3),[0,0,0]],k@np.c_[np.eye(3),[-1,0,0]]]
    xyz=np.array([[0,0,4],[.8,0,4.]])
    record={"source":"fixture calibrated cameras","independent":True,"synchronization_verified":True,"world_axes":"x_pitcher_y_up_z_right_handed",
            "projection_matrices":np.array(cams).tolist(),"endpoints_pixels":[project(xyz,k).tolist(),project(xyz-[1,0,0],k).tolist()]}
    points,error,space=reconstruct_frame(record,"calibrated_multiview",{},.8)
    np.testing.assert_allclose(points,xyz,atol=1e-8)
    record["independent"]=False
    with pytest.raises(ValueError,match="independent"):reconstruct_frame(record,"calibrated_multiview",{},.8)

def test_temporal_optimizer_reduces_reprojection_and_shares_shape():
    torch=pytest.importorskip("torch")
    n=5;k=torch.tensor([[100.,0,50],[0,100,50],[0,0,1]])
    template=torch.zeros(70,3);template[:,0]=torch.linspace(-.5,.5,70);template[:,1]=torch.linspace(-.4,.4,70)
    def forward(shape,motion,scales,camera):
        return template[None]*(1+shape[0])+motion[:,3:6,None].transpose(1,2)*.01+camera[:,None]
    initial={"motion":torch.zeros(n,136),"shape":torch.zeros(n,45),"scales":torch.zeros(n,68),
             "camera":torch.tensor([[.1,0,3.]]*n),"keypoints":template[None].repeat(n,1,1)+torch.tensor([.1,0,3.]),"intrinsics":k}
    target=template.numpy()+[0,0,3.];pixels=np.repeat(project(target,k.numpy())[None],n,0)
    settings=yaml.safe_load((Path(__file__).resolve().parents[1]/"configs/fitting.yaml").read_text())
    settings.update(adam_steps=10,lbfgs_steps=5,initializer_weight=0,temporal_weight=0)
    fit=fit_sequence(forward,initial,pixels,np.ones((n,70)),np.arange(n)*.01,settings,frame_ids=[0,1,4,5,6])
    assert np.nanmean(fit["reprojection_px"])<.5
    assert fit["shared_shape"].shape==(45,)
    assert np.isfinite(fit["keypoints_m"]).all()