Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

opencv

I've just begun using the OpenCV library for Python and came across something I didn't understand.

cap = cv2.VideoCapture(0)  while True:       ret, frame = cap.read() #returns ret and the frame       cv2.imshow('frame',frame)        if cv2.waitKey(1) & 0xFF == ord('q'):           break 

When I use cv2.waitKey(1), I get a continuous live video feed from my laptops webcam. However when I use cv2.waitKey(0), I get still images. Every time I close the window, another one pops up with another picture taken at the time. Why does it not show as a continuous feed?

like image 572
Omar Pervez Khan Avatar asked Jul 02 '18 20:07

Omar Pervez Khan


People also ask

What happens if we pass 0 to waitKey () function for playing video?

Python OpenCV – waitKey() Function waitkey() function of Python OpenCV allows users to display a window for given milliseconds or until any key is pressed. It takes time in milliseconds as a parameter and waits for the given time to destroy the window, if 0 is passed in the argument it waits till any key is pressed.

What does waitKey return?

waitkey(1) waits for 1 ms and returns the code of the key on keyboard if it is pressed.

What is cv2 waitKey 1 & 0xFF?

In this code, if cv2.waitKey(0) & 0xFF == ord('q'): break. The waitKey(0) function returns -1 when no input is made whatsoever. As soon the event occurs i.e. a Button is pressed it returns a 32-bit integer.


2 Answers

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.

like image 96
Anatolii Avatar answered Oct 11 '22 19:10

Anatolii


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.

like image 25
Dikshit Kathuria Avatar answered Oct 11 '22 20:10

Dikshit Kathuria