无法在OpenCV Python中第二次加载相机



我正在开发一个简单的程序,通过USB连接加载外部相机。当我第一次运行该程序时,它会加载相机并成功执行其余代码。但是,如果我停止执行并尝试重新运行程序,它不会加载相机。然而,如果我拔下USB电缆并再次插入,程序会完美运行(如果我重新运行程序,错误仍然会发生(

以下是我的实现,

import cv2 as cv
import pytesseract
import imutils
capture = cv.VideoCapture(0)
pytesseract.pytesseract.tesseract_cmd = 'C:\Program Files\Tesseract-OCR\tesseract.exe'
temperature = 0
tot = 0
for i in range(10):
_, frame = capture.read()
frame = imutils.resize(image=frame, width=500)
frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
frame_gray = frame_gray[:50, :88]
cv.imshow('frame', frame)
try:
temperature = float(pytesseract.image_to_string(frame_gray))
tot = tot + temperature
except ValueError:
print('except')
cv.imshow('Frame', frame_gray)
if cv.waitKey(20) & 0xFF == ord('q'):
break
print(tot / 10)
capture.release()
cv.destroyAllWindows()

下面是我第二次运行程序时产生的错误

[ WARN:0] global C:UsersappveyorAppDataLocalTemp1pip-req-build-5rb_9df3opencvmodulesvideoiosrccap_msmf.cpp (372) `anonymous-namespace'::SourceReaderCB::OnReadSample videoio(MSMF): OnReadSample() is called with error status: -2147023901
[ WARN:0] global C:UsersappveyorAppDataLocalTemp1pip-req-build-5rb_9df3opencvmodulesvideoiosrccap_msmf.cpp (384) `anonymous-namespace'::SourceReaderCB::OnReadSample videoio(MSMF): async ReadSample() call is failed with error status: -2147023901
[ WARN:1] global C:UsersappveyorAppDataLocalTemp1pip-req-build-5rb_9df3opencvmodulesvideoiosrccap_msmf.cpp (912) CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -2147023901
Traceback (most recent call last):
File "D:StudiesOpenCVLab07Lab.py", line 15, in <module>
frame = imutils.resize(image=frame, width=500)
File "C:Python39libsite-packagesimutilsconvenience.py", line 69, in resize
(h, w) = image.shape[:2]
AttributeError: 'NoneType' object has no attribute 'shape'
[ WARN:1] global C:UsersappveyorAppDataLocalTemp1pip-req-build-5rb_9df3opencvmodulesvideoiosrccap_msmf.cpp (434) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

所以基本上,我必须插上USB电缆才能重新运行程序。我该如何解决这个问题?提前感谢!

第一次尝试使用方法cv.VideoCapture.open并检查它是否返回True,或者在相同的原则下使用cv.VideaCapture.isOpened

在打开新设备之前,使用open((方法调用release((

capture = cv.VideoCapture()
capture.open(0)
if not capture.IsOpened() :
...
...
capture.release()

警告在退出脚本之前一定要调用release((问题也可能来自你的相机,请与另一台联系

最新更新