首先说一下报错的地方,是在使用VideoWriter保存视频时:
'''
opencv读取摄像头视频流,并且显示
'''
import cv2
import numpy as np
#调用摄像头
cap = cv2.VideoCapture(0)
#DIVX,X264
fourcc = cv2.VideoWriter_fourcc(*'X264')
fps = 20
#获取图像的高宽
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
writer = cv2.VideoWriter('video.mp4',fourcc,fps,(width,height))
while True:
#读取视频帧
rec, frame = cap.read()
#镜像
frame = cv2.flip(frame,1)
#灰度图片
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
#保存视频
writer.write(frame)
#显示图片
cv2.imshow('demo',frame)
#退出条件
if cv2.waitKey(10) & 0xFF == ord('q'):
break
cap.release()
writer.release()
cv2.destroyAllWindows()
出现如下错误:
OpenCV: FFMPEG: tag 0x34363258/'X264' is not supported with codec id 27 and format 'mp4 / MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x31637661/'avc1'
[ERROR:0@0.234] global cap_ffmpeg_impl.hpp:2991 open Could not find encoder for codec_id=27, error: Encoder not found
[ERROR:0@0.234] global cap_ffmpeg_impl.hpp:3066 open VIDEOIO/FFMPEG: Failed to initialize VideoWriter
经过查找网上资料,发现是cv2.VideoWriter_fourcc()参数存在问题,
解决方法:
将
fourcc = cv2.VideoWriter_fourcc(*'X264')
修改为:
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
即可完美解决问题。