capture.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. """Video and window frame capture."""
  2. from __future__ import annotations
  3. from typing import Iterator, Optional, Tuple
  4. import cv2
  5. import numpy as np
  6. from tracker.window_picker import get_client_screen_rect
  7. def iter_video_frames(video_path: str) -> Iterator[Tuple[int, np.ndarray]]:
  8. cap = cv2.VideoCapture(video_path)
  9. if not cap.isOpened():
  10. raise RuntimeError(f"Cannot open video: {video_path}")
  11. idx = 0
  12. while True:
  13. ok, frame = cap.read()
  14. if not ok:
  15. break
  16. yield idx, frame
  17. idx += 1
  18. cap.release()
  19. def grab_window_bgr(hwnd: int) -> Optional[np.ndarray]:
  20. """Capture HWND client area as BGR via mss. Returns None if invalid."""
  21. import mss
  22. try:
  23. left, top, width, height = get_client_screen_rect(hwnd)
  24. except Exception:
  25. return None
  26. if width <= 0 or height <= 0:
  27. return None
  28. with mss.mss() as sct:
  29. monitor = {"left": int(left), "top": int(top), "width": int(width), "height": int(height)}
  30. shot = sct.grab(monitor)
  31. frame = np.array(shot) # BGRA
  32. return cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)