baseball-engine / tests /test_automatic_pitcher_direction.py
github-actions[bot]
Automated Deploy: 3ea2037ab7d55d5b498f7e2ea0336818fc24f725
fe40b87
Raw History Blame Contribute Delete
8.34 kB
"""Independent projected geometry and video-level automatic direction checks.
Synthetic accuracy verifies geometry, not home-plate recognition in real footage.
"""
import av
import cv2
import numpy as np
import pytest
from scipy.spatial.transform import Rotation
from baseball_batting.automatic_pitcher_direction import outlines, fit_outline, checked_outline, estimate, METHOD
from baseball_batting.motion_contract import MotionInput, MotionCamera
from baseball_batting.geometry import project
from baseball_batting.ingest import ingest
from baseball_batting.motion_export import export_motion
from baseball_batting.camera_up import consensus
from baseball_batting.pitcher_direction import Unreliable
from test_motion_player import raw_for
from test_camera_up import evidence, capture as up_capture
K = np.array([[1200., 0, 640], [0, 1200, 360], [0, 0, 1]])
CAMERA = MotionCamera(fx=1200, fy=1200, cx=640, cy=360, source='Synthetic camera truth', calibration_status='calibrated')
def plate(angle=30., tilt=(0, 0, 0)):
# Physical front-left, front-right, rear-right, rear tip, rear-left corners.
# Independently expressed in metres; do not import the production template.
corners = np.array([[-.2159, 0], [.2159, 0], [.2159, .2159], [0, .4318], [-.2159, .2159]])
direction = np.array([np.cos(np.radians(angle)), 0., np.sin(np.radians(angle))])
across = np.cross([0, -1, 0], direction)
points = [0, 1, 4.5]+corners[:, 0, None]*across-corners[:, 1, None]*direction
rotation = Rotation.from_euler('xyz', tilt, degrees=True).as_matrix()
return project(points @ rotation.T, K), rotation @ direction, rotation @ [0., -1., 0.]
def frame(angle=30., rectangle=False):
image = np.full((720, 1280, 3), (20, 65, 30), np.uint8)
if rectangle:
cv2.rectangle(image, (500, 500), (650, 570), (240, 240, 240), -1)
else:
pixels, _, _ = plate(angle)
cv2.fillConvexPoly(image, np.rint(pixels).astype('int32'), (240, 240, 240))
return image
def video_file(tmp_path, angles=None, rectangle=False):
path = tmp_path/'plate.mp4'
with av.open(str(path), 'w') as output:
stream = output.add_stream('libx264', rate=30)
stream.width, stream.height, stream.pix_fmt = 1280, 720, 'yuv420p'
stream.options = {'crf':'0', 'bf':'0'}
for angle in angles or [30.]*13:
for packet in stream.encode(av.VideoFrame.from_ndarray(frame(angle, rectangle), format='bgr24')):
output.mux(packet)
for packet in stream.encode():
output.mux(packet)
return path
def automatic_up():
return {'status':'estimated', 'reliable':True, 'up_vector':[0, -1, 0],
'up_source':'Synthetic image-provider output', 'coordinate_frame':'upright_camera_x_right_y_down_z_away',
'maximum_model_uncertainty_deg':1., 'maximum_deviation_deg':0.,
'estimated_camera':{**CAMERA.model_dump(), 'calibration_status':'estimated'}}
@pytest.mark.parametrize('angle', [0, 30, 60, 90, 135, 180, 225, 270])
@pytest.mark.parametrize('tilt', [(0, 0, 0), (4, -8, 12)])
def test_plate_geometry_recovers_true_direction_with_tilt_and_unknown_corner_order(angle, tilt):
pixels, truth, up = plate(angle, tilt)
for order in (pixels, np.roll(pixels, 2, axis=0), pixels[::-1]):
direction, error = fit_outline(order, CAMERA, up)
np.testing.assert_allclose(direction, truth, atol=1e-10)
assert error < 1e-10
@pytest.mark.parametrize('angle', [0, 30, 60, 135, 180, 225])
def test_pixel_detector_and_sensitivity_checks_recover_rendered_direction(angle):
proposals = outlines(frame(angle))
assert len(proposals) == 1
direction, error, spread = checked_outline(proposals[0], CAMERA, [0, -1, 0], np.radians(1))
_, truth, _ = plate(angle)
assert np.degrees(np.arccos(np.clip(direction @ truth, -1, 1))) < 2
assert error < .065 and spread < 10
def test_rectangles_people_and_regular_pentagons_do_not_supply_a_direction():
assert outlines(frame(rectangle=True)) == []
assert outlines(frame(), [0, 0, 1280, 720]) == []
angles = np.arange(5)*2*np.pi/5
floor = np.stack([.3*np.cos(angles), np.ones(5), 4.5+.3*np.sin(angles)], axis=1)
with pytest.raises(Unreliable, match='does_not_match'):
fit_outline(project(floor, K), CAMERA, [0, -1, 0])
def test_default_request_uses_automatic_camera_and_no_direction_inputs(tmp_path):
path = video_file(tmp_path)
options = MotionInput() # No direction, handedness, camera or floor-point input.
capture = ingest(path, options.metadata())
calculated = options.model_copy(update={'up_vector':(0, -1, 0), 'up_source':'Automatic image estimate'})
result = estimate(path, capture, calculated, automatic_up())
assert result['status'] == 'estimated', result
assert result['automatic'] and result['method'] == METHOD and result['applied']
assert result['confidence'] is None and result['accuracy_validated'] is False
assert result['camera_calibration']['calibration_status'] == 'estimated'
assert options.pitcher_vector is None and options.camera is None
assert result['temporal_coverage_fraction'] == 1
def test_missing_references_and_unclear_video_return_unknown_without_user_prompts(tmp_path):
options = MotionInput()
assert estimate(None, None, options, {})['reason_code'] == 'automatic_up_unavailable'
options = options.model_copy(update={'up_vector':(0, -1, 0), 'up_source':'Automatic'})
assert estimate(None, None, options, {})['reason_code'] == 'automatic_camera_calibration_unavailable'
path = video_file(tmp_path, rectangle=True)
out = estimate(path, ingest(path, {}), options, automatic_up())
assert out['status'] == 'unknown' and out['pitcher_vector'] is None
assert not out['applied']
def test_contradictory_directions_are_not_averaged(tmp_path):
path = video_file(tmp_path, angles=[30.]*6+[210.]*7)
options = MotionInput(up_vector=[0,-1,0], up_source='Synthetic gravity')
out = estimate(path, ingest(path, {}), options, automatic_up())
assert out['status'] == 'unknown' and out['reason_code'] == 'inconsistent_home_plate_direction', out
def test_multiple_visible_plates_are_ambiguous(tmp_path, monkeypatch):
path = video_file(tmp_path)
one, _, _ = plate()
monkeypatch.setattr('baseball_batting.automatic_pitcher_direction.outlines', lambda *a: [one, one.copy()])
out = estimate(path, ingest(path, {}), MotionInput(up_vector=[0,-1,0], up_source='Test'), automatic_up())
assert out['reason_code'] == 'multiple_home_plates_ambiguous' and not out['applied']
@pytest.mark.parametrize('model', ['sam3d', 'gvhmr'])
def test_export_no_longer_uses_plate_detection_as_automatic_direction(tmp_path, model, monkeypatch):
def unexpected(*args, **kwargs):
raise AssertionError('Legacy home-plate detector must not run for motion uploads')
monkeypatch.setattr('baseball_batting.automatic_pitcher_direction.estimate', unexpected)
path = video_file(tmp_path)
options = MotionInput(model=model, annotated_videos=False, single_swing=True,
camera_stability='fixed_verified')
capture = ingest(path, options.metadata())
manifest = export_motion(tmp_path, path, capture, raw_for(capture), options, {'name':'synthetic'},
{'analysis_id':'auto-plate', 'analysis_revision':1}, up_reference=automatic_up())
ref = manifest.coordinates['pitcher_estimation']
assert ref['status'] == 'unknown', ref # This fixture has no body swing.
assert ref['method'] == 'automatic_body_swing_direction_v2'
assert manifest.pipeline['inputs']['pitcher_vector'] is None
assert manifest.pipeline['inputs']['camera'] is None
assert manifest.pipeline['calculation_inputs']['pitcher_vector'] is None
def test_only_consistent_accepted_camera_estimates_are_available_for_scene_geometry():
rows = [evidence(i, estimated_intrinsics=K.tolist()) for i in range(7)]
result = consensus(rows, up_capture(), MotionInput())
assert result['estimated_camera']['fx'] == 1200
assert result['estimated_camera']['calibration_status'] == 'estimated'
rows[0]['estimated_intrinsics'] = (K*np.array([[2,1,1],[1,2,1],[1,1,1]])).tolist()
assert 'estimated_camera' not in consensus(rows, up_capture(), MotionInput())