Para extrair um objeto colorido específico de uma imagem, você pode usar a função cv.inRange(). Para este exemplo, vamos extrair um objeto azul da imagem.
Definir a Faixa de Cores
Primeiro, defina os limites inferior e superior da cor azul no espaço de cores HSV:
## Blue is represented in HSV at a hue of around 240 degrees out of 360.
## The Hue range in OpenCV-HSV is 0-180, to store the value in 8 bits.
## Thus, blue is represented in OpenCV-HSV as a value of H around 240 / 2 = 120.
## To detect blue correctly, the following values could be chosen:
blue_lower = np.array([100, 150, 0], np.uint8)
blue_upper = np.array([140, 255, 255], np.uint8)
Aplicar o Limiar (Threshold) na Imagem
Aplique o limiar na imagem HSV para obter apenas as cores azuis:
## mask of blue color
blue_mask = cv.inRange(hsv_image, blue_lower, blue_upper)
Aplicar a Máscara
Aplique a máscara à imagem original para extrair o objeto azul:
## Use the mask to extract the blue object
blue_object = cv.bitwise_and(image, image, mask=blue_mask)
Exiba a imagem original e o objeto azul extraído:
## Save the image to the specified file
cv.imwrite('blue_object.jpg', blue_object)