CRICKET / code /geometry3d.py
d9993r's picture
Add files using upload-large-folder tool
ea1a74e verified
Raw History Blame Contribute Delete
6.65 kB
"""Multi-view geometry for the pitch (standard sections 2, 7.4, 9.1 "3D reconstruction").
World frame (metres): origin at the bowler-end popping crease on the middle-stump line,
y along the pitch towards the batter, z up, x to the right as seen from behind the bowler.
Each camera is calibrated from clicked pitch features with known positions: the four
popping/return crease corners (on the ground) plus, optionally, the base and top of the
middle stump at each end (stump height 71.1 cm). With at least 6 points including one
stump top, we recover the camera's focal length, orientation and position (PnP with a
focal-length search; no checkerboard needed). Two or more calibrated, synchronised views
then give true 3D points by triangulation."""
import cv2
import numpy as np
from pitch import BATTER_STUMPS_Y_M, POPPING_GAP_M, RETURN_HALF_M
STUMP_H = 0.711
WORLD = {
# popping crease meets return crease
"bowler_left": (-RETURN_HALF_M, 0.0, 0.0), "bowler_right": (RETURN_HALF_M, 0.0, 0.0),
"batter_left": (-RETURN_HALF_M, POPPING_GAP_M, 0.0), "batter_right": (RETURN_HALF_M, POPPING_GAP_M, 0.0),
# bowling crease (stump line) meets return crease, 1.22 m behind the popping crease
"bowler_bc_left": (-RETURN_HALF_M, -1.22, 0.0), "bowler_bc_right": (RETURN_HALF_M, -1.22, 0.0),
"batter_bc_left": (-RETURN_HALF_M, BATTER_STUMPS_Y_M, 0.0), "batter_bc_right": (RETURN_HALF_M, BATTER_STUMPS_Y_M, 0.0),
# middle stump, base and top (71.1 cm)
"bowler_stump_base": (0.0, -1.22, 0.0), "bowler_stump_top": (0.0, -1.22, STUMP_H),
"batter_stump_base": (0.0, BATTER_STUMPS_Y_M, 0.0), "batter_stump_top": (0.0, BATTER_STUMPS_Y_M, STUMP_H),
}
GROUND4 = ["bowler_left", "bowler_right", "batter_left", "batter_right"]
MIRROR = {}
for _end in ("bowler", "batter"):
for _a, _b in (("left", "right"), ("bc_left", "bc_right")):
MIRROR[f"{_end}_{_a}"], MIRROR[f"{_end}_{_b}"] = f"{_end}_{_b}", f"{_end}_{_a}"
def named_points(cal):
"""Calibration record -> {name: [x, y]}: the 4 crease clicks (left/right as seen in the
image) plus any stump points."""
pts = {n: p for n, p in zip(GROUND4, cal.get("points_px") or []) if p}
for key in ("named_px", "extra_px"):
pts.update({k: v for k, v in (cal.get(key) or {}).items() if v and k in WORLD})
return pts
def _K(f, w, h):
return np.array([[f, 0, w / 2], [0, f, h / 2], [0, 0, 1]], float)
def _fit(names, img, f, w, h):
obj = np.float64([WORLD[n] for n in names])
K = _K(f, w, h)
img = np.float64(img)
try: # SQPnP copes with mostly-flat point sets (side-on views)
ok, rv, tv = cv2.solvePnP(obj, img, K, None, flags=cv2.SOLVEPNP_SQPNP)
except cv2.error:
ok = False
if not ok:
ok, rv, tv = cv2.solvePnP(obj, img, K, None, flags=cv2.SOLVEPNP_ITERATIVE)
if not ok:
return None
rv, tv = cv2.solvePnPRefineLM(obj, img, K, None, rv, tv)
proj, _ = cv2.projectPoints(obj, rv, tv, K, None)
err = float(np.sqrt(np.mean(np.sum((proj[:, 0] - img) ** 2, axis=1))))
R, _ = cv2.Rodrigues(rv)
depth = (R @ obj.T + tv).T[:, 2]
if (depth <= 0).any():
return None
return {"f": f, "R": R, "t": tv.ravel(), "rms": err}
def calibrate_camera(cal, frame_size, focal_px=None):
"""Full camera calibration from named clicks. Returns None if not enough points.
Left/right in the clicks is image-relative, so both labelings are tried and the
physically valid one (camera in front, lowest reprojection error) is kept."""
w, h = frame_size
pts = named_points(cal)
if len(pts) < 6 or not any(k.endswith("_top") for k in pts):
return None
best = None
# left/right is judged in the image, which is ambiguous for side-on cameras (the crease
# runs away from the lens, and perspective can flip the order of one pair but not the
# other), so try every combination of swapping each crease pair and keep the labeling
# that fits the geometry with the camera in front of every point.
import itertools
pairs = [("bowler_left", "bowler_right"), ("bowler_bc_left", "bowler_bc_right"),
("batter_left", "batter_right"), ("batter_bc_left", "batter_bc_right")]
for mirror in itertools.product((False, True), repeat=4):
swap = {}
for (a_, b_), m in zip(pairs, mirror):
if m:
swap[a_], swap[b_] = b_, a_
names = [swap.get(n, n) for n in pts]
img = np.float64([pts[n] for n in pts])
for f in ([focal_px] if focal_px else np.geomspace(0.3 * w, 5 * w, 60)):
r = _fit(names, img, f, w, h)
if r and (best is None or r["rms"] < best["rms"]):
best = dict(r, mirror=mirror, names=names)
if best is None:
return None
lo, hi = (best["f"], best["f"]) if focal_px else (best["f"] / 1.12, best["f"] * 1.12) # golden-section refine
img = np.float64([pts[n] for n in pts])
for _ in range(30):
a, b = lo + 0.382 * (hi - lo), lo + 0.618 * (hi - lo)
ra, rb = _fit(best["names"], img, a, w, h), _fit(best["names"], img, b, w, h)
ea, eb = (ra or {"rms": 1e9})["rms"], (rb or {"rms": 1e9})["rms"]
if ea < eb:
hi = b
else:
lo = a
r = _fit(best["names"], img, (lo + hi) / 2, w, h) or best
K = _K(r["f"], w, h)
P = K @ np.hstack([r["R"], r["t"][:, None]])
C = (-r["R"].T @ r["t"]).ravel()
return {"P": P.tolist(), "K": K.tolist(), "focal_px": round(float(r["f"]), 1), "reprojection_px": round(r["rms"], 2),
"position_m": [round(float(c), 2) for c in C], "points_used": len(pts), "swapped_pairs": [p[0].replace("_left", "") for p, m in zip(pairs, best["mirror"]) if m],
"frame_size": [w, h]}
def triangulate(Ps, uvs):
"""Linear (DLT) triangulation from 2+ views. Returns (xyz, mean reprojection px)."""
A = []
for P, (u, v) in zip(Ps, uvs):
P = np.asarray(P)
A.append(u * P[2] - P[0])
A.append(v * P[2] - P[1])
_, _, Vt = np.linalg.svd(np.asarray(A))
X = Vt[-1]
X = X[:3] / X[3]
errs = []
for P, (u, v) in zip(Ps, uvs):
x = np.asarray(P) @ np.append(X, 1)
errs.append(np.hypot(x[0] / x[2] - u, x[1] / x[2] - v))
return X, float(np.mean(errs))
def project(P, X):
x = np.asarray(P) @ np.append(np.asarray(X, float), 1)
return x[:2] / x[2]
def angle3(a, b, c):
v1, v2 = np.asarray(a) - b, np.asarray(c) - b
n = np.linalg.norm(v1) * np.linalg.norm(v2)
return float(np.degrees(np.arccos(np.clip(np.dot(v1, v2) / n, -1, 1)))) if n > 1e-9 else float("nan")