我正在尝试制作一个使用网络摄像头获取视频的应用程序。但是当我运行程序时,网络摄像头没有启动,我也没有看到 cv2 窗口打开。我什至尝试制作一个简单的网络摄像头程序,但它也不起作用:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
我收到以下错误:
[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (436) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
Traceback (most recent call last):
File "test.py", line 11, in <module>
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.3.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
我的网络摄像头在其他应用程序中工作正常。只有 cv2 有问题。我应该怎么做才能解决这个问题?
最佳答案
似乎没有框架可以转换为灰度。 试试这个怎么样。
import numpy as np
import cv2
#change to your video path
cap = cv2.VideoCapture("D:\start.mp4")
while(cap.isOpened()):
# Capture frame-by-frame
ret, frame = cap.read()
if (ret!=True):
break
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
关于python - 尝试使用 CV2 从网络摄像头捕获视频时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62785443/