一、 使用摄像头捕获视频并显示
import cv2
cap = cv2.VideoCapture(0)
while(1):
# get a frame
ret, frame = cap.read()
# show a frame
cv2.imshow("capture", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
- opencv自带的VideoCapture()函数定义摄像头对象,其参数0表示第一个摄像头,有多个摄像头的情况下参数换1、2、3……试试
- 在while循环中,利用摄像头对象的read()函数读取视频的某帧,并显示,然后等待1个单位时间,如果期间检测到了键盘输入q,则退出,即关闭窗口。
- 调用release()释放摄像头,调用destroyAllWindows()关闭所有图像窗口。
二、视频保存
视频保存可以用cv2.VideoWriter这个函数,需要参数有视频名, 格式, 码率(fps), 帧的尺寸等参数
可以这么调用:
fourcc = cv2.VideoWriter_fourcc(*'XVID')
fps = cap.get(cv2.CAP_PROP_FPS)
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), \
int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
out = cv2.VideoWriter('camera_test.avi', fourcc, fps, size)
...
# 写入一帧
out.write(frame)
网上有人说fourcc参数填-1,我试了,发现并没有用
fps那个参数之在读取视频再保存的时候用,保存摄像头拍摄到的视频就要填要保存视频的帧数
三、完整代码
import cv2
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
# fps = cap.get(cv2.CAP_PROP_FPS)
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
out = cv2.VideoWriter('camera_test.avi', fourcc,10.0, size)
while True:
ret, frame = cap.read()
# 横向翻转
frame = cv2.flip(frame, 1)
out.write(frame)
# 在图像上显示 Press Q to save and quit
cv2.putText(frame,
"Press Q to save and quit",
(10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8,
(0, 255, 0), 2)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
参考:
https://blog.csdn.net/huanglu_thu13/article/details/52337013
https://blog.csdn.net/qq_38003892/article/details/79304139
https://blog.csdn.net/fanzy1234/article/details/78582204
网友评论