#!/usr/bin/env -S uv run --no-project --with opencv-python-headless --with numpy --with pillow python3 -I """ Georeference an unrectified historical aerial frame (MAGIC / CT State Library scan) against a georeferenced reference image (a CT ECO export in EPSG:6434 described by ref.json: {"bbox":[x0,y0,x1,y1],"size":N}) and warp it onto a property's viewer grid (envelope and cell size of an existing aerial-*.jgw). Writes .jpg/.jgw/.prj and .georef.json. Method: 1. coarse: blurred gradient-magnitude images; brute-force sweep over scale (m per frame px) and rotation; the central part of the frame is slid over the reference with normalized cross-correlation (cv2.matchTemplate TM_CCOEFF_NORMED), which gives scores comparable across scales; 2. fine: ECC affine refinement on gradient images; 3. verify: residual shift of the output against the template image around the grid centre (phase correlation) and the NCC of the gradients there. Both go in the report; the residual is in metres. No relief correction. On hilly ground expect several metres of error away from the matched features. """ import argparse, json, sys import numpy as np, cv2 from PIL import Image Image.MAX_IMAGE_PIXELS = None def load_gray(path): im = Image.open(path) if im.mode != "L": im = im.convert("L") return np.array(im) def grad(a, sigma): a = cv2.GaussianBlur(a.astype(np.float32), (0, 0), sigma) gx = cv2.Sobel(a, cv2.CV_32F, 1, 0); gy = cv2.Sobel(a, cv2.CV_32F, 0, 1) g = np.sqrt(gx * gx + gy * gy); g = g / (np.percentile(g, 99) + 1e-6) return np.clip(g, 0, 1).astype(np.float32) def rotate(img, angle): h, w = img.shape; M = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1.0) cos, sin = abs(M[0, 0]), abs(M[0, 1]); nw, nh = int(h * sin + w * cos), int(h * cos + w * sin) M[0, 2] += nw / 2 - w / 2; M[1, 2] += nh / 2 - h / 2 return cv2.warpAffine(img, M, (nw, nh), flags=cv2.INTER_LINEAR), M def main(): p = argparse.ArgumentParser() p.add_argument("--frame", required=True); p.add_argument("--ref", required=True); p.add_argument("--refmeta", required=True) p.add_argument("--template", required=True); p.add_argument("--prj", required=True); p.add_argument("--out", required=True) p.add_argument("--scales", default="0.3:3.0"); p.add_argument("--angles", default="-6:6:1") p.add_argument("--coarse-px", type=int, default=500); p.add_argument("--fine-px", type=int, default=1800) p.add_argument("--check", default=None); p.add_argument("--min-score", type=float, default=0.0) a = p.parse_args() meta = json.load(open(a.refmeta)); x0, y0, x1, y1 = meta["bbox"]; N = meta["size"] ref_ft_px = (x1 - x0) / N; ref_m_px = ref_ft_px * 0.3048006096 ref_full = load_gray(a.ref); frame_full = load_gray(a.frame) # ---- coarse ------------------------------------------------------------------------------------ c = a.coarse_px / N; ref_c = cv2.resize(ref_full, None, fx=c, fy=c, interpolation=cv2.INTER_AREA) ref_g = grad(ref_c, 2.0); coarse_m_px = ref_m_px / c lo, hi = [float(v) for v in a.scales.split(":")]; scales = []; v = lo while v <= hi * 1.0001: scales.append(v); v *= 1.06 alo, ahi, ast = [float(v) for v in a.angles.split(":")]; angles = np.arange(alo, ahi + 1e-9, ast) best = None; table = [] for mpp in scales: s = mpp / coarse_m_px fr = cv2.resize(frame_full, None, fx=s, fy=s, interpolation=cv2.INTER_AREA) for ang in angles: fr_r, M = rotate(fr, ang); fg = grad(fr_r, 2.0) h, w = fg.shape; th, tw = min(h, int(ref_g.shape[0] * 0.8)), min(w, int(ref_g.shape[1] * 0.8)) oy, ox = (h - th) // 2, (w - tw) // 2; tpl = fg[oy:oy + th, ox:ox + tw] if th < 40 or tw < 40: continue r = cv2.matchTemplate(ref_g, tpl, cv2.TM_CCOEFF_NORMED); _, score, _, loc = cv2.minMaxLoc(r) if best is None or score > best["score"]: best = dict(score=float(score), mpp=mpp, ang=float(ang), s=s, M=M, oy=oy, ox=ox, loc=loc) table.append((mpp, best["score"])) print(f" scale {mpp:.2f} m/px -> best so far {best['score']:.3f} at {best['mpp']:.2f} m/px {best['ang']:+.0f} deg", file=sys.stderr) if best["score"] < a.min_score: sys.exit(f"coarse score {best['score']:.3f} below {a.min_score}; refusing to write") print(f"coarse: {best['mpp']:.3f} m/px, {best['ang']:+.1f} deg, score {best['score']:.3f}", file=sys.stderr) S = np.array([[best["s"], 0, 0], [0, best["s"], 0], [0, 0, 1]], np.float64); R = np.vstack([best["M"], [0, 0, 1]]) Crop = np.array([[1, 0, -best["ox"]], [0, 1, -best["oy"]], [0, 0, 1]], np.float64) Place = np.array([[1, 0, best["loc"][0]], [0, 1, best["loc"][1]], [0, 0, 1]], np.float64) T_frame_to_refc = Place @ Crop @ R @ S # ---- fine (ECC affine) ------------------------------------------------------------------------- f = min(1.0, a.fine_px / N); ref_f = cv2.resize(ref_full, None, fx=f, fy=f, interpolation=cv2.INTER_AREA); ref_fg = grad(ref_f, 1.2) Up = np.array([[f / c, 0, 0], [0, f / c, 0], [0, 0, 1]], np.float64); T0 = Up @ T_frame_to_refc pre = cv2.warpPerspective(frame_full, T0, (ref_f.shape[1], ref_f.shape[0]), flags=cv2.INTER_AREA) pre_g = grad(pre, 1.2); maskv = cv2.erode((pre > 0).astype(np.uint8), np.ones((15, 15), np.uint8)) warp = np.eye(2, 3, dtype=np.float32); ecc = None try: ecc, warp = cv2.findTransformECC(ref_fg, pre_g, warp, cv2.MOTION_AFFINE, (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 300, 1e-7), maskv, 7) ecc = float(ecc) except cv2.error as e: print("ECC refinement failed; keeping the coarse solution", file=sys.stderr) Wa = np.vstack([warp, [0, 0, 1]]).astype(np.float64); T_frame_to_reff = np.linalg.inv(Wa) @ T0 # ---- compose to the viewer grid ---------------------------------------------------------------- A, D, B, E, C, F = [float(v) for v in open(a.template).read().split()] tmpl = np.array(Image.open(a.template[:-4] + ".jpg").convert("L")); Hh, W = tmpl.shape reff2world = np.array([[ref_ft_px / f, 0, x0], [0, -ref_ft_px / f, y1], [0, 0, 1]]) world2out = np.array([[1 / A, 0, -C / A], [0, 1 / E, -F / E], [0, 0, 1]]) Mout = world2out @ reff2world @ T_frame_to_reff out = cv2.warpPerspective(frame_full, Mout, (W, Hh), flags=cv2.INTER_AREA, borderValue=0) # ---- verify against the template around the grid centre --------------------------------------- og, tg = grad(out, 1.5), grad(tmpl, 1.5); cy, cx = Hh // 2, W // 2; r = min(Hh, W) // 3 ow, tw_ = og[cy - r:cy + r, cx - r:cx + r], tg[cy - r:cy + r, cx - r:cx + r] ncc = float(np.corrcoef(ow.ravel(), tw_.ravel())[0, 1]) if ow.std() > 0 else 0.0 (sx, sy), resp = cv2.phaseCorrelate(tw_, ow); shift_m = float(np.hypot(sx * A, sy * A) * 0.3048006096) print(f"fine: ECC {ecc if ecc is not None else float('nan'):.3f}; verify: gradient NCC {ncc:.3f}, residual shift {shift_m:.1f} m (resp {resp:.3f})", file=sys.stderr) Image.fromarray(out).save(a.out + ".jpg", quality=90) open(a.out + ".jgw", "w").write(open(a.template).read()); open(a.out + ".prj", "w").write(open(a.prj).read()) report = {"frame": a.frame, "ref": a.ref, "coarse": {"score": best["score"], "m_per_frame_px": best["mpp"], "rotation_deg": best["ang"]}, "ecc": ecc, "verify_centre": {"gradient_ncc": round(ncc, 3), "residual_shift_m": round(shift_m, 1), "phase_resp": round(float(resp), 3)}, "coverage_of_grid": round(float((out > 0).mean()), 3), "model": "similarity (coarse) + affine (ECC); no relief correction", "frame_to_ref_px": T_frame_to_reff.tolist(), "ref_scale_factor": f, "scale_table": table} json.dump(report, open(a.out + ".georef.json", "w"), indent=1); print(json.dumps({k: report[k] for k in ("coarse", "ecc", "verify_centre", "coverage_of_grid")})) if a.check: tile = 100; yy, xx = np.mgrid[0:Hh, 0:W]; cb = ((yy // tile + xx // tile) % 2).astype(bool) Image.fromarray(np.where(cb, out, tmpl)).save(a.check) if __name__ == "__main__": main()