orena-seg / data_preprocessing /blue_screen_detector.py
Gbone3176's picture
Add blue-screen preprocessing scripts
ce16509 verified
Raw History Blame Contribute Delete
5.48 kB
#!/usr/bin/env python3
"""Detect candidate blue-screen intervals in endoscopy videos.
The detector ignores the black border around the circular endoscopic view,
samples sparsely, and reports only candidate intervals. It never modifies the
input video.
"""
from __future__ import annotations
import argparse
import csv
import json
from pathlib import Path
import cv2
import numpy as np
def circular_roi(frame: np.ndarray, black_threshold: int = 18) -> np.ndarray:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
mask = (gray > black_threshold).astype(np.uint8) * 255
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((15, 15), np.uint8))
n, labels, stats, _ = cv2.connectedComponentsWithStats(mask)
if n > 1:
idx = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA]))
x, y, w, h, area = stats[idx]
if area > frame.shape[0] * frame.shape[1] * 0.05:
cx, cy = x + w / 2, y + h / 2
radius = 0.5 * min(w, h) * 1.02
yy, xx = np.ogrid[:frame.shape[0], :frame.shape[1]]
return ((xx - cx) ** 2 + (yy - cy) ** 2 <= radius ** 2).astype(np.uint8)
# Conservative fallback for the known 16:9 endoscopy layout.
yy, xx = np.ogrid[:frame.shape[0], :frame.shape[1]]
cx, cy = frame.shape[1] / 2, frame.shape[0] / 2
rx, ry = frame.shape[1] * 0.47, frame.shape[0] * 0.47
return (((xx - cx) / rx) ** 2 + ((yy - cy) / ry) ** 2 <= 1).astype(np.uint8)
def frame_score(frame: np.ndarray, roi: np.ndarray, size: int = 160) -> dict[str, float]:
small = cv2.resize(frame, (size, size), interpolation=cv2.INTER_AREA)
mask = cv2.resize(roi, (size, size), interpolation=cv2.INTER_NEAREST).astype(bool)
hsv = cv2.cvtColor(small, cv2.COLOR_BGR2HSV)
h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2]
valid = mask & (v > 18)
if not np.any(valid):
return {"blue_ratio": 0.0, "texture": 0.0, "mean_hue": 0.0, "valid_ratio": 0.0}
blue = valid & (h >= 88) & (h <= 140) & (s >= 55) & (v >= 35)
gray = cv2.cvtColor(small, cv2.COLOR_BGR2GRAY)
texture = float(cv2.Laplacian(gray, cv2.CV_64F).var())
return {"blue_ratio": float(blue.sum() / valid.sum()),
"texture": texture, "mean_hue": float(np.mean(h[valid])),
"valid_ratio": float(valid.sum() / mask.sum())}
def detect(args: argparse.Namespace) -> dict:
cap = cv2.VideoCapture(str(args.video))
if not cap.isOpened():
raise RuntimeError(f"cannot open video: {args.video}")
fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
width, height = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
duration = frame_count / fps if frame_count else None
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
ok, first = cap.read()
if not ok:
raise RuntimeError("cannot decode first frame")
roi = circular_roi(first)
step = max(1, int(round(args.sample_seconds * fps)))
samples = []
for frame_idx in range(0, frame_count, step):
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
ok, frame = cap.read()
if not ok:
continue
score = frame_score(frame, roi)
score.update(frame_index=frame_idx, time_seconds=frame_idx / fps)
score["blue_like"] = bool(score["blue_ratio"] >= args.blue_ratio and score["texture"] <= args.max_texture)
samples.append(score)
cap.release()
intervals = []
start = None
for item in samples + [{"blue_like": False, "time_seconds": (duration or 0.0)}]:
if item["blue_like"] and start is None:
start = item["time_seconds"]
if not item["blue_like"] and start is not None:
end = item["time_seconds"]
if end - start >= args.min_seconds:
intervals.append({"start_seconds": round(start, 3), "end_seconds": round(end, 3), "duration_seconds": round(end-start, 3)})
start = None
return {"video": str(args.video), "fps": fps, "frame_count": frame_count,
"width": width, "height": height, "duration_seconds": duration,
"sampling_seconds": args.sample_seconds, "blue_ratio_threshold": args.blue_ratio,
"max_texture": args.max_texture, "min_interval_seconds": args.min_seconds,
"intervals": intervals, "sample_count": len(samples), "samples": samples}
def main() -> None:
p = argparse.ArgumentParser()
p.add_argument("video", type=Path)
p.add_argument("--output-dir", type=Path, required=True)
p.add_argument("--sample-seconds", type=float, default=2.0)
p.add_argument("--blue-ratio", type=float, default=0.55)
p.add_argument("--max-texture", type=float, default=180.0)
p.add_argument("--min-seconds", type=float, default=6.0)
args = p.parse_args()
args.output_dir.mkdir(parents=True, exist_ok=True)
result = detect(args)
stem = args.video.stem.replace(" ", "_")
(args.output_dir / f"{stem}.json").write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
with (args.output_dir / f"{stem}_intervals.csv").open("w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=["start_seconds", "end_seconds", "duration_seconds"])
w.writeheader(); w.writerows(result["intervals"])
print(json.dumps({k: result[k] for k in ("video", "duration_seconds", "sample_count", "intervals")}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()