File size: 1,442 Bytes
fce55e7
 
c3e4914
 
fce55e7
 
 
 
 
 
 
 
 
 
 
 
 
c3e4914
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import io

import cv2
import numpy as np
from PIL import Image, ImageSequence


def sample_gif_frames(data: bytes, n_frames: int = 5) -> list[Image.Image]:
    """Sample n_frames uniformly from a GIF. Returns RGB PIL images."""
    gif = Image.open(io.BytesIO(data))
    frames = list(ImageSequence.Iterator(gif))
    total = len(frames)
    if total == 0:
        raise ValueError("GIF has no frames")
    n = min(n_frames, total)
    indices = np.linspace(0, total - 1, n, dtype=int)
    return [frames[int(i)].convert("RGB") for i in indices]


def sample_frames(video_path: str, n_frames: int = 5) -> list[Image.Image]:
    """Sample n_frames uniformly across the video. Returns RGB PIL images."""
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        raise ValueError("Could not open video file")

    total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    if total <= 0:
        cap.release()
        raise ValueError("Video has no readable frames")

    n = min(n_frames, total)
    indices = np.linspace(0, total - 1, n, dtype=int)

    frames = []
    for idx in indices:
        cap.set(cv2.CAP_PROP_POS_FRAMES, int(idx))
        ok, frame = cap.read()
        if not ok:
            continue
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        frames.append(Image.fromarray(frame))

    cap.release()
    if not frames:
        raise ValueError("No frames could be decoded from video")
    return frames