Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use return value of a function as condition of while that returns tuple in python

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?

like image 512
Hayri Uğur Koltuk Avatar asked Mar 21 '13 08:03

Hayri Uğur Koltuk


People also ask

Can a function return a tuple?

Functions can return tuples as return values.

Can function return tuple in Python with example?

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 “.

How do I return two data types in Python?

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.


2 Answers

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)
like image 98
Zacrath Avatar answered Oct 04 '22 15:10

Zacrath


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)
like image 34
ornoone Avatar answered Oct 04 '22 14:10

ornoone