使用 Python 将 2 个视频连接成 1 个视频

Fad*_*hin 1 python opencv numpy video-processing

我想编写一个程序,使用 python (cv2) 中的 openCV 来监视和跟踪 2 个不同视频中的对象。

我想将两个视频合并为 1 个视频,然后在该视频上运行一个程序来跟踪对象。

有人可以展示并解释合并它们背后的说明吗?

我这里的代码不起作用。在视频 1 的第一帧后启动视频 2

import cv2


capture = cv2.VideoCapture('p1a_tetris_1.mp4') #tell open cv to use the following video file as input


while capture.isOpened():


        ret, frame = capture.read() #capture each frame from the video . 
                                #ret is a boolean to indicate if the 

        if ret == True :    
            grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # apply gray frame to current frame


            cv2.imshow('video Part 1', grayFrame) # shows video in grascale 


        else : 
            capture = cv2.VideoCapture('p1a_tetris_2.mp4')

            while capture.isOpened():
                try:      
                    ret, frame = capture.read()
                    print(ret)

                    if ret == True :    
                        grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # apply gray frame to current frame

                        cv2.imshow('Video Part 2', grayFrame) # shows video in grascale 

                        if cv2.waitKey(1) == 27:
                            break
                    else : 

                        break
                except :
                    print("error occured")
Run Code Online (Sandbox Code Playgroud)

capture.release() cv2.destroyAllWindows()

Sal*_*ead 6

moviepy大部分为我生成了损坏的文件,所以这里有一个同样快速的方法cv2

# A list of the paths of your videos
videos = ["v1.mp4", "v2.mp4"]

# Create a new video
video = cv2.VideoWriter("new_video.mp4", cv2.VideoWriter_fourcc(*"MPEG"), fps, resolution)

# Write all the frames sequentially to the new video
for v in videos:
    curr_v = cv2.VideoCapture(v)
    while curr_v.isOpened():
        # Get return value and curr frame of curr video
        r, frame = curr_v.read()
        if not r:
            break
        # Write the frame
        video.write(frame)

# Save the video
video.release()
Run Code Online (Sandbox Code Playgroud)

方便复制粘贴的功能:

def concatenate_videos(new_video_path, *videos):
    video = cv2.VideoWriter(new_video_path, cv2.VideoWriter_fourcc(*"MPEG"), fps, resolution)

    for v in videos:
        curr_v = cv2.VideoCapture(v)
        while curr_v.isOpened():
            r, frame = curr_v.read()
            if not r:
                break
            video.write(frame)

    video.release()
Run Code Online (Sandbox Code Playgroud)


Fad*_*hin 5

FFMPEG 不是我的解决方案......

我用 moviepy 代替(顺便说一句更简单)

from moviepy.editor import VideoFileClip, concatenate_videoclips


clip_1 = VideoFileClip("p1b_tetris_1.mp4")
clip_2 = VideoFileClip("p1b_tetris_2.mp4")
final_clip = concatenate_videoclips([clip_1,clip_2])
final_clip.write_videofile("final.mp4")
Run Code Online (Sandbox Code Playgroud)