File size: 2,164 Bytes
6461f0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""Uniform frame sampling from a video into base64-encoded JPEG strings."""
from __future__ import annotations

import base64
import io
import os

import cv2
from PIL import Image

DEFAULT_NUM_SAMPLE_FRAMES: int = 8


def extract_frames_from_video(
    video_path: str,
    num_frames: int = DEFAULT_NUM_SAMPLE_FRAMES,
    jpeg_quality: int = 90,
    verbose: bool = True,
) -> list[str]:
    """Uniformly sample frames from a video and return them as base64 JPEGs.

    Returns
    -------
    list[str]
        Base64-encoded JPEG strings, in temporal order
        (frame 1 = earliest, frame N = latest).
    """
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        raise RuntimeError(f"Cannot open video: {video_path}")

    fps = cap.get(cv2.CAP_PROP_FPS)
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    if fps <= 0 or total_frames <= 0:
        cap.release()
        raise RuntimeError(
            f"Invalid video metadata: fps={fps}, total_frames={total_frames}"
        )

    duration = total_frames / fps
    num_to_sample = max(1, min(int(num_frames), total_frames))
    if num_to_sample == 1:
        sample_indices = [0]
    else:
        sample_indices = [
            int(round(i * (total_frames - 1) / (num_to_sample - 1)))
            for i in range(num_to_sample)
        ]

    frame_b64_list: list[str] = []
    for frame_idx in sample_indices:
        cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx)
        ret, frame = cap.read()
        if not ret:
            continue
        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        img = Image.fromarray(frame_rgb)
        buf = io.BytesIO()
        img.save(buf, format="JPEG", quality=int(jpeg_quality))
        frame_b64_list.append(base64.b64encode(buf.getvalue()).decode("utf-8"))

    cap.release()
    if not frame_b64_list:
        raise RuntimeError(f"Failed to extract any frames from {video_path}")

    if verbose:
        print(
            f"  [frames] Extracted {len(frame_b64_list)} frames from "
            f"{os.path.basename(video_path)} "
            f"(duration={duration:.1f}s, fps={fps:.1f})"
        )
    return frame_b64_list