#!/usr/bin/env python3 """ Local OpenCV fitting / warping server for image-register.html. The browser does the picking; this server does the "machinery" with OpenCV: fitting the IR->RGB transform and warping the IR onto the RGB. Nothing is hand-implemented — it's cv2.findHomography / estimateAffinePartial2D / warpPerspective. Run: python fit_server.py # http://localhost:8000 python fit_server.py --port 8010 Then open http://localhost:8000/ (the server also serves image-register.html, so it's same-origin — no CORS headache). Loading a folder still uses the normal folder picker in the browser. Endpoints (all CORS-enabled): GET / or /image-register.html -> the app HTML POST /fit {correspondences:[{ir:[x,y],rgb:[x,y]},...], ransac_thresh} -> {ok, n_pairs, models:{h_rn, h_ls, s_rn, s_ls}} # h_* = 8-DOF homography, s_* = 3-DOF scale+translation (no rotation); # *_rn = RANSAC (robust), *_ls = least-squares over all pairs POST /warp {matrix:[[...3x3...]], ir_png_b64, rgb_w, rgb_h} -> {ok, warp_png_b64} # warped IR as an RGBA PNG (transparent outside its footprint) """ import argparse, base64, json, os, traceback from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import numpy as np import cv2 HTML_PATH = "image-register.html" # ── the OpenCV machinery ──────────────────────────────────────────────────── def fit_models(ir, rgb, thresh): """Fit IR->RGB with three cv2 estimators; return matrices + RMSE + inliers.""" ir = np.asarray(ir, np.float64) rgb = np.asarray(rgb, np.float64) n = len(ir) models = {} def rmse_persp(H, mask=None): proj = cv2.perspectiveTransform(ir.reshape(-1, 1, 2), H).reshape(-1, 2) d2 = np.sum((proj - rgb) ** 2, axis=1) if mask is not None: d2 = d2[mask.ravel().astype(bool)] return float(np.sqrt(np.mean(d2))) if len(d2) else float("nan") def sim_card(M, label, mask=None): """Package a 2x3 scale+translation matrix M as a model card (matrix + stats). If `mask` is given the RMSE is measured over inliers only; otherwise over all pairs. Scale+translation = [[s,0,tx],[0,s,ty]] — uniform scale s=M[0,0], no rotation, translation (tx,ty).""" proj = cv2.transform(ir.reshape(-1, 1, 2), M).reshape(-1, 2) d2 = np.sum((proj - rgb) ** 2, axis=1) inl = mask.ravel().astype(bool) if mask is not None else np.ones(n, bool) card = {"label": label, "dof": 3, "matrix": np.vstack([M, [0, 0, 1]]).tolist(), "n": n, "rmse": float(np.sqrt(np.mean(d2[inl]))) if inl.sum() else float("nan"), "scale": float(M[0, 0]), "rotation_deg": 0.0, # rotation is fixed at 0 by construction "translation": [float(M[0, 2]), float(M[1, 2])]} if mask is not None: # RANSAC card advertises inliers card["inliers"] = int(inl.sum()) return card def fit_scale_trans(irp, rgbp): """Least-squares scale+translation over the given point subset. Each pair (x,y)->(X,Y) gives s·x + tx = X and s·y + ty = Y, linear in [s, tx, ty]. Stack all rows and lstsq. Returns a 2x3 matrix.""" m = len(irp) A = np.zeros((2 * m, 3)); rhs = np.zeros(2 * m) A[0::2] = np.column_stack([irp[:, 0], np.ones(m), np.zeros(m)]) A[1::2] = np.column_stack([irp[:, 1], np.zeros(m), np.ones(m)]) rhs[0::2] = rgbp[:, 0]; rhs[1::2] = rgbp[:, 1] s, tx, ty = np.linalg.lstsq(A, rhs, rcond=None)[0] return np.array([[s, 0, tx], [0, s, ty]], np.float64) # 8-DOF projective homography — RANSAC (robust, rejects outliers) H, mask = cv2.findHomography(ir, rgb, cv2.RANSAC, thresh) if H is not None: models["h_rn"] = {"label": "8-DOF homography · RANSAC", "dof": 8, "matrix": H.tolist(), "n": n, "inliers": int(mask.sum()), "rmse": rmse_persp(H, mask)} # 8-DOF projective homography — plain least-squares over all pairs Hls, _ = cv2.findHomography(ir, rgb, 0) if Hls is not None: models["h_ls"] = {"label": "8-DOF homography · least-squares", "dof": 8, "matrix": Hls.tolist(), "n": n, "rmse": rmse_persp(Hls)} # 3-DOF scale+translation — RANSAC. OpenCV has no partial-affine estimator # without rotation, so we roll our own: repeatedly fit from a minimal 2-point # sample, count inliers within `thresh`, keep the best consensus set, then # refit least-squares over those inliers. Deterministic seed → stable output. if n >= 2: rng = np.random.default_rng(0) best_inl, best_count = None, -1 for _ in range(2000): i, j = rng.choice(n, 2, replace=False) Mi = fit_scale_trans(ir[[i, j]], rgb[[i, j]]) if not np.isfinite(Mi).all(): continue proj = cv2.transform(ir.reshape(-1, 1, 2), Mi).reshape(-1, 2) inl = np.sqrt(np.sum((proj - rgb) ** 2, axis=1)) < thresh if int(inl.sum()) > best_count: best_count, best_inl = int(inl.sum()), inl if best_inl is not None and best_inl.sum() >= 2: M = fit_scale_trans(ir[best_inl], rgb[best_inl]) models["s_rn"] = sim_card(M, "3-DOF scale+translation · RANSAC", best_inl.reshape(-1, 1).astype(np.uint8)) # 3-DOF scale+translation — plain least-squares over all pairs. Mls = fit_scale_trans(ir, rgb) models["s_ls"] = sim_card(Mls, "3-DOF scale+translation · least-squares") return {"ok": True, "n_pairs": n, "models": models} def warp_layer(matrix, ir_bgr, rw, rh): """Warp IR into RGB space by `matrix`; return an RGBA PNG (base64) that is opaque inside the IR footprint and transparent outside.""" M = np.asarray(matrix, np.float64) warp = cv2.warpPerspective(ir_bgr, M, (rw, rh)) mask = cv2.warpPerspective(np.full(ir_bgr.shape[:2], 255, np.uint8), M, (rw, rh)) b, g, r = cv2.split(warp) bgra = cv2.merge([b, g, r, mask]) # cv2 PNG expects BGRA ok, buf = cv2.imencode(".png", bgra) return base64.b64encode(buf).decode() # ── tiny HTTP server ──────────────────────────────────────────────────────── class Handler(BaseHTTPRequestHandler): def _cors(self): self.send_header("Access-Control-Allow-Origin", "*") self.send_header("Access-Control-Allow-Headers", "Content-Type") self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") def _send(self, body, code=200, ctype="application/json"): if isinstance(body, (dict, list)): body = json.dumps(body).encode() elif isinstance(body, str): body = body.encode() self.send_response(code); self._cors() self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def do_OPTIONS(self): self.send_response(204); self._cors(); self.end_headers() def do_GET(self): if self.path.split("?")[0] in {"/", "/image-register.html"} and os.path.exists(HTML_PATH): self._send(open(HTML_PATH, "rb").read(), ctype="text/html; charset=utf-8") else: self._send({"ok": False, "error": "not found"}, 404) def do_POST(self): n = int(self.headers.get("Content-Length", 0)) try: data = json.loads(self.rfile.read(n) or b"{}") except Exception as e: return self._send({"ok": False, "error": f"bad json: {e}"}, 400) try: if self.path == "/fit": pts = data["correspondences"] if len(pts) < 4: return self._send({"ok": False, "error": "need ≥4 correspondences"}, 400) ir = [p["ir"] for p in pts]; rgb = [p["rgb"] for p in pts] self._send(fit_models(ir, rgb, float(data.get("ransac_thresh", 6)))) elif self.path == "/warp": irbuf = base64.b64decode(data["ir_png_b64"]) ir = cv2.imdecode(np.frombuffer(irbuf, np.uint8), cv2.IMREAD_COLOR) b64 = warp_layer(data["matrix"], ir, int(data["rgb_w"]), int(data["rgb_h"])) self._send({"ok": True, "warp_png_b64": b64}) else: self._send({"ok": False, "error": "unknown endpoint"}, 404) except Exception as e: traceback.print_exc() self._send({"ok": False, "error": str(e)}, 500) def log_message(self, *a): pass # quiet def main(): global HTML_PATH ap = argparse.ArgumentParser() ap.add_argument("--port", type=int, default=8000) ap.add_argument("--html", default=HTML_PATH) args = ap.parse_args() HTML_PATH = args.html print(f"image-register fit server → http://localhost:{args.port}/ (serving {HTML_PATH})") print("Open that URL, load a folder, pick points, Fit. Ctrl-C to stop.") ThreadingHTTPServer(("127.0.0.1", args.port), Handler).serve_forever() if __name__ == "__main__": main()