本文代码主要是在对视频处理后(例如在图片上显示检测结果、添加某些文字等),想按原尺寸、帧率保存视频;也可以对批量处理后的图片进行自定义帧率的视频保存,方便查看结果。
import cv2
# open your target video
video = cv2.VideoCapture('/home/yasin/test_video.avi')
print("Loaded video ...")
# get size and fps of video
width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = video.get(cv2.CAP_PROP_FPS)
fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', '2')
# create VideoWriter for saving
outVideo = cv2.VideoWriter('save_test_video.avi', fourcc, fps, (width, height))
cnt = 0
while (True):
ret, frame = video.read()
if not ret:
print("... end of video file reached")
break
# here is your own frame processing code, for example, put word "This is a test frame" on the erery frame
cv2.putText(frame, 'This is a test frame', (int(width / 20), int(height / 8)),cv2.FONT_HERSHEY_SIMPLEX, 6, (0, 255, 0), 20, cv2.LINE_AA)
cv2.namedWindow('frame', 0)
cv2.imshow('frame', frame)
cv2.waitKey(2)
# write the frame after processing
outVideo.write(frame)
cnt = cnt + 1