Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

with() statement to read from VideoCapture in opencv?

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?

like image 317
Mittenchops Avatar asked Dec 06 '22 05:12

Mittenchops


1 Answers

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)

like image 94
Eric Avatar answered Dec 20 '22 06:12

Eric