Hayri Uğur Koltuk Hayri Uğur Koltuk - 4 days ago 6
Python Question

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?

Answer

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)
Comments