python – Difference in output with waitKey(0) and waitKey(1)

python – Difference in output with waitKey(0) and waitKey(1)

From the doc:

1.waitKey(0) will display the window infinitely until any keypress (it is suitable for image display).

2.waitKey(1) will display a frame for 1 ms, after which display will be automatically closed. Since the OS has a minimum time between switching threads, the function will not wait exactly 1 ms, it will wait at least 1 ms, depending on what else is running on your computer at that time.

So, if you use waitKey(0) you see a still image until you actually press something while for waitKey(1) the function will show a frame for at least 1 ms only.

waitKey(0) will pause your screen because it will wait infinitely for keyPress on your keyboard and will not refresh the frame(cap.read()) using your WebCam.
waitKey(1) will wait for keyPress for just 1 millisecond and it will continue to refresh and read frame from your webcam using cap.read().

More clearly, Use debugger in your code.When using waitKey(0) in the while loop, the debugger never crosses this statement and does not refresh the frame and hence the frame output seems stable.Does not move.
Where as with waitKey(1), the debugger will cross the code after pausing at

if cv2.waitKey(1) & 0xFF == ord(q)

for 1 milli second.

python – Difference in output with waitKey(0) and waitKey(1)

From the documentation you can see that cv2.waitKey(delay) waits for delay milliseconds if delay is positive but forever (waits for a key event infinitely) if its zero or negative. Thats why you see these differences in behavior.

In the case of cv2.waitKey(1) this is, in fact, negligible but its use provides the user the opportunity to press a key (the key might be caught in some next iteration but does not make a big difference).

Leave a Reply

Your email address will not be published.