File size: 2,607 Bytes
6715b3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import cv2
import os
from typing import List

# Base directory for all frame data
BASE_FRAMES_DATA_DIR = os.path.join("data", "frames")

def segment_video(video_path: str, task_id: str, frames_per_second: int = 1) -> List[str]:
    """Extracts key frames from a video, organized by task_id and video_id, and returns a list of frame paths."""
    if not task_id:
        raise ValueError("task_id must be provided to segment_video for path organization.")
    if not os.path.exists(video_path):
        # This video_path should already be task_id specific if download_video was used correctly
        raise FileNotFoundError(f"Video file not found: {video_path}")

    video_id = os.path.splitext(os.path.basename(video_path))[0]
    # frames_output_folder: data/frames/<task_id>/<video_id>/
    task_video_frames_dir = os.path.join(BASE_FRAMES_DATA_DIR, task_id, video_id)
    os.makedirs(task_video_frames_dir, exist_ok=True)

    frame_paths = []
    try:
        cap = cv2.VideoCapture(video_path)
        if not cap.isOpened():
            raise IOError(f"Could not open video file: {video_path}")

        fps = cap.get(cv2.CAP_PROP_FPS)
        if fps == 0:
            print(f"Warning: Could not get FPS for {video_path}. Assuming 30 FPS.")
            fps = 30 # Default if FPS is not available
            
        frame_interval = int(fps / frames_per_second)
        if frame_interval == 0:
            frame_interval = 1 # Ensure at least one frame is processed if frames_per_second > fps

        frame_count = 0
        saved_frame_count = 0
        while True:
            ret, frame = cap.read()
            if not ret:
                break

            if frame_count % frame_interval == 0:
                frame_filename = os.path.join(task_video_frames_dir, f"frame_{saved_frame_count:04d}.png")
                cv2.imwrite(frame_filename, frame)
                frame_paths.append(frame_filename)
                saved_frame_count += 1
            
            frame_count += 1

    except cv2.error as e:
        print(f"OpenCV error processing video {video_path} for task {task_id}: {e}")
        raise
    except Exception as e:
        print(f"Error segmenting video {video_path} for task {task_id}: {e}")
        raise
    finally:
        if 'cap' in locals() and cap.isOpened():
            cap.release()
    
    if not frame_paths:
        print(f"Warning: No frames were extracted from {video_path} (Task ID: {task_id}).")

    print(f"Segmented video {video_path} (Task ID: {task_id}). Extracted {len(frame_paths)} frames to {task_video_frames_dir}")
    return frame_paths