Usage of ord('q') and 0xFF

2020-07-24 05:10发布

I am not able to understand the following code snippet-

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

in this code-

    1 import numpy as np
    2 import cv2
    3 
    4 cap = cv2.VideoCapture(0)
    5 
    6 while(True):
    7     # Capture frame-by-frame
    8     ret, frame = cap.read()
    9 
   10     # Our operations on the frame come here
   11     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
   12 
   13     # Display the resulting frame
   14     cv2.imshow('frame',gray)
   15     if cv2.waitKey(1) & 0xFF == ord('q'):
   16         break
   17 
   18 # When everything done, release the capture
   19 cap.release()
   20 cv2.destroyAllWindows()

What does ord('q') and 0xFF mean? How is it being used here?

标签: python opencv
3条回答
三岁会撩人
2楼-- · 2020-07-24 05:26
  • 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.
查看更多
▲ chillily
3楼-- · 2020-07-24 05:43

As per the cv2.waitkey docs:

It returns the code of the pressed key or -1 if no key was pressed before the specified time had elapsed.

Generally in the OpenCV tutorials and blogs, it is a general convention to use "q" key for halting any indefinite operation such as capturing frames from camera in your case. In your case, the program indefinitely checks at each iteration if "q" key is being pressed using cv2.waitKey(1) & 0xFF == ord('q') statement. If True then it simply brakes the infinite while loop. You can set it to any key of your choice.

查看更多
贼婆χ
4楼-- · 2020-07-24 05:50

First, cv2.waitKey(1) & 0xFF will be executed.

  • Doing wait 1 ms for user press.
  • If user press, for example, q then waitKey return DECIMAL VALUE of q is 113. In Binary, It is expressed as 0b01110001.
  • Next, AND operator is excuted with two inputs are 0b01110001 and 0xFF (0b11111111).

0b01110001 AND 0b11111111 = 0b01110001. Exactly result is DECIMAL VALUE of q

Second, compare value of left expression 0b01110001 with ord('q'). Clearly, these values is the same as another value. And final result is break is invoked.

查看更多
登录 后发表回答