What's 0Xff for in Cv2.Waitkey(1)

What's 0xFF for in cv2.waitKey(1)?

0xFF is a hexadecimal constant which is 11111111 in binary. By using bitwise AND (&) with this constant, it leaves only the last 8 bits of the original (in this case, whatever cv2.waitKey(0) is).

Usage of ord('q') and 0xFF

  • ord('q') returns the Unicode code point of q
  • cv2.waitkey(1) returns a 32-bit integer corresponding to the pressed key
  • & 0xFF is a bit mask which sets the left 24 bits to zero, because ord() returns a value betwen 0 and 255, since your keyboard only has a limited character set
  • Therefore, once the mask is applied, it is then possible to check if it is the corresponding key.

Can anyone tell me why the code below used waitKey(20) and what does this 0xFF == ord('q') mean?

The waitKey() function waits the specified amount of milliseconds and then returns the code of the key that was pressed, or -1 if no key was pressed.

To understand the expression better, let's add some parenthesis:

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

The & is a bitwise and operator which is used here for bit masking to get only the lowest eight bits (because 0xFF is equal to 1111 1111 in binary). waitKey() returns an int which usually is a 32 bit or a 64 bit integer, depending on the architecture. So any "excess" bits are "eliminated" by the bitwise and. The ord() function supposedly(!) returns the ordinal value of it's parameter, i. e. the ASCII code of 'q' in that example.

In other words: It waits for 20 milliseconds for key presses and checks whether the pressed key is Q.

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.

if cv2.waitKey(1) with 2 cases

This waits for a key to be pressed and stores it in key and you can use the key code in your conditions, if no key is pressed in 1000ms (k will be -1) it will quit.

k = cv2.waitKey(1000)
if k == -1:
cv2.destroyAllWindows()
elif k == ord('a'):
print("a key")

cv2.waitKey(0)



Related Topics



Leave a reply



Submit