To extract a specific colored object from an image, you can use the cv.inRange()
function. For this example, we'll extract a blue object from the image.
Define the Color Range
First, define the lower and upper bounds of the blue color in the HSV colorspace:
## 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)
Threshold the Image
Threshold the HSV image to get only the blue colors:
## mask of blue color
blue_mask = cv.inRange(hsv_image, blue_lower, blue_upper)
Apply the Mask
Apply the mask to the original image to extract the blue object:
## Use the mask to extract the blue object
blue_object = cv.bitwise_and(image, image, mask=blue_mask)
Display the original image and the extracted blue object:
## Save the image to the specified file
cv.imwrite('blue_object.jpg', blue_object)