File size: 1,403 Bytes
1812e4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import cv2
import os
import tempfile

def process_video(video_path, clip_duration=10, target_fps=25):
    """
    Processes the input video:
    - Trims the last `clip_duration` seconds
    - Samples frames at `target_fps`
    
    Returns:
        frames: List of BGR frames
        metadata: Dict with original FPS, trimmed duration, frame count
    """
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        raise IOError("Cannot open video file.")

    orig_fps = cap.get(cv2.CAP_PROP_FPS)
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    duration = total_frames / orig_fps

    # Calculate starting point for last `clip_duration` seconds
    start_time = max(0, duration - clip_duration)
    start_frame = int(start_time * orig_fps)

    # Set video to start point
    cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)

    # Read and sample frames
    frames = []
    frame_interval = int(orig_fps // target_fps) if target_fps < orig_fps else 1
    frame_idx = 0

    while True:
        ret, frame = cap.read()
        if not ret:
            break
        if frame_idx % frame_interval == 0:
            frames.append(frame)
        frame_idx += 1

    cap.release()

    metadata = {
        "original_fps": orig_fps,
        "sampled_fps": target_fps,
        "clip_duration": clip_duration,
        "sampled_frames": len(frames)
    }

    return frames, metadata