How to use waitKey() [closed]

asked 2017-11-05 12:17:02 -0500

ghltshubh gravatar image

I am writing a program to read images from a folder and transition between them using addWeighted() method. But I am not where to keep the waitKey() method. Should is go inside the same loop where I am transitioning between the images or should it go outside the loop. I tried the following but it does not work as required. I am actually not sure about waitKey() behavior I have seen code where it is used inside the loop and sometimes outside. What I have understood by now is that it when your frame is static it can go outside without looping but when your frame needs a refresh it needs to go inside the loop. Is my understanding correct?

Exercise: Create a slide show of images in a folder with smooth transition

import glob
images = glob.glob('*.png')
    for i in range(len(images)-1):
        current = cv2.imread(images[i])
        nxt = cv2.imread(images[i+1])
        for alpha in [x / 100.0 for x in range(101)]:
            dst = cv2.addWeighted(current, 1.0-alpha, nxt, alpha, 0)
            cv2.imshow('res', dst)
            if cv2.waitKey(0) == 27:
edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by berak
close date 2017-11-05 18:13:36.506153



waitKey() might be a misnomer. it actually holds the message loop, nessecary to render any gui things.

waitKey(0) will wait forever for a key press. did you want this ? (waitKey(10) might be the other idea.)

berak gravatar imageberak ( 2017-11-05 12:23:06 -0500 )edit

yeah waitKey(10) worked. So correct me if I am wrong, what it does is it holds the loop for that amount of time and allows the user to perform actions during that hold period of time. Thanks.

ghltshubh gravatar imageghltshubh ( 2017-11-05 13:00:39 -0500 )edit

think of it -- it's yielding 10 ms back to the os to render your image (among other tasks nessecary there)

berak gravatar imageberak ( 2017-11-05 13:04:07 -0500 )edit

so it's not mandatory. right?

ghltshubh gravatar imageghltshubh ( 2017-11-05 13:08:37 -0500 )edit

it is mandatory.

( no image ever will show up, using imshow(),, unless you have a corresponding waitKey(someMillis))

berak gravatar imageberak ( 2017-11-05 13:11:55 -0500 )edit

Oh ok. Thanks.

ghltshubh gravatar imageghltshubh ( 2017-11-05 13:14:40 -0500 )edit