问题描述
我正在使用openCV
进行录制,一开始录制进展顺利,但是我希望当我按下空格键时,录制的所有内容都保存在设备上(这是损坏的地方)。我收到以下错误:
OpenCV:FFMPEG:标签0x4745504d /'MPEG'不支持编解码器ID 2和格式'mp4 / MP4(MPEG-4 Part 14)' OpenCV:FFMPEG:后备使用标记0x7634706d /'mp4v'
然后窗口冻结。
这是代码:
def record_video():
capture = cv2.VideoCapture(0)
while capture.isOpened():
res,video = capture.read()
cv2.imshow("Recording Window",video)
if cv2.waitKey(1) == 27: #ESC key to stop recording
break
elif cv2.waitKey(1) == 32: #SPACE key to start recording and save it to the device
width = int(capture.get (cv2.CAP_PROP_FRAME_WIDTH))
height = int(catch.get (cv2.CAP_PROP_FRAME_HEIGHT))
code = cv2.VideoWriter_fourcc (* 'MPEG') #format
recorder = cv2.VideoWriter("video.mp4",code,20,(width,height))
while True:
result,video_record = capture.read()
recorder.write(video_record)
if cv2.waitKey(1) & 0xFF == ord("q"): #q key to stop recording
break
recorder.release()
capture.release()
cv2.destroyAllWindows()
capture.release()
cv2.destroyAllWindows()
解决方法
要创建.mp4视频,您需要将其初始化为*mp4v
code = cv2.VideoWriter_fourcc(*'mp4v') #format
但是,如果上述初始化对您不起作用,则需要使用ffmpeg
编译opencv
。
另一种选择是使用 Motion-JPEG 视频格式,与.mp4
code = cv2.VideoWriter_fourcc(*'MJPG') #format
recorder = cv2.VideoWriter("video.avi",code,20,(width,height))