File size: 5,326 Bytes
1d15e3f | 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 | """Test training and development source videos/photos for geometric overlap on sampled real frames."""
import argparse
import gzip
import hashlib
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import cv2
import numpy as np
from full_coverage_windows import source_arrays
from cave_completion_data import rows_at
def main():
p = argparse.ArgumentParser(description=__doc__)
for k in ("base", "manifest", "output"):
p.add_argument("--" + k, required=True, type=Path)
args = p.parse_args()
cv2.setNumThreads(1)
rows = rows_at(args.manifest)
sets = {
s: sorted({r["source"] for r in rows if r["split"] == s})
for s in ("train", "development")
}
def features(sid):
sift = cv2.SIFT_create(nfeatures=500)
_, video, _ = source_arrays(args.base, sid, False)
base_indices = (
np.linspace(0, len(video) - 1, min(12, len(video))).round().astype(int)
)
frames = []
for i in sorted(set(base_indices)):
gray = cv2.cvtColor(video[i], cv2.COLOR_RGB2GRAY)
pts, desc = sift.detectAndCompute(gray, None)
if desc is not None and len(desc) >= 16:
frames.append(
(
int(i),
np.array([k.pt for k in pts], np.float32),
desc,
gray.shape,
)
)
return sid, frames
with ThreadPoolExecutor(4) as pool:
banks = dict(pool.map(features, sets["train"] + sets["development"]))
def compare(ids):
source, dev = ids
matches = []
bf = cv2.BFMatcher()
for ia, pa, da, (ha, wa) in banks[source]:
for ib, pb, db, (hb, wb) in banks[dev]:
pairs = bf.knnMatch(da, db, k=2)
good = [a for a, b in pairs if a.distance < 0.70 * b.distance]
if len(good) < 16:
continue
rev = {m.queryIdx: m.trainIdx for m in bf.match(db, da)}
good = [m for m in good if rev[m.trainIdx] == m.queryIdx]
if len(good) < 16:
continue
a = np.array([pa[m.queryIdx] for m in good], np.float32)
b = np.array([pb[m.trainIdx] for m in good], np.float32)
H, mask = cv2.findHomography(a, b, cv2.RANSAC, 2)
if H is None:
continue
ok = mask[:, 0] > 0
if ok.sum() < 16 or ok.mean() < 0.60:
continue
support = min(
cv2.contourArea(cv2.convexHull(a[ok])) / (wa * ha),
cv2.contourArea(cv2.convexHull(b[ok])) / (wb * hb),
)
if support < 0.08:
continue
e = np.linalg.norm(
cv2.perspectiveTransform(a[ok, None, :], H)[:, 0] - b[ok], axis=1
)
if np.median(e) <= 1.25:
matches.append(
dict(
train_frame=ia,
dev_frame=ib,
inliers=int(ok.sum()),
support=float(support),
median_px=float(np.median(e)),
)
)
if matches:
best = max(matches, key=lambda m: (m["inliers"], m["support"]))
return dict(
train_source=source,
dev_source=dev,
matched_pairs=len(matches),
best=best,
)
tasks = [(t, d) for t in sets["train"] for d in sets["development"]]
with ThreadPoolExecutor(4) as pool:
hits = [m for m in pool.map(compare, tasks) if m]
flagged = sorted({m["train_source"] for m in hits})
usable = [r for r in rows if r["split"] == "train" and r["source"] not in flagged]
out = dict(
manifest_sha256_uncompressed=hashlib.sha256(
gzip.decompress(args.manifest.read_bytes())
).hexdigest(),
train_sources=len(sets["train"]),
development_sources=len(sets["development"]),
sampled_frames={s: sum(len(banks[i]) for i in ids) for s, ids in sets.items()},
checked_source_pairs=len(tasks),
flagged_training_sources=flagged,
verified_matches=hits,
eligible_counts=dict(Counter(r["kind"] for r in usable)),
eligible_by_scene_kind=dict(
Counter(r["scene"] + "/" + r["kind"] for r in usable)
),
description="Sampled frames only. Matches are conservative leakage flags. An unmatched source is not proof of an independent physical tunnel.",
)
args.output.write_text(json.dumps(out, indent=2, allow_nan=False) + "\n")
print(
json.dumps(
{
k: out[k]
for k in (
"sampled_frames",
"checked_source_pairs",
"flagged_training_sources",
"eligible_counts",
"eligible_by_scene_kind",
)
}
),
flush=True,
)
if __name__ == "__main__":
main()
|