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?
ord('q')
returns the Unicode code point of qcv2.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, becauseord()
returns a value betwen 0 and 255, since your keyboard only has a limited character setAs per the
cv2.waitkey
docs: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 usingcv2.waitKey(1) & 0xFF == ord('q')
statement. IfTrue
then it simply brakes the infinitewhile
loop. You can set it to any key of your choice.First,
cv2.waitKey(1) & 0xFF
will be executed.waitKey
returnDECIMAL VALUE
of q is 113. In Binary, It is expressed as 0b01110001.AND
operator is excuted with two inputs are 0b01110001 and 0xFF (0b11111111).0b01110001
AND
0b11111111 = 0b01110001. Exactly result isDECIMAL VALUE
of qSecond, compare value of left expression 0b01110001 with
ord('q')
. Clearly, these values is the same as another value. And final result isbreak
is invoked.