File size: 8,007 Bytes
16231ab | 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 | #!/usr/bin/env python3
"""Remove visually redundant frames (e.g. SonicUrban walks: standing at a crossing, slow stretches, repeated views).
Embedding: OpenCLIP ViT-B/16 image features (L2-normalised), cached next to the output.
Within each video (--group-column), frames are visited in time order (--time-column) and a frame is kept only if
its cosine similarity to EVERY frame already kept from that video is below --threshold (so a view the walker
returns to later is removed too). Across videos, a kept frame is dropped when it is a near-duplicate
(cosine >= --cross-threshold) of a kept frame from another video (re-uploads, same route filmed twice).
Writes the kept rows (same columns + dedup_max_cosine), <output>.dropped.csv, <output>.quality.json and,
for choosing the thresholds, <output>.examples_<bin>.jpg sheets of frame pairs in several similarity bins.
"""
from __future__ import annotations
import sys as _sys
from pathlib import Path as _Path
_SCRIPTS = next(_p for _p in _Path(__file__).resolve().parents if _p.name == "scripts")
_sys.path[:0] = [str(_SCRIPTS.parent), str(_SCRIPTS.parent / "models")] + [str(_d) for _d in sorted(_SCRIPTS.rglob("*")) if _d.is_dir() and _d.name != "__pycache__"]
import argparse
import json
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import numpy as np
import pandas as pd
def parse_args():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--input", type=Path, required=True)
p.add_argument("--output", type=Path, required=True)
p.add_argument("--path-column", default="photo_path")
p.add_argument("--group-column", default="recording_id")
p.add_argument("--time-column", default="segment_start_seconds")
p.add_argument("--threshold", type=float, default=0.92, help="within-video: drop if cosine to a kept frame >= this")
p.add_argument("--cross-threshold", type=float, default=0.96, help="across videos: drop near-duplicates >= this")
p.add_argument("--openclip-model", default="ViT-B-16")
p.add_argument("--openclip-pretrained", default="laion2b_s34b_b88k")
p.add_argument("--batch-size", type=int, default=128)
p.add_argument("--workers", type=int, default=8)
p.add_argument("--examples", type=int, default=12, help="pairs per similarity bin in the example sheets (0 = none)")
p.add_argument("--device", default="cuda")
return p.parse_args()
def embed(paths, args, cache: Path):
done = {}
if cache.exists():
with np.load(cache, allow_pickle=True) as z:
done = dict(zip(z["keys"], z["features"]))
todo = [q for q in dict.fromkeys(paths) if q not in done]
if todo:
import open_clip
import torch
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
model, _, preprocess = open_clip.create_model_and_transforms(args.openclip_model, pretrained=args.openclip_pretrained,
device=args.device)
model.eval()
def load(q):
with Image.open(q) as im:
im.draft("RGB", (448, 448))
return preprocess(im.convert("RGB"))
print(f"Embedding {len(todo)} frames ({len(done)} cached)", flush=True)
with ThreadPoolExecutor(args.workers) as pool, torch.inference_mode():
for i in range(0, len(todo), args.batch_size):
chunk = todo[i:i + args.batch_size]
x = torch.stack(list(pool.map(load, chunk))).to(args.device)
f = torch.nn.functional.normalize(model.encode_image(x).float(), dim=-1).cpu().numpy().astype(np.float16)
done.update(zip(chunk, f))
if (i // args.batch_size) % 50 == 0:
print(f" {min(i + args.batch_size, len(todo))}/{len(todo)}", flush=True)
np.savez(cache, keys=np.array(list(done), dtype=object), features=np.stack(list(done.values())))
return np.stack([done[q] for q in paths]).astype(np.float32)
def sheet(pairs, paths, out: Path, title_values):
from PIL import Image, ImageDraw
W, H = 300, 170
img = Image.new("RGB", (W * 2 + 10, H * len(pairs)), "white")
d = ImageDraw.Draw(img)
for r, ((i, j), v) in enumerate(zip(pairs, title_values)):
for c, k in enumerate((i, j)):
with Image.open(paths[k]) as im:
im = im.convert("RGB"); im.thumbnail((W, H))
img.paste(im, (c * (W + 10), r * H))
d.text((4, r * H + 4), f"cos {v:.3f}", fill="yellow")
img.save(out, quality=85)
def main():
args = parse_args()
f = pd.read_csv(args.input, low_memory=False).reset_index(drop=True)
paths = f[args.path_column].astype(str).tolist()
E = embed(paths, args, args.output.with_suffix(".openclip_cache.npz"))
keep = np.zeros(len(f), bool)
max_cos = np.zeros(len(f), np.float32)
within_pairs = []
order = f.sort_values([args.group_column, args.time_column]).index.to_numpy()
for _, idx in pd.Series(order).groupby(f.loc[order, args.group_column].to_numpy(), sort=False):
kept = []
for i in idx.to_numpy():
if kept:
s = E[kept] @ E[i]
j = int(np.argmax(s)); max_cos[i] = s[j]
within_pairs.append((kept[j], i, float(s[j])))
if s[j] >= args.threshold:
continue
kept.append(i)
keep[kept] = True
n_within = int(len(f) - keep.sum())
# across videos: compare kept frames block-wise; drop the later video's frame of a near-duplicate pair
ki = np.flatnonzero(keep)
groups = f[args.group_column].astype(str).to_numpy()
cross_drop = np.zeros(len(f), bool)
Ek = E[ki]
for s0 in range(0, len(ki), 4096):
block = Ek[s0:s0 + 4096] @ Ek.T
for a, row in enumerate(block):
i = ki[s0 + a]
hits = np.flatnonzero(row >= args.cross_threshold)
hits = [ki[h] for h in hits if groups[ki[h]] != groups[i] and ki[h] < i and not cross_drop[ki[h]]]
if hits:
cross_drop[i] = True
keep &= ~cross_drop
f["dedup_max_cosine"] = max_cos
f[keep].to_csv(args.output, index=False)
dropped = f[~keep].copy()
dropped["dedup_reason"] = np.where(cross_drop[~keep], "cross_video_duplicate", "within_video_redundant")
dropped.to_csv(args.output.with_suffix(".dropped.csv"), index=False)
per_video = f.assign(kept=keep).groupby(args.group_column).kept.agg(["size", "sum"])
report = {"input_frames": int(len(f)), "kept_frames": int(keep.sum()), "dropped_within_video": n_within,
"dropped_cross_video": int(cross_drop.sum()), "threshold": args.threshold, "cross_threshold": args.cross_threshold,
"videos": int(len(per_video)), "kept_per_video_median": float(per_video["sum"].median()),
"keep_rate_per_video_median": float((per_video["sum"] / per_video["size"]).median()),
"nearest_kept_cosine_quantiles": {str(q): float(np.quantile([p[2] for p in within_pairs], q)) for q in (0.1, 0.25, 0.5, 0.75, 0.9)}
if within_pairs else {}}
args.output.with_suffix(".quality.json").write_text(json.dumps(report, indent=2))
print(json.dumps(report, indent=2))
if args.examples and within_pairs:
rng = np.random.default_rng(0)
wp = np.array([(a, b) for a, b, _ in within_pairs]); wv = np.array([v for *_, v in within_pairs])
for lo, hi in ((0.85, 0.90), (0.90, 0.92), (0.92, 0.95), (0.95, 1.01)):
sel = np.flatnonzero((wv >= lo) & (wv < hi))
if len(sel):
pick = rng.choice(sel, min(args.examples, len(sel)), replace=False)
out = args.output.with_name(args.output.stem + f".examples_{lo:.2f}-{min(hi, 1):.2f}.jpg")
sheet([tuple(wp[k]) for k in pick], paths, out, wv[pick])
print(f"examples: {out}")
if __name__ == "__main__":
main()
|