[英]Concatenate 2 videos into 1 using Python
我想編寫一個程序,使用 python (cv2) 中的 openCV 監視和跟蹤 2 個不同視頻中的對象。
我想將兩個視頻合並為一個視頻,然后在該視頻上運行一個程序來跟蹤對象。
有人可以展示並解釋合並它們的說明嗎?
我的代碼在這里不起作用。 它在視頻 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")
capture.release() cv2.destroyAllWindows()
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")
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():
r, frame = curr_v.read() # Get return value and curr frame of curr video
if not r:
break
video.write(frame) # Write the frame
video.release() # Save the video
def merge_video(video1, video2):
camera = cv2.VideoCapture(video1)
cv2.namedWindow("detection", cv2.WINDOW_AUTOSIZE)
sz = (int(camera.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fourcc = cv2.VideoWriter_fourcc(*'mpeg')
vout = cv2.VideoWriter()
vout.open(os.path.join("output.mp4"), fourcc, 20, sz, True)
while True:
res, frame = camera.read()
if not res:
break
cv2.imshow("detection", frame)
# Save the video frame by frame
vout.write(frame)
if cv2.waitKey(110) & 0xff == 27:
break
camera = cv2.VideoCapture(video2)
cv2.namedWindow("detection", cv2.WINDOW_AUTOSIZE)
while True:
res, frame = camera.read()
if not res:
break
cv2.imshow("detection", frame)
# Save the video frame by frame
vout.write(frame)
if cv2.waitKey(110) & 0xff == 27:
break
vout.release()
camera.release()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.