Hayri Uğur Koltuk Hayri Uğur Koltuk - 1 year ago 59
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()


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

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

s, i = capture.read()
if (s == False):

How can test the condition in
, not in an
which breaks if succesful?

Answer Source

the best way to think pythonic is to forget other languages

s = True
while s:
    s, i = capture.read()
    if s: