orena-seg / data_preprocessing /process_blue_screen_dataset.py
Gbone3176's picture
Add blue-screen preprocessing scripts
ce16509 verified
Raw History Blame Contribute Delete
13.8 kB
#!/usr/bin/env python3
"""Coarse-to-fine frozen blue-screen detection for endoscopy videos.
Stage 1 decodes each video sequentially and hashes one circular-ROI frame per
second. Stage 2 re-reads only candidate windows and locates exact repeated-frame
runs at native FPS. Inputs are read-only; all results go below --output-dir.
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import socket
import time
from datetime import datetime, timezone
from pathlib import Path
import cv2
import numpy as np
VIDEO_SUFFIXES = {".avi", ".mp4", ".mov", ".mkv"}
def utc_now() -> str:
return datetime.now(timezone.utc).astimezone().isoformat()
def hhmmss(seconds: float) -> str:
ms = int(round(seconds * 1000))
hours, rem = divmod(ms, 3_600_000)
minutes, rem = divmod(rem, 60_000)
secs, millis = divmod(rem, 1000)
return f"{hours:02d}:{minutes:02d}:{secs:02d}.{millis:03d}"
def roi_mask(height: int, width: int) -> np.ndarray:
yy, xx = np.ogrid[:height, :width]
return (((xx - width / 2) / (width * 0.47)) ** 2 +
((yy - height / 2) / (height * 0.47)) ** 2 <= 1)
def frame_features(frame: np.ndarray, mask: np.ndarray, size: int) -> tuple[str, float]:
small = cv2.resize(frame, (size, size), interpolation=cv2.INTER_AREA)
small_mask = cv2.resize(mask.astype(np.uint8), (size, size),
interpolation=cv2.INTER_NEAREST).astype(bool)
pixels = small[small_mask]
digest = hashlib.md5(pixels.tobytes()).hexdigest()
hsv = cv2.cvtColor(small, cv2.COLOR_BGR2HSV)
h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2]
valid = small_mask & (v > 18)
if not valid.any():
return digest, 0.0
blue = valid & (h >= 88) & (h <= 140) & (s >= 55) & (v >= 35)
return digest, float(blue.sum() / valid.sum())
def coarse_scan(video: Path, sample_seconds: float, min_static_seconds: float,
blue_threshold: float, size: int) -> tuple[dict, list[dict]]:
cap = cv2.VideoCapture(str(video))
if not cap.isOpened():
raise RuntimeError("cannot open video")
fps = float(cap.get(cv2.CAP_PROP_FPS) or 0)
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)
if fps <= 0 or frame_count <= 0 or width <= 0 or height <= 0:
cap.release()
raise RuntimeError(f"invalid metadata fps={fps} frames={frame_count} size={width}x{height}")
mask = roi_mask(height, width)
step = max(1, int(round(fps * sample_seconds)))
samples: list[dict] = []
frame_idx = 0
next_sample = 0
while True:
ok, frame = cap.read()
if not ok:
break
if frame_idx >= next_sample:
digest, ratio = frame_features(frame, mask, size)
samples.append({"frame": frame_idx, "time": frame_idx / fps,
"hash": digest, "blue_ratio": ratio})
next_sample += step
frame_idx += 1
cap.release()
if frame_idx < frame_count * 0.99:
raise RuntimeError(f"early decode stop decoded={frame_idx} metadata_frames={frame_count}")
min_samples = max(2, int(np.ceil(min_static_seconds / sample_seconds)))
candidates: list[dict] = []
run_start = 0
for i in range(1, len(samples) + 1):
if i == len(samples) or samples[i]["hash"] != samples[run_start]["hash"]:
chunk = samples[run_start:i]
mean_blue = float(np.mean([x["blue_ratio"] for x in chunk]))
if len(chunk) >= min_samples and mean_blue >= blue_threshold:
candidates.append({
"start_seconds": chunk[0]["time"],
"end_seconds": chunk[-1]["time"] + sample_seconds,
"sample_count": len(chunk),
"mean_blue_ratio": mean_blue,
"hash": chunk[0]["hash"],
})
run_start = i
metadata = {"fps": fps, "frame_count": frame_count, "width": width,
"height": height, "duration_seconds": frame_count / fps,
"decoded_frames": frame_idx, "coarse_samples": len(samples)}
return metadata, candidates
def refine_candidate(video: Path, metadata: dict, candidate: dict, pad_seconds: float,
min_static_seconds: float, blue_threshold: float,
size: int) -> list[dict]:
fps = metadata["fps"]
first = max(0, int(np.floor((candidate["start_seconds"] - pad_seconds) * fps)))
last = min(metadata["frame_count"] - 1,
int(np.ceil((candidate["end_seconds"] + pad_seconds) * fps)))
cap = cv2.VideoCapture(str(video))
cap.set(cv2.CAP_PROP_POS_FRAMES, first)
mask = roi_mask(metadata["height"], metadata["width"])
samples: list[dict] = []
frame_idx = first
while frame_idx <= last:
ok, frame = cap.read()
if not ok:
break
digest, ratio = frame_features(frame, mask, size)
samples.append({"frame": frame_idx, "hash": digest, "blue_ratio": ratio})
frame_idx += 1
cap.release()
min_frames = max(2, int(np.ceil(min_static_seconds * fps)))
runs: list[dict] = []
run_start = 0
for i in range(1, len(samples) + 1):
if i == len(samples) or samples[i]["hash"] != samples[run_start]["hash"]:
chunk = samples[run_start:i]
mean_blue = float(np.mean([x["blue_ratio"] for x in chunk]))
if len(chunk) >= min_frames and mean_blue >= blue_threshold:
start_frame = chunk[0]["frame"]
end_frame = chunk[-1]["frame"]
runs.append({
"start_frame": start_frame,
"end_frame": end_frame,
"start_seconds": start_frame / fps,
"end_seconds": (end_frame + 1) / fps,
"duration_seconds": len(chunk) / fps,
"start_time": hhmmss(start_frame / fps),
"end_time": hhmmss((end_frame + 1) / fps),
"frame_count": len(chunk),
"mean_blue_ratio": mean_blue,
"exact_repeated_hash": chunk[0]["hash"],
"confidence": "high",
})
run_start = i
return runs
def merge_duplicate_runs(runs: list[dict]) -> list[dict]:
by_key: dict[tuple[int, int], dict] = {}
for run in runs:
by_key[(run["start_frame"], run["end_frame"])] = run
return sorted(by_key.values(), key=lambda x: x["start_frame"])
def save_evidence(video: Path, intervals: list[dict], output_dir: Path, fps: float) -> None:
if not intervals:
return
output_dir.mkdir(parents=True, exist_ok=True)
cap = cv2.VideoCapture(str(video))
for index, interval in enumerate(intervals, 1):
points = {
"before": max(0, interval["start_frame"] - 1),
"start": interval["start_frame"],
"end": interval["end_frame"],
"after": interval["end_frame"] + 1,
}
evidence = {}
for label, frame_idx in points.items():
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
ok, frame = cap.read()
if ok:
name = f"interval_{index:03d}_{label}_f{frame_idx}.jpg"
cv2.imwrite(str(output_dir / name), frame)
evidence[label] = str((output_dir / name).name)
interval["evidence_frames"] = evidence
cap.release()
def write_aggregate(output_dir: Path, records: list[dict], started_at: str,
elapsed: float, input_dir: Path, config: dict) -> None:
intervals = []
for record in records:
for idx, interval in enumerate(record.get("intervals", []), 1):
intervals.append({"video_id": record["video_id"],
"video_path": record["video_path"],
"interval_index": idx, **interval})
fields = ["video_id", "video_path", "interval_index", "start_frame", "end_frame",
"start_seconds", "end_seconds", "duration_seconds", "start_time", "end_time",
"frame_count", "mean_blue_ratio", "confidence", "exact_repeated_hash"]
with (output_dir / "intervals.csv").open("w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=fields, extrasaction="ignore")
writer.writeheader(); writer.writerows(intervals)
with (output_dir / "videos.jsonl").open("w", encoding="utf-8") as handle:
for record in records:
handle.write(json.dumps(record, ensure_ascii=False) + "\n")
summary = {
"status": "completed" if all(r["status"] == "completed" for r in records) else "failed",
"started_at": started_at, "finished_at": utc_now(), "elapsed_seconds": elapsed,
"host": socket.gethostname(), "input_dir": str(input_dir), "config": config,
"video_count": len(records),
"completed_video_count": sum(r["status"] == "completed" for r in records),
"failed_video_count": sum(r["status"] == "failed" for r in records),
"videos_with_blue_screen": sum(bool(r.get("intervals")) for r in records),
"interval_count": len(intervals),
"total_video_seconds": sum(r.get("duration_seconds", 0) for r in records),
"total_blue_screen_seconds": sum(x["duration_seconds"] for x in intervals),
}
(output_dir / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--input-dir", type=Path, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--sample-seconds", type=float, default=1.0)
parser.add_argument("--min-static-seconds", type=float, default=6.0)
parser.add_argument("--blue-ratio", type=float, default=0.45)
parser.add_argument("--pad-seconds", type=float, default=5.0)
parser.add_argument("--coarse-size", type=int, default=96)
parser.add_argument("--fine-size", type=int, default=160)
parser.add_argument("--resume", action="store_true")
args = parser.parse_args()
videos = sorted(p for p in args.input_dir.rglob("*") if p.suffix.lower() in VIDEO_SUFFIXES)
if not videos:
raise SystemExit("no videos found")
args.output_dir.mkdir(parents=True, exist_ok=True)
per_video_dir = args.output_dir / "per_video"
evidence_root = args.output_dir / "evidence"
per_video_dir.mkdir(exist_ok=True)
started_at = utc_now(); t0 = time.perf_counter()
config = {"sample_seconds": args.sample_seconds,
"min_static_seconds": args.min_static_seconds,
"blue_ratio": args.blue_ratio, "pad_seconds": args.pad_seconds,
"coarse_size": args.coarse_size, "fine_size": args.fine_size,
"definition": "exact repeated decoded ROI frames with blue ratio above threshold"}
records = []
for number, video in enumerate(videos, 1):
video_id = video.stem.split(" ", 1)[0]
result_path = per_video_dir / f"{video_id}.json"
if args.resume and result_path.exists():
records.append(json.loads(result_path.read_text(encoding="utf-8")))
print(f"[{number}/{len(videos)}] resume {video.name}", flush=True)
continue
print(f"[{number}/{len(videos)}] start {video.name} {utc_now()}", flush=True)
item_t0 = time.perf_counter()
record = {"video_id": video_id, "video_path": str(video), "status": "failed",
"started_at": utc_now(), "intervals": []}
try:
metadata, candidates = coarse_scan(video, args.sample_seconds,
args.min_static_seconds,
args.blue_ratio, args.coarse_size)
fine_runs = []
for candidate in candidates:
fine_runs.extend(refine_candidate(video, metadata, candidate,
args.pad_seconds,
args.min_static_seconds,
args.blue_ratio, args.fine_size))
fine_runs = merge_duplicate_runs(fine_runs)
save_evidence(video, fine_runs, evidence_root / video_id, metadata["fps"])
blue_seconds = sum(x["duration_seconds"] for x in fine_runs)
record.update(metadata)
record.update({"status": "completed", "coarse_candidate_count": len(candidates),
"interval_count": len(fine_runs), "blue_screen": bool(fine_runs),
"blue_screen_seconds": blue_seconds,
"blue_screen_ratio": blue_seconds / metadata["duration_seconds"],
"intervals": fine_runs})
except Exception as exc:
record["error"] = f"{type(exc).__name__}: {exc}"
record["finished_at"] = utc_now()
record["elapsed_seconds"] = time.perf_counter() - item_t0
result_path.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding="utf-8")
records.append(record)
write_aggregate(args.output_dir, records, started_at,
time.perf_counter() - t0, args.input_dir, config)
print(f"[{number}/{len(videos)}] {record['status']} intervals={len(record['intervals'])} elapsed={record['elapsed_seconds']:.1f}s", flush=True)
write_aggregate(args.output_dir, records, started_at,
time.perf_counter() - t0, args.input_dir, config)
if any(r["status"] != "completed" for r in records):
raise SystemExit(2)
if __name__ == "__main__":
main()