Ask Your Question

Are there specific times when cv2.waitKey() is required?

asked 2014-09-18 23:58:13 -0500

roboscan gravatar image

updated 2014-10-02 00:48:03 -0500

berak gravatar image

So I've been playing around with various ideas for capturing some webcam feeds, and I am finding that I get varied results (some good some bad) by placing cv2.waitKey() functions in various places within my code.

I know that it is typically used to capture keyboard input, but I also read that cv2.waitKey() 'performs various tasks' (I'm paraphrasing as I don't remember the quote). Are there rules for when this function is required and / or when it is recommended? If so, can anyone point me to them?

(For instance) I asked in another question about why a loop of alternating frames from 2 webcams wasn't working... This evening, I got it working by adding a cv2.waitKey(1) after the .read() function and then after the .imshow() function. I tried different timings and different placements with varied (seemingly inconsistent) results.

Thank you very much! J

edit retag flag offensive close merge delete


IMHO when you want to see that image that you are displaying; or I have also met it when playing a video and you want to save the frame, or stop it, or close it, or whatever, based on the specific keys

thdrksdfthmn gravatar imagethdrksdfthmn ( 2014-09-19 02:35:58 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2014-10-01 14:28:27 -0500

ejehardenberg gravatar image

updated 2014-10-01 14:30:02 -0500

I know that it is required if you want to show changes in an image during a loop, or even the loop itself. When you call imshow it doesn't immediately draw itself (in my experience and afaik), it requires a call to waitKey before it attempts to process it's event loops. This is because waitKey is simply waiting for a delay, and during this delay Highgui runs whatever tasks need to be done drawing.

HighGui cannot process windows events like redraw, resizing, input event unless you call waitKey(delay), I found this info out from firsthand experience and from this post

As far as when it is recommended, I'd say anytime you need to update display changes to a user you should call it, or if you're waiting for a user to give you some input. Hope this helps.

The documentation here: should tell you pretty much everything you want to know about why this all is, but to qoute:

This function is the only method in HighGUI that can fetch and handle events, so it needs to be called periodically for normal event processing unless HighGUI is used within an environment that takes care of event processing.

edit flag offensive delete link more

Question Tools


Asked: 2014-09-18 23:58:13 -0500

Seen: 1,404 times

Last updated: Oct 01 '14