I was looking for something like this but I couldn't find so here it goes.
Some background
I use opencv to retrieve frames from a video file. Usually people do it in an endless loop like:
while (True):
    s, img = cv.read()
or
for i in xrange(10000): #just a big number
    s, img = cv.read()
now i want to retrieve all frames and quit the loop when there are no more frames. However my skills in python aren't strong enough to do what I want to do.
What I want to know
read function (or method, i don't know how they are called in python) returns a tuple: first represents success of the operation, and second represents the frame returned. I want to break the while loop when first element of the tuple is false. Having a C background, I thought maybe this would work:
while ((success, img = capture.read())[0]):
    #do sth with img
i thought this will break the loop when success is false. But it did not. Then i thought maybe this will work:
while ((success, img = capture.read()).success):
    #do sth with img
it also did not work. I don't want to do something like
while(True):
    s, i = capture.read()
    if (s == False):
        break
How can test the condition in while, not in an if which breaks if succesful?
Functions can return tuples as return values.
A Python function can return any object such as a tuple. To return a tuple, first create the tuple object within the function body, assign it to a variable your_tuple , and return it to the caller of the function using the keyword operation “ return your_tuple “.
In Python, you can return multiple values by simply return them separated by commas. In Python, comma-separated values are considered tuples without parentheses, except where required by syntax.
You could write a generator function.
def readframes(cv):
    while True:
        success, frame = cv.read()
        if success:
            yield frame
        else:
            return
This way you can loop through the frames with a for loop.
for frame in readframes(cv):
    do_something_with_frame(frame)
                        the best way to think pythonic is to forget other languages
s = True
while s:
    s, i = capture.read()
    if s:
        do_some_stuff(i)
                        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