import cv2
import numpy as np
import matplotlib.pyplot as plt
def concatenate_video(input_video1, input_video2, output_video):
video_caputre1 = cv2.VideoCapture(input_video1)
video_caputre2 = cv2.VideoCapture(input_video2)
# get video parameters
fps = video_caputre1.get(cv2.CAP_PROP_FPS)
width = video_caputre1.get(cv2.CAP_PROP_FRAME_WIDTH)
height = video_caputre1.get(cv2.CAP_PROP_FRAME_HEIGHT)
num1 = video_caputre1.get(cv2.CAP_PROP_FRAME_COUNT)
print("1_fps:", fps)
print("1_width:", width)
print("1_height:", height)
print('1_num_frame:', num1)
fps = video_caputre2.get(cv2.CAP_PROP_FPS)
width = video_caputre2.get(cv2.CAP_PROP_FRAME_WIDTH)
height = video_caputre2.get(cv2.CAP_PROP_FRAME_HEIGHT)
num2 = video_caputre2.get(cv2.CAP_PROP_FRAME_COUNT)
print("2_fps:", fps)
print("2_width:", width)
print("2_height:", height)
print('2_num_frame:', num2)
if num1 != num2:
print('Frame1 != Frame2!!!')
return
# 定义截取尺寸,后面定义的每帧的h和w要于此一致,否则视频无法播放
concate_width = int(width * 2)
concate_height = int(height)
size = (concate_width, concate_height)
fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
# 创建视频写入对象
videp_write = cv2.VideoWriter(output_video, fourcc, fps, size)
print('Start!!!')
# 读取视频帧
success1, frame_src1 = video_caputre1.read() # (960, 2560, 3) # (height, width, channel)
success2, frame_src2 = video_caputre2.read()
while success1 and not cv2.waitKey(1) == 27: # 读完退出或者按下 esc 退出
frame_target = np.concatenate((frame_src1, frame_src2), axis=1) # axis改变拼接方式,0为竖向拼接,1为横向拼接
# [width, height] 要与上面定义的size参数一致,注意参数的位置
# 写入视频文件
videp_write.write(frame_target)
# 不断读取
success1, frame_src1 = video_caputre1.read()
success2, frame_src2 = video_caputre2.read()
print("Finished!!!")
video_caputre1.release()
video_caputre2.release()
if __name__ == '__main__':
left_file = '/root/Source/SL_projects/left_frank/left.mp4'
right_file = '/root/Source/SL_projects/right_frank/right.mp4'
output_file = '/root/Source/SL_projects/frank_concate.avi'
concatenate_video(input_video1=left_file, input_video2=right_file, output_video=output_file)
Python拼接视频
最新推荐文章于 2024-06-13 19:03:00 发布