|
| 1 | +from typing import List, Dict, Union |
| 2 | +import numpy as np |
| 3 | +import json |
| 4 | +import cv2 |
| 5 | + |
| 6 | +from ns_vfs.dataloader._base import DatasetLoader |
| 7 | + |
| 8 | +class NextQA(DatasetLoader): |
| 9 | + def _parse_timestamp(self, ts: str) -> float: |
| 10 | + """ |
| 11 | + Parse a timestamp like "HH:MM:SS.mmm" into total seconds as float. |
| 12 | + """ |
| 13 | + h, m, s = ts.split(':') |
| 14 | + return int(h) * 3600 + int(m) * 60 + float(s) |
| 15 | + |
| 16 | + def load_all(self, sample_fps: int = 2, chunk_size: int = 10) -> List[Dict[str, Union[List[np.ndarray], None]]]: |
| 17 | + """ |
| 18 | + Load a video and subtitles, sample at `sample_fps` frames/sec, group every |
| 19 | + `chunk_size` frames into one dict, and attach subtitles overlapping each chunk. |
| 20 | +
|
| 21 | + Returns: |
| 22 | + List of dicts of the form: |
| 23 | + [ |
| 24 | + {'frames': [f1, f2, ..., f10], 'subtitle': None}, |
| 25 | + {'frames': [f11, ..., f20], 'subtitle': None}, |
| 26 | + ... |
| 27 | + ] |
| 28 | + """ |
| 29 | + |
| 30 | + # --- 1) Open video and get duration --- |
| 31 | + cap = cv2.VideoCapture(self.video_path) |
| 32 | + if not cap.isOpened(): |
| 33 | + raise IOError(f"Cannot open video: {self.video_path}") |
| 34 | + total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) |
| 35 | + vid_fps = cap.get(cv2.CAP_PROP_FPS) |
| 36 | + duration_sec = total_frames / vid_fps |
| 37 | + |
| 38 | + # --- 2) Sample frames at regular intervals --- |
| 39 | + interval = 1.0 / sample_fps |
| 40 | + timestamps = np.arange(0, duration_sec, interval) |
| 41 | + |
| 42 | + sampled = [] |
| 43 | + for t in timestamps: |
| 44 | + cap.set(cv2.CAP_PROP_POS_MSEC, t * 1000) |
| 45 | + ret, frame = cap.read() |
| 46 | + if not ret: |
| 47 | + break |
| 48 | + sampled.append((t, frame.copy())) |
| 49 | + cap.release() |
| 50 | + |
| 51 | + chunks: List[Dict[str, Union[List[np.ndarray], None]]] = [] |
| 52 | + for i in range(0, len(sampled), chunk_size): |
| 53 | + chunk = sampled[i:i + chunk_size] |
| 54 | + if not chunk: |
| 55 | + continue |
| 56 | + |
| 57 | + frames = [f for (_, f) in chunk] |
| 58 | + |
| 59 | + chunks.append({ |
| 60 | + 'frames': frames, |
| 61 | + 'subtitle': None |
| 62 | + }) |
| 63 | + |
| 64 | + return chunks |
0 commit comments