Spaces:
Running on T4
Running on T4
Download baseball_batting/geometry.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 5.83 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/baseball_batting/geometry.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/baseball_batting/geometry.py
-
curl -L -o geometry.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/baseball_batting/geometry.py
5.83 kB
| """Explicit camera geometry, rigid-bat reconstruction and calibrated planar mapping.""" | |
| import numpy as np | |
| from scipy.optimize import least_squares | |
| def matrix(value, shape, name): | |
| array = np.asarray(value, float) | |
| if array.shape != shape or not np.isfinite(array).all(): | |
| raise ValueError(f"{name} must be a finite {shape} matrix") | |
| return array | |
| def intrinsics(value): | |
| k = matrix(value, (3, 3), "intrinsics") | |
| if k[0, 0] <= 0 or k[1, 1] <= 0 or not np.allclose(k[2], [0, 0, 1]): | |
| raise ValueError("Intrinsics require positive focal lengths and homogeneous row [0,0,1]") | |
| return k | |
| def rotation(value): | |
| r = matrix(value, (3, 3), "rotation") | |
| if not np.allclose(r.T @ r, np.eye(3), atol=1e-6) or not np.isclose(np.linalg.det(r), 1, atol=1e-6): | |
| raise ValueError("Rotation must be orthonormal and right-handed") | |
| return r | |
| def project(points, k, distortion=None): | |
| points = np.asarray(points, float) | |
| intrinsic=intrinsics(k) | |
| if distortion is not None: | |
| import cv2 | |
| d=matrix(distortion,(5,),'Brown-Conrady distortion') | |
| result=np.full(points.shape[:-1]+(2,),np.nan) | |
| valid=np.isfinite(points).all(axis=-1)&(points[...,2]>1e-8) | |
| if valid.any(): | |
| result[valid]=cv2.projectPoints(points[valid].reshape(-1,1,3),np.zeros(3),np.zeros(3),intrinsic,d)[0].reshape(-1,2) | |
| return result | |
| homogeneous = points @ intrinsic.T | |
| result = np.full(points.shape[:-1] + (2,), np.nan) | |
| valid = np.isfinite(points).all(axis=-1) & (points[..., 2] > 1e-8) | |
| result[valid] = homogeneous[valid, :2] / homogeneous[valid, 2:3] | |
| return result | |
| def to_world(points, calibration): | |
| transform = calibration.get("world_from_camera") | |
| if not transform or not calibration.get("source") or calibration.get("world_axes") != "x_pitcher_y_up_z_right_handed": | |
| raise ValueError("A documented camera-to-world transform and world axes are required") | |
| r = rotation(transform["rotation"]) | |
| t = matrix(transform["translation_m"], (3,), "world translation") | |
| return np.asarray(points) @ r.T + t | |
| def ground_pixels_to_metres(points, calibration): | |
| if not calibration.get("source") or calibration.get("ground_plane_verified") is not True: | |
| raise ValueError("Documented ground-plane calibration is required") | |
| h = matrix(calibration["ground_homography_pixels_to_xz_metres"], (3, 3), "homography") | |
| if abs(np.linalg.det(h)) < 1e-12: | |
| raise ValueError("Ground homography is singular") | |
| points = np.asarray(points, float) | |
| homogeneous = np.concatenate([points, np.ones(points.shape[:-1] + (1,))], axis=-1) @ h.T | |
| return homogeneous[..., :2] / np.where(abs(homogeneous[..., 2:3]) > 1e-12, homogeneous[..., 2:3], np.nan) | |
| def triangulate(pixels, cameras, max_reprojection_px=3., min_ray_angle_deg=2.): | |
| """Calibrated synchronized views; reject degenerate ray geometry and behind-camera points.""" | |
| pixels, cameras = np.asarray(pixels, float), np.asarray(cameras, float) | |
| valid = np.isfinite(pixels).all(axis=1) | |
| if cameras.shape != (len(pixels), 3, 4) or valid.sum() < 2: | |
| raise ValueError("At least two calibrated synchronized endpoint observations are required") | |
| pixels, cameras = pixels[valid], cameras[valid] | |
| centers, rays, equations = [], [], [] | |
| for point, camera in zip(pixels, cameras): | |
| if np.linalg.matrix_rank(camera[:, :3]) < 3: | |
| raise ValueError("Degenerate camera projection") | |
| centers.append(-np.linalg.solve(camera[:, :3], camera[:, 3])) | |
| direction = np.linalg.solve(camera[:, :3], [*point, 1.]) | |
| rays.append(direction / np.linalg.norm(direction)) | |
| equations.extend([point[0]*camera[2]-camera[0], point[1]*camera[2]-camera[1]]) | |
| angles = [np.degrees(np.arccos(np.clip(abs(np.dot(a, b)), -1, 1))) | |
| for i, a in enumerate(rays) for b in rays[i+1:]] | |
| if max(angles) < min_ray_angle_deg: | |
| raise ValueError("Triangulation rays are too nearly parallel") | |
| _, _, vectors = np.linalg.svd(equations) | |
| if abs(vectors[-1, 3]) < 1e-10: | |
| raise ValueError("Triangulation is at infinity") | |
| initial = vectors[-1, :3] / vectors[-1, 3] | |
| def residual(point): | |
| image = cameras @ np.r_[point, 1.] | |
| return (image[:, :2] / image[:, 2:3] - pixels).ravel() | |
| fit = least_squares(residual, initial, loss="soft_l1") | |
| depths = (cameras @ np.r_[fit.x, 1.])[:, 2] | |
| errors = np.linalg.norm(residual(fit.x).reshape(-1, 2), axis=1) | |
| if not fit.success or (depths <= 0).any() or errors.max() > max_reprojection_px: | |
| raise ValueError("Triangulation failed cheirality or reprojection checks") | |
| return fit.x, float(errors.max()) | |
| def barrel_from_independent_knob(knob, barrel_pixel, k, length, anchor=None, tolerance_m=.03): | |
| """Sphere/ray intersection; two positive solutions remain ambiguous without an anchor.""" | |
| knob = matrix(knob, (3,), "independent knob position") | |
| ray = np.linalg.solve(intrinsics(k), [*barrel_pixel, 1.]) | |
| ray /= np.linalg.norm(ray) | |
| along = np.dot(ray, knob) | |
| discriminant = along**2 - np.dot(knob, knob) + length**2 | |
| if discriminant < -1e-10: | |
| raise ValueError("Endpoint ray and known bat length disagree") | |
| depths = [along + np.sqrt(max(discriminant, 0)), along - np.sqrt(max(discriminant, 0))] | |
| candidates = [depth*ray for depth in depths if depth > 0] | |
| if len(candidates) == 2 and np.linalg.norm(candidates[0]-candidates[1]) < 1e-6: | |
| candidates = candidates[:1] | |
| if anchor is not None: | |
| errors = [np.linalg.norm(point - np.asarray(anchor)) for point in candidates] | |
| candidates = [point for point, error in zip(candidates, errors) if error <= tolerance_m] | |
| if len(candidates) != 1: | |
| raise ValueError("Bat endpoint depths remain ambiguous") | |
| return candidates[0] | |