简体   繁体   中英

How cv2.waitKey(1) & 0xff == ord('q') works?

How this line works?

As I know so far, the output of cv2.waitKey(number) for all every int number is -1 , and 0xff is a hexadecimal number that is equals to 255 in decimal numbers.

-1 & 0xff is equals to 255 in decimal numbers.

Also, ord('q') is equal to 113 .

But now, I don't know why 255 == 113 ?

cv2.waitKey(1) returns the character code of the currently pressed key and -1 if no key is pressed. the & 0xFF is a binary AND operation to ensure only the single byte (ASCII) representation of the key remains as for some operating systems cv2.waitKey(1) will return a code that is not a single byte. ord('q') always returns the ASCII representation of 'q' which is 113 (0x71 in hex).

therefore if the user is pressing the q key when cv2.waitKey(1) is evaluated the following will be determined:

cv2.waitKey(1) & 0xFF == cv2.ord('q')
0xXX71 & 0xFF == 0x71
0x71 == 0x71
True

I just finished some OpenCV code and cv2.waitKey(1) & 0xff == ord('q') was one of the pieces that I toyed with multiple times.

First:

cv2.waitKey([delay])

The function waitKey waits for a key event infinitely and the delay is in milliseconds. waitKey(0) means forever.

Second:

The ord() method returns an integer representing a Unicode code point for the given Unicode character. In your code you want the user to select the letter 'q' which is translated to the Unicode value of '113.'

Third:

0xFF is a hexadecimal constant which is 11111111 in binary. It is used to mask off the last 8bits of the sequence and the ord() of any keyboard character will not be greater than 255.

Here is the code that I'm using, which does not use ord() or & 0xff .

def display_facial_prediction_results(image):
  # Display image with bounding rectangles
  # and title in a window. The window
  # automatically fits to the image size.
  cv2.imshow('Facial Prediction', image)

  while (True):
    # Displays the window infinitely
    key = cv2.waitKey(0)

    # Shuts down the display window and terminates
    # the Python process when a specific key is
    # pressed on the window.
    # 27 is the esc key
    # 113 is the letter 'q'
    if key == 27 or key == 113:
        break
  cv2.destroyAllWindows()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM