录制视频
使用自带摄像头录制一段5s的短视频
error & solution
fourcc1 = cv2.CV_FOURCC('m', 'p', '4', 'v')
在实践过程中,运行这一行时报错:
原因分析
在opencv3中,已将部分函数名进行了修改,因此通常情况下不能直接使用旧版opencv的函数接口。所以,这里使用cv2.cv.CV_FOURCC()
或cv2.CV_FOURCC()
会报错。
`
解决办法
将cv2.CV_FOURCC替换为cv2.VideoWriter_fourcc,以下两种方式均可以:
fourcc = cv2.VideoWriter_fourcc('X','V','I','D')
fourcc = cv2.VideoWriter_fourcc(*'XVID')
python版关键代码
1 def write_video(): 2 cap = cv2.VideoCapture(0) 3 # get first frame from camera to know frame size and type 4 ret, frame = cap.read() 5 rows, cols, channels = frame.shape 6 7 # fourcc = cv2.CV_FOURCC('m', 'p', '4', 'v') # error! 8 # fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') # ok! 9 fourcc = cv2.VideoWriter_fourcc(*'XVID') # another feasible way! 10 11 my_writer = cv2.VideoWriter('MyOutput30.avi', fourcc, 10, (cols, rows)) 12 13 fps = 30 14 seconds = 5 # 设置录制时间(秒) 15 frames_remaining = seconds * fps 16 17 while ret and frames_remaining > 0: 18 ret, frame = cap.read() 19 my_writer.write(frame) 20 frames_remaining -= 1
Reference
- https://stackoverflow.com/questions/15584608/python-opencv2-cv2-cv-fourcc-not-working-with-videowriter
- http://blog.csdn.net/superdont/article/details/26259727