When I first used OpencV to process images, I probably looked up the cv2.waitKey function. At that time, I was in a bit of a coma. I only knew that cv2.imshow would display images by adding cv2.waitKey. I came across it again today when I was making frame-by-frame video clips. I stared at it and wondered what it was for, so I opened my browser and spent most of the day browsing. Now sum up my harvest and ideas.
Why is cv2.imshow followed by cv2.waitkey
Let’s start with its sibling, Cv2.imshow. We all know that imShow is used to display an image in the GUI, but one feature we don’t pay much attention to is its duration. Check out the quiz below to find out.
In fact, waitKey controls the duration of the imshow, and when the imShow is not followed by WaitKey, there is no time for the imShow to display the image, so only an empty window flashes by. By adding waitKey, even just cv2. Waitkey (1), we can capture a frame of image. So cv2.imshow must be followed by cv2.waitkey.
Imshow source code for a comment to confirm: This function should be followed by cv::waitKey function which displays the image for specified . milliseconds. Otherwise, it won’t display the image.
This function should be followed by the cv2.waitkey function to display the specified image. Otherwise, it will not display the image.
Why bother with the design
This function is the only method in HighGUI that can fetch and handle events, so it needs to be.
This function is the only method to get and handle events in the HighGUI window, so it must exist.
Cv2.waitkey (1000) &0xff == ord(‘q’
To explain the literal meaning:
cv2.waitKey(1000)
: Returns a value based on keyboard input within 1000ms0xFF
: a hexadecimal numberord('q')
: Returns the ASCII code of q
0xFF is a hexadecimal number, converted to binary is 11111111. The value returned by waitKey ranges from 0 to 255, which also happens to be 8 bits. Cv2.waitkey (1) &0xff = cv2.waitKey(1) WaitKey (1) == ord(‘q’)
In fact, using waitKey on Linux sometimes results in the waitKey return value exceeding the range (0-255). Cv2.waitkey (1) = cv2.waitKey(1000) = cv2.waitKey(0xFF); Cv2.waitkey (1000) & 0xFF is still in the range (0-255), which avoids some weird bugs.
Cv2. Waitkey and time.sleep
Someone must have written waitKey as sleep in their code, and you’ll find that sometimes waitkey doesn’t work.
The function only works if there is at least one HighGUI window created and The window is active
This function only works if at least one HighGUI window exists.
That is, waitKey’s delay mechanism is conditional on creating a HighGUI window before it works. And time.sleep is an unconditional delay mechanism.
Can cv2.waitKey replace time.sleep in cv2.imshow?
The answer is clear: no.
To be solved.
Personal blog: LeeeSe