Python with()语句从opencv中的VideoCapture读取?
我喜欢使用with语句访问文件和数据库连接,因为在出现错误或文件关闭时,with语句会自动断开连接Python with()语句从opencv中的VideoCapture读取?,python,opencv,with-statement,Python,Opencv,With Statement,我喜欢使用with语句访问文件和数据库连接,因为在出现错误或文件关闭时,with语句会自动断开连接 f = open('file.txt', 'r') for i in f(): print(i) f.close() 对 with open('file.txt', 'r') as f: for i in f: print(i) 在以下内容中,是否有从相机缓冲区读取的等效重新措辞 c = cv.VideoCapture(0) while(1): _,f
f = open('file.txt', 'r')
for i in f():
print(i)
f.close()
对
with open('file.txt', 'r') as f:
for i in f:
print(i)
在以下内容中,是否有从相机缓冲区读取的等效重新措辞
c = cv.VideoCapture(0)
while(1):
_,f = c.read()
cv.imshow('e2',f)
if cv.waitKey(5)==27:
cv.waitKey()
break
c.release()
我试过:
c = cv.VideoCapture(0)
while(1):
with c.read() as _,f:
cv.imshow('e2',f)
if cv.waitKey(5)==27:
cv.waitKey()
break
---没有运气。看起来拆卸/释放是另一种功能。这个习惯用法在这里可能吗?我不知道opencv,所以可能有更好的答案——但是您可以通过定义
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
class MyVideoCapture(cv.VideoCapture):
def __enter__(self):
return self
def __exit__(self, *args):
self.release()
使用情况如下所示:
with MyVideoCapture(0) as c:
while(1):
_,f = c.read()
cv.imshow('e2',f)
if cv.waitKey(5)==27:
cv.waitKey()
break
点击break
语句后,资源将被释放
根据您的评论,opencv在这里似乎做了一些古怪的事情。您还可以创建自定义类来包装VideoCapture实例:
class VideoCaptureWrapper(object):
def __init__(self, *args, **kwargs):
self.vid_steam = VideoCapture(*args, **kwargs):
def __enter__(self):
return self
def __exit__(self, *args):
self.vid_stream.release()
这里的用法是:
with VideoCaptureWrapper(0) as c:
while(1):
_,f = c.vid_stream.read()
cv.imshow('e2',f)
if cv.waitKey(5)==27:
cv.waitKey()
break
另一种方式:
from contextlib import contextmanager
@contextmanager
def VideoCapture(*args, **kwargs):
cap = cv2.VideoCapture(*args, **kwargs)
try:
yield cap
finally:
cap.release()
这看起来很像我要找的。抱歉,我以前没有使用过上下文管理器——在我上面提到的上下文中,我该如何称呼它?@Mittenchops——添加了一些示例用法。在这种情况下,在读取数据时覆盖\uuuu iter\uuuu
以产生数据(f
)也可能是很好的方法。。。但我想这取决于你的实际用例。这看起来确实像我所想的。但是我在类定义中遇到了这个错误:`File./main.py',第7行,在类MyVideoCapture(cv.VideoCapture):TypeError:error调用元类基时无法创建'builtin_function_或_method'实例',但我怀疑这足以让我开始并告诉我可能发生什么。嗯,玩了一些,看起来它可能有更深层次的问题。@Mittenchops--糟糕透了。无论如何,我已经更新了一个解决方案,我们使用组合而不是继承。我看不出有什么办法会失败;-)