我喜欢使用 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 = 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
---没有运气。看起来拆卸/发布是一种不同的功能。这个成语在这里可能吗?
最佳答案
另一种使用 contextlib.contextmanager
的方法:
from contextlib import contextmanager
@contextmanager
def VideoCapture(*args, **kwargs):
cap = cv2.VideoCapture(*args, **kwargs)
try:
yield cap
finally:
cap.release()
(注意:接受的答案已被编辑以包含此建议)
关于python - with()语句从opencv中的VideoCapture读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19086343/