Split a video to multiple chunks according to multiple starting and ending frame indices

6,082

According to "Creating a video with OpenCV", I use python (2.7) and OpenCV (3.0.0-beta) to split it: (Note that the audio is loss in this method)

import cv2

if __name__ == '__main__':
    vidPath = '/path/foo/video.mp4'
    shotsPath = '/path/foo/video/%d.avi' # output path (must be avi, otherwize choose other codecs)
    segRange = [(0,40),(50,100),(200,400)] # a list of starting/ending frame indices pairs

    cap = cv2.VideoCapture(vidPath)
    fps = int(cap.get(cv2.CAP_PROP_FPS))
    size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    fourcc = int(cv2.VideoWriter_fourcc('X','V','I','D')) # XVID codecs

    for idx,(begFidx,endFidx) in enumerate(segRange):
        writer = cv2.VideoWriter(shotsPath%idx,fourcc,fps,size)
        cap.set(cv2.CAP_PROP_POS_FRAMES,begFidx)
        ret = True # has frame returned
        while(cap.isOpened() and ret and writer.isOpened()):
            ret, frame = cap.read()
            frame_number = cap.get(cv2.CAP_PROP_POS_FRAMES) - 1
            if frame_number < endFidx:
                writer.write(frame)
            else:
                break
        writer.release()
Share:
6,082

Related videos on Youtube

Jon
Author by

Jon

Updated on September 18, 2022

Comments

  • Jon
    Jon almost 2 years

    Are there any tools (like FFmpeg or OpenCV) can split a video into multiple chunks according to some specific starting and ending frame indices? For example, given (0,20),(21,33),(40,60)..., each tuple means a starting and ending frame indices pair for a chunk, and the neighbor chunks might not adjoin.

    Note that, the number of chunks might be large. For example, given a 1 hour video, there might be 1500 splits.

  • Ryan Loggerythm
    Ryan Loggerythm almost 6 years
    how has this answer not gotten an upvote in all this time? great answer, @Jon
  • Keith Johnson
    Keith Johnson over 2 years
    Any way to do this without losing the audio? And on mp4s?