What Actually WaitKey is doing

I want to know that what actually cv2.waitKey() is doing … I know that it is used for waiting for a particular amount of milliseconds or for indefinite period of time (if 0 is mentioned) . But , when I ran the following python code first a grey window popped up(for ten seconds ) and then after 10s , the image came up.
import cv2
import time
image = cv2.imread("./my.jpg")
cv2.imshow(“Image” , image)
time.sleep(10)
cv2.waitKey(3000)
So, is waitKey the one who is responsible for showing the image or some other thing is going on internally ???

Hi,
What’s your problem with doc?

The problem is that right after imshow() you need to call waitKey() for at least few miliseconds. Within thoes few milieconds OpenCV allows the image to be painted by GUI. Using time.sleep() you block the thread for 10 seconds and GUI can not paint the image during that time.

This should solve your problem:

import cv2
import time
image = cv2.imread("./my.jpg")
cv2.imshow(“Image” , image)

#1 ms for painting
cv2.waitKey(1)

#Block for 10 seconds
time.sleep(10)

#Wait 3 seconds for button press
cv2.waitKey(3000)

waitKey() does the actual drawing, imshow() just copies an image pointer.

so if you sleep() 10 seconds between imshow() and waitKey(), it won’t draw anything in the meantime

1 Like

the number doesn’t matter to the “drawing”. every waitKey call “draws” everything that needs to be “drawn”.

the timeout is merely a convenience that keeps the GUI event loop running for that long (or until a key is pressed), in case you don’t need to do anything else during that time.

1 Like

@tiglon

waitKey is the function that execute the rendering in HighGUI.

It’s a well documented but no intuitive function. When you use imshow in a loop, you should call waitKeyeven if you don’t want to wait for anything.

waitKey does three things:

  • waits for a keypress
  • optionally, waits for a period of time at most, so it can be used as a convenient alternative to sleep()
  • renders windows (like pending imshow) before waiting

The waiting is doing by a gui function in GTK, QT or whatever library is used. It is expected to pause the thread with a mutex or equivalent.

1 Like

@berak @Alejandro_Silvestri thanks for clarifying !!!
But , is there any way to go into the source code of the waitKey function ???
As on my local workstation the waitKey code is present in compiled form(binary form ) (have .pyd extension ) and on the github repo of opencv , I am unable to find the code …

sure there is, it’s all on github

… just be aware, that opencv is mainly a c++ lib, don’t expect python there !

1 Like

If you have GTK, you can see the code here.

If you have QT, this is the code.

You can look for cvWaitKey in all .cpp files in this folder.

1 Like