CV: How to extracts the part of the picture with the specified color

CV extracts the part of the picture with the specified color

How to extract the red, blue and green colors of the image below?

1. Import the library first

import cv2
import numpy as np

2. Read picture

The conversion between BGR and HSV uses CV2. Color_ BGR2HSV

img = cv2.imread("3.png")
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)#HSV空间

(in HSV space, h is color/chroma, value range [0179], s is saturation, value range [0255], V is brightness, value range [0255].)

3. The threshold values of three colors are set and extracted

cv2.inRange(src, lowerb, upperb[, dst]) → dst

SRC – first input array. Input matrix (image)
lowerb – inclusive lower boundary array or a scalar. Lower threshold
upperrb – inclusive upper boundary array or a scalar. Upper threshold
DST – output array of the same size as SRC and CV_ 8U type. Output the same matrix as Src

lower_blue=np.array([110,100,100])#blue
upper_blue=np.array([130,255,255])

lower_green=np.array([60,100,100])#green
upper_green=np.array([70,255,255])

lower_red=np.array([0,100,100])#red
upper_red=np.array([10,255,255])

red_mask=cv2.inRange(hsv,lower_red,upper_red)
blue_mask=cv2.inRange(hsv,lower_blue,upper_blue)
green_mask=cv2.inRange(hsv,lower_green,upper_green)

4. Process the original image

red=cv2.bitwise_and(img,img,mask=red_mask)
green=cv2.bitwise_and(img,img,mask=green_mask)
blue=cv2.bitwise_and(img,img,mask=blue_mask)

res=green+red+blue

cv2.bitwise_ And() function is used to “and” binary data, that is, to binary “and” each pixel value of image (gray image or color image), 1 & amp; 1 = 1, 1 & amp; 0 = 0, 0 & amp; 1 = 0, 0 & amp; 0 = 0.

5. Output display

cv2.imshow('img',res)
cv2.waitKey(0)
cv2.destroyAllWindows()

6. Results display

All code packed

import cv2
import numpy as np


img = cv2.imread("3.png")
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

lower_blue=np.array([110,100,100])#blue
upper_blue=np.array([130,255,255])

lower_green=np.array([60,100,100])#green
upper_green=np.array([70,255,255])

lower_red=np.array([0,100,100])#red
upper_red=np.array([10,255,255])

red_mask=cv2.inRange(hsv,lower_red,upper_red)
blue_mask=cv2.inRange(hsv,lower_blue,upper_blue)
green_mask=cv2.inRange(hsv,lower_green,upper_green)

red=cv2.bitwise_and(img,img,mask=red_mask)
green=cv2.bitwise_and(img,img,mask=green_mask)
blue=cv2.bitwise_and(img,img,mask=blue_mask)

res=green+red+blue

cv2.imshow('img',res)
cv2.waitKey(0)

cv2.destroyAllWindows()

Read More: