[Python] Fast splitting of video into chunks of 'x' frames

Discussão em 'Python' iniciado por Stack, Outubro 25, 2024.

  1. Stack

    Stack Membro Participativo

    I am trying to split a video into chunks of 1000 frames each (it has to be done at frame level). I am currently using the opencv library, but it is very slow. It takes half an hour to split an 1-hour video into these equally-sized chunks.

    This is the function I am currently using:

    def split_video(video_path, output_dir, frames_per_chunk=1000):
    cap = cv2.VideoCapture(video_path)
    fps = cap.get(cv2.CAP_PROP_FPS)
    frame_count = 0
    chunk_count = 0
    frames = []

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

    frame_idx = 0
    while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
    break

    frames.append(frame)
    frame_count += 1
    # Save chunk after every 'frames_per_chunk' frames
    if frame_count % frames_per_chunk == 0:
    chunk_filename = f'video_chunk_{chunk_count}.mp4'
    chunk_path = os.path.join(output_dir, chunk_filename)
    save_frames_to_video(frames, chunk_path, fps)
    frames = []
    chunk_count += 1
    frame_idx +=1

    # Save any remaining frames
    if frames:
    chunk_filename = f'video_chunk_{chunk_count}.mp4'
    chunk_path = os.path.join(output_dir, chunk_filename)
    save_frames_to_video(frames, chunk_path, fps)

    print(f'video split into {chunk_count + 1} chunks')
    cap.release()
    return


    Are there any other methods or libraries in Python I can use that are more efficient at this? I have looked into the ffmpeg library, but that seems to handle well only splitting by duration instead of number frames.

    Continue reading...

Compartilhe esta Página