使用 cv2.VideoCapture 捕获图片 [英] use cv2.VideoCapture to capture a picture
问题描述
我想使用我的笔记本电脑网络摄像头使用以下代码捕捉图片:
I want to use my laptop webcam to capture a picture using the code below:
import cv2
cap = cv2.VideoCapture(1)
while(True):
ret, frame = cap.read()
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
但它抛出这个错误:
cv2.imshow('frame', frame) cv2.error: OpenCV(4.0.0)C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:350:错误: (-215:Assertion failed) size.width>0 &&尺寸.高度>0 英寸函数 'cv::imshow'
cv2.imshow('frame', frame) cv2.error: OpenCV(4.0.0) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:350: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
我该如何解决这个错误?
How can I fix this error?
推荐答案
当 OpenCV
有问题从相机或流获取帧时,它不会引发错误,但会返回 False
在 ret
(返回状态)中,所以你应该检查它.它也在 frame
和 imshow
中返回 None
有问题显示 None
- 它没有宽度和高度 - 所以size.width>0 && 出现错误size.height>0
When OpenCV
has problem to get frame from camera or stream then it doesn't raise error but it return False
in ret
(return status) so you should check it. It also return None
in frame
and imshow
has problem to display None
- it has no width and height - so you get error with size.width>0 && size.height>0
据我所知,大多数笔记本电脑网络摄像头的编号都是 0
,而不是 1
As I know mostly laptop webcame has number 0
, not 1
这适用于我的笔记本电脑网络摄像头
This works with my laptop webcam
import cv2
cap = cv2.VideoCapture(0) # zero instead of one
while True:
ret, frame = cap.read()
if not ret: # exit loop if there was problem to get frame to display
break
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
<小时>
正如 Dave W. Smith 在评论中所说:一些笔记本电脑可能需要时间来发送正确的图像然后这里版本不退出循环
as said Dave W. Smith in comment: some laptops may need time to send correct image then here version which doesn't exit loop
while True:
ret, frame = cap.read()
if ret: # display only if status (ret) is True and there is frame
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
这篇关于使用 cv2.VideoCapture 捕获图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!