python下利用OpenCV将图片插入到视频中

完成功能:将若干张图片和一个视频合成一个新的视频文件,其中片头按幻灯片形式播放这些图片,最后按照视频原来的速度播放输入的视频,并在视频中添加文字。
基于python和OpenCV的程序代码如下:

# combine *.jpg as slide and *.mp4 to video
cap = cv2.VideoCapture('E:\\Code\\openCV_Camera\data_zju\\video.mp4')#790,544,960
frames_num=cap.get(7)
width = cap.get(3)
height = cap.get(4)
size = (int(width),int(height))
fps = cap.get(5)
print(int(width),int(height),fps)
frames = frames_num + 9
print('frame number:',int(frames))

text = '2019-07-15 sym @ zju %d'
videoWriter = cv2.VideoWriter("E:\\Code\\openCV_Camera\data_zju\\combine4slide.avi",cv2.VideoWriter_fourcc('M','J','P','G'),int(fps),size)
# add *.jpgs to video
fps2 = int(fps)
for i in range(9*fps2):
    if i <9*fps2:
        name = i//fps2 + 1
        text2 = text % name
        #print('name',name)
        src = cv2.imread('E:\\Code\\openCV_Camera\data_zju\\%d.jpg' % name)
        img = cv2.resize(src, (960,544),interpolation=cv2.INTER_NEAREST)
        #add text on the figure
        cv2.putText(img, text2, (100, 500), cv2.FONT_HERSHEY_COMPLEX, 1.0, (100, 200, 200), 5)
        videoWriter.write(img)
    else:
        break
#add *.mp4 to video                
while(cap.isOpened()):
    ret,frame = cap.read()
    if ret:
        #frame = cv2.flip(frame,0)
        name = name + 1
        text3 = text % name
        
        #print(text3)
        cv2.putText(frame,text3, (100, 500), cv2.FONT_HERSHEY_COMPLEX, 1.0, (100, 200, 200), 5)
        videoWriter.write(frame)
    else:
        break        
videoWriter.release()  

python下利用OpenCV将图片插入到视频中_第1张图片

 

你可能感兴趣的:(python学)