OpenCV

Object Selection Based on Color Thresholding

HSV (hue, saturation, value) colorspace is a model to represent the colorspace similar to the RGB color model. Since the hue channel models the color type, it is very useful in image processing tasks that need to segment objects based on its color

In this example code below , we convert the image to HSV color space, and create a color selection using inrange thresholding. A masked image is created using a bitwise AND operation as shown below:

import cv2 as cv
import numpy as np

img = cv.imread('./images/pokemon.jpg')
cv.imshow('Original Img',img)

hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
lower_blue = np.array([50,50,50])
upper_blue = np.array([130,255,255])

mask = cv.inRange(hsv, lower_blue, upper_blue)
cv.imshow('Mask',mask)

res = cv.bitwise_and(img,img, mask= mask)
cv.imshow('Selected image',res)

cv.waitKey()

Original image before masking:

Before OpenCV masking

Mask

Output image after masking:

References:

Relevant Courses

April 14, 2021