OpenCV将4个视频文件并列合成为1个,在窗口的4个区域播放

《OpenCV系列教程》
项目位置:OpenCV-Sample
代码位置:103-4VidoesArePlayedSideBySideAsOneVideo.py

代码功能是将4个独立的视频文件并列合并成了一个视频文件,并在屏幕的4个区域进行播放。同理可以将更多文件合并成为一个文件。

和成效果如下:
OpenCV将4个视频文件并列合成为1个,在窗口的4个区域播放_第1张图片
代码如下:

import cv2
import numpy as np

videoLeftUp = cv2.VideoCapture('./res/2_003_013.mp4')
videoLeftDown = cv2.VideoCapture('./res/2_003_014.mp4')
videoRightUp = cv2.VideoCapture('./res/2_003_015.mp4')
videoRightDown = cv2.VideoCapture('./res/2_003_016.mp4')

fps = videoLeftUp.get(cv2.CAP_PROP_FPS)

width = (int(videoLeftUp.get(cv2.CAP_PROP_FRAME_WIDTH)))
height = (int(videoLeftUp.get(cv2.CAP_PROP_FRAME_HEIGHT)))

videoWriter = cv2.VideoWriter('./out/4in1.mp4', cv2.VideoWriter_fourcc('m', 'p', '4', 'v'), fps, (width, height))

successLeftUp, frameLeftUp = videoLeftUp.read()
successLeftDown , frameLeftDown = videoLeftDown.read()
successRightUp, frameRightUp = videoRightUp.read()
successRightDown, frameRightDown = videoRightDown.read()

while successLeftUp and successLeftDown and successRightUp and successRightDown:
    frameLeftUp = cv2.resize(frameLeftUp, (int(width / 2), int(height / 2)), interpolation=cv2.INTER_CUBIC)
    frameLeftDown = cv2.resize(frameLeftDown, (int(width / 2), int(height / 2)), interpolation=cv2.INTER_CUBIC)
    frameRightUp = cv2.resize(frameRightUp, (int(width / 2), int(height / 2)), interpolation=cv2.INTER_CUBIC)
    frameRightDown = cv2.resize(frameRightDown, (int(width / 2), int(height / 2)), interpolation=cv2.INTER_CUBIC)

    frameUp = np.hstack((frameLeftUp, frameRightUp))
    frameDown = np.hstack((frameLeftDown, frameRightDown))
    frame = np.vstack((frameUp, frameDown))

    videoWriter.write(frame)
    successLeftUp, frameLeftUp = videoLeftUp.read()
    successLeftDown, frameLeftDown = videoLeftDown.read()
    successRightUp, frameRightUp = videoRightUp.read()
    successRightDown, frameRightDown = videoRightDown.read()

videoWriter.release()
videoLeftUp.release()
videoLeftDown.release()
videoRightUp.release()
videoRightDown.release()

最后合成的文件是无声的,那就给他配个声音吧。从刚才的那4个视频中随意选一个提取音频:

$ ffmpeg -i 2_003_014.mp4 -vn -y -acodec copy 3.aac

视频、音频合二为一:

 ffmpeg -i ../out/4in1.mp4  -i ./3.aac  -vcodec copy -acodec copy output.mp4

这样新生成的视频就有声音了。

你可能感兴趣的:(OpenCV)