| from __future__ import annotations |
| from typing import Optional, Dict, Tuple |
| from PIL import Image |
| import numpy as np |
| import cv2 |
| import os |
|
|
| def pil_from_path(path: str) -> Optional[Image.Image]: |
| try: |
| return Image.open(path).convert("RGB") |
| except Exception: |
| return None |
|
|
| def first_frame(path: str, max_side: int = 960) -> Tuple[Optional[Image.Image], Dict[str, float]]: |
| info: Dict[str, float] = {} |
| try: |
| cap = cv2.VideoCapture(path) |
| if not cap.isOpened(): |
| return None, {"error": "Cannot open video"} |
| fps = cap.get(cv2.CAP_PROP_FPS) or 0.0 |
| w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0) |
| h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0) |
| frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0) |
| ok, frame = cap.read() |
| cap.release() |
| if not ok or frame is None: |
| return None, {"error": "Failed to read first frame"} |
| frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) |
| scale = min(1.0, max_side / max(h, w)) if max(h, w) > 0 else 1.0 |
| if scale < 1.0: |
| frame = cv2.resize(frame, (int(w*scale), int(h*scale)), interpolation=cv2.INTER_AREA) |
| dur = (frames / fps) if fps > 0 else 0.0 |
| return Image.fromarray(frame), {"width": w, "height": h, "fps": round(fps,3), "frames": frames, "duration_s": round(dur,2)} |
| except Exception as e: |
| return None, {"error": str(e)} |
|
|
| def mask_debug_on_image(img: Image.Image) -> Image.Image: |
| """Classical single-frame mask heuristic for quick sanity checks (no models).""" |
| ar = np.array(img) |
| if ar.ndim == 3 and ar.shape[2] == 3: |
| gray = cv2.cvtColor(ar, cv2.COLOR_RGB2GRAY) |
| else: |
| gray = ar if ar.ndim == 2 else cv2.cvtColor(ar, cv2.COLOR_RGBA2GRAY) |
|
|
| edges = cv2.Canny(gray, 80, 160) |
| edges = cv2.dilate(edges, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)), 1) |
|
|
| border = np.concatenate([gray[0, :], gray[-1, :], gray[:, 0], gray[:, -1]]) |
| bg_median = np.median(border) |
| diff = np.abs(gray.astype(np.float32) - bg_median) |
| thresh = (diff > 28).astype(np.uint8) * 255 |
|
|
| mask = cv2.bitwise_or(thresh, edges) |
| k7 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7)) |
| mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, k7) |
| mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, k7) |
| mask_c = cv2.cvtColor(mask, cv2.COLOR_GRAY2RGB) |
| overlay = (0.6 * ar + 0.4 * np.dstack([mask, np.zeros_like(mask), np.zeros_like(mask)])).astype(np.uint8) |
| return Image.fromarray(overlay) |
|
|