import cv2
import os

# Directory containing the FLV files
video_dir = '/PATH/TO/CREMA-D/VideoFlash/'
output_dir = '/PATH/TO/TARGET/DIRECTORY/CREMA-D/VideoFrames/'

# Create the output directory if it doesn't exist
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# Process each video file in the directory
for video_file in os.listdir(video_dir):
    if video_file.endswith('.flv'):
        video_path = os.path.join(video_dir, video_file)
        video_name = os.path.splitext(video_file)[0]

        # print(video_path, video_name)
        # continue

        # Create a directory for frames with the video file name
        frame_output_dir = os.path.join(output_dir, video_name)
        os.makedirs(frame_output_dir, exist_ok=True)

        # Open the video file
        video_capture = cv2.VideoCapture(video_path)
        total_frames = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
        frame_indices = [int(i * total_frames / 10) for i in range(10)]  # 10 uniform frames

        frame_count = 0
        extracted_frame_count = 0

        while video_capture.isOpened():
            ret, frame = video_capture.read()
            if not ret:
                break

            # Check if the current frame is one of the selected uniform frames
            if frame_count in frame_indices:
                frame_filename = os.path.join(frame_output_dir, f'frame_{extracted_frame_count}.jpg')
                cv2.imwrite(frame_filename, frame)
                extracted_frame_count += 1
                if extracted_frame_count >= 10:  # Stop after extracting 10 frames
                    break

            frame_count += 1

        # Release the video capture object
        video_capture.release()

print("Frame extraction completed.")
