File size: 6,654 Bytes
ea1a74e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
"""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")