baseball-engine / baseball_batting /automatic_pitcher_direction.py
github-actions[bot]
Automated Deploy: 83dd0e037548607e097653f87bce7ef9d342efc6
9ec8d34
Raw History Blame Contribute Delete
11.2 kB
"""Legacy experimental field direction from a visible home-plate outline.
Not called by motion uploads; body_pitcher_direction is the automatic path.
No stance or stride defines the field axis. Camera height cancels when the
outline is intersected with a level floor. Shape/temporal checks are engineering
checks, not a calibrated probability or proof that a practice plate is aligned.
"""
from pathlib import Path
import math
import numpy as np
from .camera_up_provider import CAMERA_FRAME
from .storage import sha256_file
METHOD = 'automatic_home_plate_floor_geometry_v1'
# Clockwise outline in arbitrary units: broad front edge, sides, rear point.
# Direction toward the pitcher is negative template Y, not toward the rear tip.
TEMPLATE = np.array([[-.5, 0], [.5, 0], [.5, .5], [0, 1], [-.5, .5]])
LIMITS = {'sample_count': 9, 'minimum_frames': 3, 'minimum_coverage': .5,
'maximum_shape_error': .065, 'maximum_direction_spread_deg': 8.,
'maximum_sensitivity_deg': 10., 'minimum_outline_area_px': 160.,
'maximum_candidates_per_frame': 24}
def reference(reason='home_plate_not_detected'):
return dict(status='unknown', pitcher_vector=None, pitcher_source=None,
coordinate_frame=CAMERA_FRAME, method=METHOD, automatic=True,
applied=False, reliable=False, confidence=None,
accuracy_validated=False, reason_code=reason, limits=dict(LIMITS),
implementation_sha256=sha256_file(Path(__file__)),
assumptions=['visible_object_is_home_plate', 'plate_is_aligned_toward_pitcher',
'plate_lies_on_level_floor'],
plate_alignment_verified=False,
reliability_kind='shape_temporal_and_sensitivity_checks; not validated accuracy')
def outlines(image, athlete_box=None):
"""Bounded white convex pentagon proposals, in original upright pixels."""
import cv2
h, w = image.shape[:2]
scale = min(1., 1280 / max(h, w))
small = cv2.resize(image, (round(w*scale), round(h*scale)), interpolation=cv2.INTER_AREA)
hsv = cv2.cvtColor(small, cv2.COLOR_BGR2HSV)
proposals = []
for brightness in (120, 165, 205):
mask = ((hsv[:, :, 1] < 95) & (hsv[:, :, 2] >= brightness)).astype('uint8') * 255
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in sorted(contours, key=cv2.contourArea, reverse=True)[:100]:
area = cv2.contourArea(contour)
if not LIMITS['minimum_outline_area_px'] <= area <= .08*small.shape[0]*small.shape[1]:
continue
perimeter = cv2.arcLength(contour, True)
for epsilon in (.012, .02, .03):
polygon = cv2.approxPolyDP(contour, epsilon*perimeter, True)
if len(polygon) != 5 or not cv2.isContourConvex(polygon):
continue
p = polygon[:, 0, :].astype(float)/scale
if np.any(p < 2) or np.any(p[:, 0] > w-3) or np.any(p[:, 1] > h-3):
continue # A clipped silhouette is not a complete plate.
if athlete_box is not None:
x1, y1, x2, y2 = athlete_box
if np.any((p[:, 0] >= x1) & (p[:, 0] <= x2) & (p[:, 1] >= y1) & (p[:, 1] <= y2)):
continue
if any(np.linalg.norm(p.mean(0)-q.mean(0)) < 5/scale for q in proposals):
continue
proposals.append(p)
break
return proposals[:LIMITS['maximum_candidates_per_frame']]
def fit_outline(pixels, camera, up):
"""Recover direction by fitting the known plate shape on the floor."""
from .pitcher_direction import _rays, _unit, Unreliable
rays, _ = _rays(pixels, camera)
up = _unit(up)
incidence = _unit(rays) @ up
if np.any(incidence >= -math.sin(math.radians(5))):
raise Unreliable('plate_too_near_horizon')
points = -rays/(rays @ up)[:, None]
template = TEMPLATE-TEMPLATE.mean(0)
fits = []
for reverse in (False, True):
order = np.arange(5)[::-1] if reverse else np.arange(5)
for offset in range(5):
ordered = points[np.roll(order, offset)]
centred = ordered-ordered.mean(0)
u, s, vt = np.linalg.svd(template.T @ centred, full_matrices=False)
rotation = u @ vt
scale = s.sum()/np.sum(template**2)
error = np.linalg.norm(centred-scale*template @ rotation)/np.linalg.norm(centred)
fits.append((float(error), _unit(-rotation[1])))
fits.sort(key=lambda item: item[0])
best_error, direction = fits[0]
if best_error > LIMITS['maximum_shape_error']:
raise Unreliable('outline_does_not_match_home_plate')
for error, other in fits[1:]:
if error <= best_error+.025 and np.dot(direction, other) < math.cos(math.radians(10)):
raise Unreliable('plate_orientation_ambiguous')
return direction, best_error
def checked_outline(pixels, camera, up, up_spread):
"""Reject directions unstable to pixel, lens, or vertical perturbations."""
from .pitcher_direction import _unit, Unreliable
vector, error = fit_outline(pixels, camera, up)
up = _unit(up)
axis = np.eye(3)[np.argmin(np.abs(up))]
a = _unit(axis-np.dot(axis, up)*up)
b = np.cross(up, a)
directions = [vector]
# These perturbations are a stress test, not estimated confidence bounds.
for theta in np.linspace(0, 2*np.pi, 8, endpoint=False):
tilted = math.cos(up_spread)*up + math.sin(up_spread)*(math.cos(theta)*a+math.sin(theta)*b)
directions.append(fit_outline(pixels, camera, tilted)[0])
for factor in (.9, 1.1):
changed = camera.model_copy(update={'fx':camera.fx*factor, 'fy':camera.fy*factor})
directions.append(fit_outline(pixels, changed, up)[0])
for corner in range(5):
for dx, dy in ((-1, -1), (-1, 1), (1, -1), (1, 1)):
changed = np.array(pixels, copy=True)
changed[corner] += [dx, dy]
directions.append(fit_outline(changed, camera, up)[0])
spread = float(np.degrees(np.arccos(np.clip(np.asarray(directions) @ vector, -1, 1))).max())
if spread > LIMITS['maximum_sensitivity_deg']:
raise Unreliable('plate_direction_unstable')
return vector, error, spread
def estimate(video, capture, options, up_reference, track=None, progress=lambda *a: None):
"""Run automatically when neither direction nor floor points were supplied."""
import cv2
from .ingest import iter_frames
from .camera_up import sample_indices
from .motion_contract import MotionCamera
from .pitcher_direction import Unreliable, _unit
out = reference()
if options.camera_stability == 'moving':
return reference('camera_moving')
if options.up_vector is None:
return reference('automatic_up_unavailable')
if up_reference.get('status') == 'estimated' and not up_reference.get('reliable'):
return reference('automatic_up_unreliable')
camera = options.camera
if camera is None:
data = up_reference.get('estimated_camera')
if data is None:
return reference('automatic_camera_calibration_unavailable')
camera = MotionCamera.model_validate(data)
out['camera_calibration'] = camera.model_dump(mode='json')
out['camera_calibration_accuracy_verified'] = False
ids = sample_indices(capture, LIMITS['sample_count'])
if len(ids) < LIMITS['minimum_frames']:
return reference('insufficient_video_frames')
uncertainty = up_reference.get('maximum_model_uncertainty_deg', 1.)
deviation = up_reference.get('maximum_deviation_deg', 0.)
if uncertainty is None or deviation is None or not np.isfinite(uncertainty+deviation):
return reference('automatic_up_uncertainty_unavailable')
up_spread = math.radians(max(1., uncertainty+deviation))
accepted, rows = [], []
progress('pitcher_direction_estimation', 0, len(ids))
try:
for i, _, _, image in iter_frames(video, capture['rotation_degrees']):
if i not in ids:
continue
box = track['boxes'][i] if track and 'boxes' in track else None
matches = []
candidates = outlines(image, box)
for pixels in candidates:
try:
vector, error, spread = checked_outline(pixels, camera, options.up_vector, up_spread)
matches.append(dict(source_frame_index=i, pitcher_vector=vector.tolist(),
corners=pixels.tolist(), shape_error=error,
maximum_sensitivity_deg=spread))
except (Unreliable, ValueError, np.linalg.LinAlgError, cv2.error):
continue
row = dict(source_frame_index=i, candidate_count=len(candidates), matched_plate_count=len(matches))
# Multiple plausible plates do not establish which one is in use.
if len(matches) == 1:
accepted.append(matches[0])
row.update(matches[0])
rows.append(row)
progress('pitcher_direction_estimation', len(rows), len(ids))
if i == ids[-1]:
break
except (ValueError, cv2.error) as error:
out.update(reason_code='automatic_direction_image_processing_failed', error_type=type(error).__name__)
return out
out.update(frames=rows, sampled_frame_count=len(rows), accepted_frame_count=len(accepted))
if any(row['matched_plate_count'] > 1 for row in rows):
out['reason_code'] = 'multiple_home_plates_ambiguous'
return out
if len(accepted) < max(LIMITS['minimum_frames'], math.ceil(.6*len(ids))):
out['reason_code'] = 'insufficient_clear_home_plate_frames'
return out
vectors = np.array([row['pitcher_vector'] for row in accepted])
# Never flip signs or average contradictory estimates into a confident axis.
if np.any(vectors @ vectors.T < math.cos(math.radians(LIMITS['maximum_direction_spread_deg']))):
out['reason_code'] = 'inconsistent_home_plate_direction'
return out
centres = np.array([np.mean(row['corners'], axis=0) for row in accepted])
w, h = image.shape[1], image.shape[0]
if np.max(np.linalg.norm(centres-centres[0], axis=1)) > .01*math.hypot(w, h):
out['reason_code'] = 'plate_or_camera_moved'
return out
frames = capture['frames']
duration = frames[-1]['playback_s']-frames[0]['playback_s']
coverage = (frames[accepted[-1]['source_frame_index']]['playback_s']-
frames[accepted[0]['source_frame_index']]['playback_s'])/duration if duration > 0 else 0.
out['temporal_coverage_fraction'] = coverage
if coverage < LIMITS['minimum_coverage']:
out['reason_code'] = 'insufficient_plate_temporal_coverage'
return out
out.update(status='estimated', pitcher_vector=_unit(vectors.mean(0)).tolist(),
pitcher_source='Automatically detected home-plate outline; estimated camera and floor geometry; plate alignment assumed',
applied=True, reliable=True, reason_code=None)
return out