I like using a with statement for accessing files and database connections because it automatically tears down the connection for me, in the event of error or file close.
f = open('file.txt', 'r')
for i in f():
print(i)
f.close()
versus
with open('file.txt', 'r') as f:
for i in f:
print(i)
Is there an equivalent rephrasing for reading from the camera buffer in the following?:
c = cv.VideoCapture(0)
while(1):
_,f = c.read()
cv.imshow('e2',f)
if cv.waitKey(5)==27:
cv.waitKey()
break
c.release()
I've tried:
c = cv.VideoCapture(0)
while(1):
with c.read() as _,f:
cv.imshow('e2',f)
if cv.waitKey(5)==27:
cv.waitKey()
break
---with no luck. It looks like the tear-down/release is a different kind of function. Is this idiom possible here?
Another way using contextlib.contextmanager
:
from contextlib import contextmanager
@contextmanager
def VideoCapture(*args, **kwargs):
cap = cv2.VideoCapture(*args, **kwargs)
try:
yield cap
finally:
cap.release()
(note: the accepted answer has been edited to include this suggestion)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With