Datasets:

Tasks:
Other
ArXiv:
Dataset-Real-World / scripts /tripod_lock.py
ruihong04's picture
4DCodeBench-RealWorld release: 77 videos, 100 dynamic masks, metadata, and the rebuild script for 23 link-only videos
53ed7ea
Raw History Blame Contribute Delete
8.78 kB
"""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()