- Color space conversion
Common conversion method: the BGR <-> the RGB , the BGR <-> Gray and the BGR <-> the HSV
Function: cv2.cvtColor (input_image , flag) , wherein the flag is a conversion type.
Code:

. 1 Import CV2 2 Import numpy AS NP . 3 . 4 IMG = cv2.imread ( ' ../image/min.jpg ' ) . 5 . 6 # the BGR converted to RGB matrix . 7 IMG = cv2.cvtColor (IMG, cv2.COLOR_BGR2RGB) . 8 . 9 # the BGR GRAY converted into matrix 10 IMG = cv2.cvtColor (IMG, cv2.COLOR_BGR2GRAY) . 11 12 is # the BGR converted into HSV matrix 13 is IMG = cv2.cvtColor (IMG, cv2.COLOR_BGR2HSV)
Note: In OpenCV the HSV format, H (color / chromaticity) is in the range [0 , 179] , S range (saturation) of [0 , 255] , V (brightness) ranges [0 , 255] . But the software uses different values may be different. The general ranges: H 0 to 360 °, S 0 to 100%, V is 0 to 255.
- Simple object tracking
Using the image in the HSV mode, the extraction of a particular color object (HSV color space represents a particular color more easily than the BGR color space)
. 1 Import numpy AS NP
2 Import CV2
. 3
. 4 # capture camera
. 5 CAP = cv2.VideoCapture (0)
. 6
. 7 the while (. 1 ):
. 8
. 9 # acquires each frame
10 RET, Frame = cap.read ()
. 11
12 is # conversion to HSV space
13 is HSV = cv2.cvtColor (Frame, cv2.COLOR_BGR2HSV)
14
15 # set threshold blue
16 lower_blue np.array = ([110, 50, 50 ])
. 17 upper_blue np.array = ([130., 255, 255 ])
18
19 # Construction mask according to the threshold value (within the threshold value is set to 255 pixels, otherwise 0)
20 is mask = cv2.inRange (HSV, lower_blue, upper_blue)
21 is
22 is RES = cv2.bitwise_and (Frame, Frame, mask = mask)
23 is
24 cv2.imshow ( ' Frame ' , Frame)
25 cv2.imshow ( ' mask ' , mask)
26 is cv2.imshow ( ' RES ' , RES)
27 K = cv2.waitKey (. 5) & 0xFF
28 IF K == 27 :
29 BREAK
30
31 cv2.destroyAllWindows ()