import sys, csv, importlib.util, numpy as np
spec = importlib.util.spec_from_file_location("olho", r"<SUA_CENTRAL>\07-videos\scripts\olho_quadro_a_quadro.py")
olho = importlib.util.module_from_spec(spec); spec.loader.exec_module(olho)
import cv2
from PIL import Image, ImageDraw
video, saida = sys.argv[1], sys.argv[2]
larg = 540
q, t, fps = olho.ler_quadros(video, 0, None, None, larg)
k = 1080 / larg
rows = []
g0 = cv2.cvtColor(q[0], cv2.COLOR_BGR2GRAY); h, w = g0.shape; c = np.array([w/2, h/2, 1.0])
for i in range(1, len(q)):
    g1 = cv2.cvtColor(q[i], cv2.COLOR_BGR2GRAY)
    p0 = cv2.goodFeaturesToTrack(g0, 600, 0.01, 6)
    M = None; inl = 0; npts = 0
    if p0 is not None and len(p0) >= 6:
        p1, st, _ = cv2.calcOpticalFlowPyrLK(g0, g1, p0, None, winSize=(25, 25), maxLevel=4)
        b = st.ravel() == 1; npts = int(b.sum())
        if npts >= 6:
            M, m = cv2.estimateAffinePartial2D(p0[b], p1[b], method=cv2.RANSAC, ransacReprojThreshold=2.0)
            inl = int(m.sum()) if m is not None else 0
    diff = float(np.abs(g1.astype(np.float32) - g0.astype(np.float32)).mean())
    if M is None:
        rows.append([t[i], i, np.nan, np.nan, np.nan, np.nan, npts, inl, diff])
    else:
        d = M @ c - c[:2]
        rows.append([t[i], i, d[0]*k, d[1]*k, np.degrees(np.arctan2(M[1,0], M[0,0])), float(np.hypot(M[0,0], M[1,0])), npts, inl, diff])
    g0 = g1
with open(saida + ".csv", "w", newline="") as fh:
    wr = csv.writer(fh); wr.writerow(["t","quadro","dx_px1080","dy_px1080","drot_graus","descala","pontos","inliers","dif_media"])
    for r in rows: wr.writerow([round(float(v),4) if isinstance(v,(float,np.floating)) else v for v in r])
print(len(rows), "quadros", fps)
