File size: 3,609 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
"""Camera-movement check for pitch calibration (standard section 17, 'silent camera movement').

A calibration is clicked on one delivery's frame. Before reusing it on another
delivery of the same video, we match background features (ORB) between the two
frames and fit a homography:
  - frames line up (points move < 3 px)       -> reuse as is        (status "same")
  - camera panned/zoomed but match is strong  -> move the 4 points   (status "transferred")
  - no reliable match (cut, big change)       -> do not use it      (status "invalid")
Results are cached per (calibration, delivery)."""
import json
from pathlib import Path

import cv2
import numpy as np

_CACHE = {}


def _gray(p, width=960):
    img = cv2.imread(str(p), cv2.IMREAD_GRAYSCALE)
    if img is None:
        return None, 1.0
    s = width / img.shape[1]
    return cv2.resize(img, (width, int(img.shape[0] * s))), s


def match_homography(ref_img_path, img_path, min_inliers=40, min_ratio=0.3):
    a, sa = _gray(ref_img_path)
    b, sb = _gray(img_path)
    if a is None or b is None:
        return None, "frame image missing"
    orb = cv2.ORB_create(3000)
    ka, da = orb.detectAndCompute(a, None)
    kb, db = orb.detectAndCompute(b, None)
    if da is None or db is None or len(ka) < 20 or len(kb) < 20:
        return None, "too few image features"
    matches = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True).match(da, db)
    if len(matches) < min_inliers:
        return None, f"only {len(matches)} feature matches"
    pa = np.float32([ka[m.queryIdx].pt for m in matches]) / sa
    pb = np.float32([kb[m.trainIdx].pt for m in matches]) / sb
    H, mask = cv2.findHomography(pa, pb, cv2.RANSAC, 4.0)
    if H is None:
        return None, "no consistent camera motion found"
    inl = int(mask.sum())
    if inl < min_inliers or inl / len(matches) < min_ratio:
        return None, f"weak match ({inl}/{len(matches)} inliers)"
    return H, f"{inl}/{len(matches)} inliers"


def transfer_calibration(cal, deliveries_dir, delivery_id):
    key = (cal["calibration_id"], delivery_id)
    if key in _CACHE:
        return _CACHE[key]
    cache_file = Path(deliveries_dir).parent / "calibration" / "transfer_cache.json"
    disk = json.load(open(cache_file)) if cache_file.exists() else {}
    k = "|".join(key)
    if k in disk:
        _CACHE[key] = disk[k]
        return disk[k]
    ref = Path(deliveries_dir) / cal["ref_delivery_id"] / "calib_frame.jpg"
    cur = Path(deliveries_dir) / delivery_id / "calib_frame.jpg"
    H, why = match_homography(ref, cur)
    out = dict(cal)
    if H is None:
        out.update(status="invalid", reason=f"camera view differs from calibration frame: {why}")
    else:
        src_pts = cal.get("points_px") or list((cal.get("named_px") or {}).values())
        pts = cv2.perspectiveTransform(np.float32([src_pts]), H)[0]
        shift = float(np.max(np.linalg.norm(pts - np.float32(src_pts), axis=1)))
        out["shift_px"] = round(shift, 1)
        if shift < 3:
            out.update(status="same", reason=f"camera unchanged ({why})")
        else:
            moved = [[round(float(x), 1), round(float(y), 1)] for x, y in pts]
            if cal.get("points_px"):
                out["points_px"] = moved
            else:
                out["named_px"] = dict(zip(cal["named_px"].keys(), moved))
            out.update(status="transferred", reason=f"camera moved {shift:.0f} px; crease points moved to match ({why})")
    _CACHE[key] = out
    disk[k] = out
    cache_file.parent.mkdir(parents=True, exist_ok=True)
    json.dump(disk, open(cache_file, "w"))
    return out