Python CV2 合并视频

380 阅读1分钟

突然收到一个需求,现有两段视频。第一段与第二段有一部分重复的视频需要进行处理。要求合并两段视频并去除重叠部分,且导出为mp4格式文件。 菜鸟python,不要喷。第一次写python

import argparse
import cv2
import numpy as np
# 提问器
parser = argparse.ArgumentParser(description='merge two videos')
parser.add_argument(
    "--files",  help='please input files name seperate with ,', default="1.264,2.264")
parser.add_argument(
    "--output", help='please output file name', default="output.mp4")
args = parser.parse_args()
# 获取按顺序排列的视频
filesName = args.files.split(",")
outputName = args.output

videoChunks = []
# 读取视频
def read_videos(filesName):
    for file in filesName:
        chunk = []
        reader = cv2.VideoCapture(file)
        while (reader.isOpened()):
            hasFrames, image = reader.read()
            if (hasFrames == False):
                break
            else:
                chunk.append(image)
        videoChunks.append(chunk)
            
read_videos(filesName)  
# 获取视频分辨率
height, width, channels = videoChunks[0][0].shape
# 循环合并
while (len(videoChunks) >= 2):
    firstChunk = videoChunks[0]
    secondChunk = videoChunks[1]
    # 找到第二段第一帧
    b = secondChunk[0]
    try:
        # 第一段倒叙查找 第二段第一帧 合并
        index = [np.array_equal(b,x) for x in firstChunk[::-1]].index(True)
        firstChunk = firstChunk[:-index] + secondChunk
    except ValueError:
        # 第一段没有第二段第一帧 合并
        firstChunk = firstChunk + secondChunk  
    videoChunks.remove(secondChunk)
# 失败的方案,全部帧合并到一起并去重
# indexs = np.unique(videofinal, axis=0,  return_index=True)[1]
# videofinal = [videofinal[index] for index in sorted(indexs)]

# 导出为MP4
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
writer = cv2.VideoWriter(outputName, fourcc, 20, (width, height))

for x in firstChunk:
    writer.write(x)
    
writer.release()