Search code examples
pythonautomation

Divide a video into multiple child videos using Python


I do create screen recording videos, then use a video editing software to divide the (screen-record.mp4) to three different videos.

ex: (screen-record.mp4 => blue-area1.mp4 & blue-area2.mp4 & blue-area3.mp4).

original video template

However, it does take a lot of effort & time to be done manually,

Is there a way to automate this process using python or something, i'm new to python.


Solution

  • You can crop video with cv2 lib:

    import cv2
    
    
    def crop_video(file, coordinates, output):
        """ Crop video """
        cap = cv2.VideoCapture(file)
        fps, frames = cap.get(cv2.CAP_PROP_FPS), cap.get(cv2.CAP_PROP_FRAME_COUNT)
        x, y, w, h = coordinates
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        out = cv2.VideoWriter(output, fourcc, fps, (w, h))
        while cap.isOpened():
            ret, frame = cap.read()
            if ret:
                crop_frame = frame[y:y + h, x:x + w]
                out.write(crop_frame)
            else:
                break
        cap.release()
        out.release()
        cv2.destroyAllWindows()
    
    
    if __name__ == '__main__':
        for i, coord in enumerate([(0, 0, 960, 540), (960, 0, 959, 539), (960, 540, 959, 539)]):
            crop_video('video.mp4', coord, f'output{i+1}.mp4')
    

    Input sample:

    input

    Output samples:

    output1

    output2

    output3