我试图在带有OpenCV库的Python中使用Visual Studio(和Visual Studio Code)。
我想从OpenCV的示例中启动此代码,该示例显示来自网络摄像头的实时视频:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
但是我在cv2.imshow('frame',frame)
行中说了一个异常:cv2.error: OpenCV(3.4.3) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:356: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
我从命令提示符通过
pip install opencv-python
安装了OpenCV当我使用Visual Studio 2017或Visual Studio Code时遇到相同的错误。
我检查了我的网络摄像头的隐私,该隐私对我所有的应用程序都可见。
使用Jupyter Notebook,我可以完美地运行此代码。
您知道这一点,为什么我不能从VS访问我的网络摄像头,但是在Jupyter Notebook中我可以做到这一点而没有任何问题吗?
编辑1
当我设定
将
cap = cv2.VideoCapture(0)
索引编译为-1
代码,但是我得到黑色输出。如我之前所说,在Jupyter中,我可以使用笔记本电脑访问网络摄像头。我正在使用Windows 10编辑2
当我在
imshow()
之前添加该行时: if ret:
print("error")
continue
我总是在命令提示符下获得error
输出。即使我稍等片刻,它仍然会打印“错误”。就像我说过几次,在Jupyter Notebook中,我可以通过上面的代码启动网络摄像头
最佳答案
我相信你想取消缩进
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
现在,它嵌套在while(True)循环中,因此过早释放了捕获并导致读取错误。
记住,缩进在Python中确实很重要。
关于python - Visual Studio,OpenCV,Python-应用中无网络摄像头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52506430/