File size: 8,780 Bytes
53ed7ea | 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 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | """Virtual-tripod video stabilization: warp every frame back to a reference frame's
coordinate system so the video becomes a fixed-camera shot, then crop to the common
valid region.
Motion model: per consecutive-frame pair, track features (Shi-Tomasi + LK optical
flow) and fit a global transform with RANSAC (dynamic foreground is rejected as
outliers). Transforms are chained to get frame_i -> frame_0, and each frame is
warped by the inverse.
Model choice: 'similarity' (translation+rotation+scale, robust) or 'homography'
(exact for rotation-only camera motion; can overfit when features are sparse).
Diagnostics per video: cumulative drift, crop loss ratio, and background residual
(median optical-flow magnitude on static regions after warping) — a large residual
means parallax from camera translation, i.e. a single 2D warp is insufficient.
Usage:
python tripod_lock.py input.mp4 [input2.mp4 ...] [--model similarity|homography]
[--out-dir output]
"""
import argparse
import json
from pathlib import Path
import cv2
import numpy as np
def read_video(path):
cap = cv2.VideoCapture(str(path))
fps = cap.get(cv2.CAP_PROP_FPS)
frames = []
while True:
ok, f = cap.read()
if not ok:
break
frames.append(f)
cap.release()
if not frames:
raise RuntimeError(f"no frames decoded from {path}")
return frames, fps
def estimate_pairwise(g0, g1, model, feature_mask=None):
p0 = cv2.goodFeaturesToTrack(
g0, maxCorners=1000, qualityLevel=0.01, minDistance=12, mask=feature_mask
)
if p0 is None or len(p0) < 20:
raise RuntimeError("too few features to track")
p1, st, _ = cv2.calcOpticalFlowPyrLK(g0, g1, p0, None)
st = st.ravel().astype(bool)
if model == "similarity":
a, _ = cv2.estimateAffinePartial2D(
p0[st], p1[st], method=cv2.RANSAC, ransacReprojThreshold=2.0
)
if a is None:
raise RuntimeError("RANSAC failed to fit similarity transform")
return np.vstack([a, [0.0, 0.0, 1.0]])
h, _ = cv2.findHomography(p0[st], p1[st], cv2.RANSAC, 2.0)
if h is None:
raise RuntimeError("RANSAC failed to fit homography")
return h
def cumulative_transforms(grays, model, feature_mask=None):
cums = [np.eye(3)]
for i in range(1, len(grays)):
t = estimate_pairwise(grays[i - 1], grays[i], model, feature_mask)
cums.append(t @ cums[-1])
return cums
def common_valid_rect_from_mats(mats, w, h):
"""Intersection over frames of the axis-aligned inner rect of each warped quad."""
corners = np.array([[0, 0], [w, 0], [w, h], [0, h]], np.float64).reshape(-1, 1, 2)
x0, y0, x1, y1 = 0.0, 0.0, float(w), float(h)
for m in mats:
pts = cv2.perspectiveTransform(corners, m).reshape(-1, 2)
xs, ys = np.sort(pts[:, 0]), np.sort(pts[:, 1])
x0, y0 = max(x0, xs[1]), max(y0, ys[1])
x1, y1 = min(x1, xs[2]), min(y1, ys[2])
if x1 - x0 < 64 or y1 - y0 < 64:
raise RuntimeError("camera drift too large: common valid region collapsed")
return int(np.ceil(x0)), int(np.ceil(y0)), int(np.floor(x1)), int(np.floor(y1))
def background_residual(warped_grays, n_samples=6):
"""Median flow magnitude between warped frame pairs on RANSAC-consistent
(static) regions. Measures parallax/estimation residual after locking."""
idx = np.linspace(0, len(warped_grays) - 1, n_samples).astype(int)
mags = []
for a, b in zip(idx[:-1], idx[1:]):
p0 = cv2.goodFeaturesToTrack(
warped_grays[a], maxCorners=500, qualityLevel=0.01, minDistance=15
)
if p0 is None:
continue
p1, st, _ = cv2.calcOpticalFlowPyrLK(warped_grays[a], warped_grays[b], p0, None)
st = st.ravel().astype(bool)
d = np.linalg.norm((p1[st] - p0[st]).reshape(-1, 2), axis=1)
# static background = the majority cluster of near-zero motion; dynamic
# foreground shows large flow and is excluded by taking the lower half
mags.append(np.median(d[d < np.percentile(d, 50)]))
return float(np.median(mags))
def process(path, out_dir, model, extra_crop=(0, 0, 0, 0), start_frame=0,
end_frame=None, ref_frame="0", track_roi=None):
path = Path(path)
frames, fps = read_video(path)
frames = frames[start_frame:end_frame]
h, w = frames[0].shape[:2]
grays = [cv2.cvtColor(f, cv2.COLOR_BGR2GRAY) for f in frames]
ref = len(frames) // 2 if ref_frame == "middle" else int(ref_frame)
feature_mask = None
if track_roi is not None:
x, y, rw, rh = track_roi
feature_mask = np.zeros((h, w), np.uint8)
feature_mask[y:y + rh, x:x + rw] = 255
cums = cumulative_transforms(grays, model, feature_mask)
# frame i -> reference frame coords: cums[ref] @ inv(cums[i])
mats = [cums[ref] @ np.linalg.inv(c) for c in cums]
warped = [cv2.warpPerspective(f, m, (w, h)) for f, m in zip(frames, mats)]
x0, y0, x1, y1 = common_valid_rect_from_mats(mats, w, h)
cl, cr, ct, cb = extra_crop # additional left/right/top/bottom trim
x0, x1, y0, y1 = x0 + cl, x1 - cr, y0 + ct, y1 - cb
if x1 - x0 < 64 or y1 - y0 < 64:
raise RuntimeError("extra crop leaves no usable frame area")
cw, ch = (x1 - x0) // 2 * 2, (y1 - y0) // 2 * 2
out_path = out_dir / f"{path.stem}_locked.mp4"
tmp_path = out_dir / f"{path.stem}_locked_raw.mp4"
vw = cv2.VideoWriter(str(tmp_path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (cw, ch))
for f in warped:
vw.write(f[y0 : y0 + ch, x0 : x0 + cw])
vw.release()
warped_grays = [
cv2.cvtColor(f[y0 : y0 + ch, x0 : x0 + cw], cv2.COLOR_BGR2GRAY) for f in warped
]
last = cums[-1]
report = {
"video": path.name,
"model": model,
"frames": len(frames),
"trim_frames": {"start": start_frame, "end": end_frame},
"reference_frame": ref,
"source_size": [w, h],
"locked_size": [cw, ch],
"crop_rect": {"x": x0, "y": y0, "width": cw, "height": ch},
"extra_crop": {"left": cl, "right": cr, "top": ct, "bottom": cb},
"track_roi": track_roi,
"crop_loss_ratio": round(1 - (cw * ch) / (w * h), 4),
"total_drift_px": {
"dx": round(float(last[0, 2]), 1),
"dy": round(float(last[1, 2]), 1),
},
"total_rotation_deg": round(
float(np.degrees(np.arctan2(last[1, 0], last[0, 0]))), 3
),
"total_scale": round(float(np.hypot(last[0, 0], last[1, 0])), 4),
"background_residual_px": round(background_residual(warped_grays), 3),
}
return tmp_path, out_path, report
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("inputs", nargs="+")
ap.add_argument("--model", choices=["similarity", "homography"], default="similarity")
ap.add_argument("--out-dir", default=str(Path(__file__).parent / "output"))
ap.add_argument("--crop-left", type=int, default=0)
ap.add_argument("--crop-right", type=int, default=0)
ap.add_argument("--crop-top", type=int, default=0)
ap.add_argument("--crop-bottom", type=int, default=0)
ap.add_argument("--start-frame", type=int, default=0)
ap.add_argument("--end-frame", type=int, default=None)
ap.add_argument("--ref-frame", default="0", help="frame index or 'middle'")
ap.add_argument(
"--track-roi", type=lambda value: tuple(map(int, value.split(","))),
help="feature-tracking region as x,y,width,height",
)
args = ap.parse_args()
extra = (args.crop_left, args.crop_right, args.crop_top, args.crop_bottom)
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
reports = []
for p in args.inputs:
tmp, out, rep = process(p, out_dir, args.model, extra,
args.start_frame, args.end_frame, args.ref_frame,
args.track_roi)
# re-encode to h264/yuv420p for playability, then drop the mp4v temp
import subprocess
subprocess.run(
["ffmpeg", "-v", "error", "-y", "-i", str(tmp), "-c:v", "libx264",
"-crf", "18", "-pix_fmt", "yuv420p", str(out)],
check=True,
)
tmp.unlink()
reports.append(rep)
print(json.dumps(rep, indent=2))
report_path = out_dir / "report.json"
existing = json.loads(report_path.read_text()) if report_path.exists() else []
merged = {r["video"]: r for r in existing}
merged.update({r["video"]: r for r in reports})
report_path.write_text(json.dumps(list(merged.values()), indent=2))
print(f"\nreport written to {report_path}")
if __name__ == "__main__":
main()
|