[英]How can a webcam be accessed using opencv with python?
这是我目前拥有的代码:
import cv2, time
video=cv2.VideoCapture(0)
check, frame=video.read()
print(check)
print(frame)
cv2.imshow("Capturing", frame)
cv2.waitkey(0)
video.release()
代码显示语法错误。
错误:
False
None
Traceback (most recent call last):
File "C:/Users/Stagiair/Desktop/aaa.py", line 9, in <module>
cv2.imshow("Capturing", frame)
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-95hbg2jt\opencv\modules\highgui\src\window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
import cv2
cap = cv2.VideoCapture(0)
# Check if the webcam is opened correctly
if not cap.isOpened():
raise IOError("Cannot open webcam")
while True:
ret, frame = cap.read()
frame = cv2.resize(frame, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
cv2.imshow('Input', frame)
c = cv2.waitKey(1)
if c == 27:
break
cap.release()
cv2.destroyAllWindows()
这应该有效。
如果您在安装CV2时遇到问题,可以尝试以下步骤:
python -m pip install –upgrade pip
pip install opencv-python.
如果您使用的是 Anaconda,请按照以下步骤操作。
conda update anaconda-navigator
conda update navigator-updater
conda install -c conda-forge opencv
或者
conda install -c https://conda.binstar.org/menpo opencv
您的示例显示video.read()
正在返回(False, None)
。 这告诉您读取失败。 您看到的失败是将None
传递给cv2.imshow()
的结果。
在我的一台笔记本电脑上,视频需要几次尝试才能“预热”并开始返回图像。 安排忽略一些(False, None)
返回通常就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.