Skip to content Skip to sidebar Skip to footer

Return Boolean From Cv2.inrange() If Color Is Present In Mask

I am making a mask using cv2.inRange(), which accepts an image, a lower bound, and an upper bound. The mask is working, but I want to return something like True/False or print('col

Solution 1:

Since you picked the color you can count Non Zero pixels in the mask result. Or use the relative area of this pixels.

Here is a full code and example.

Source image from wikipedia. I get 500px PNG image for this example. So, OpenCV show transparency as black pixels.

RGB colors

Then the HSV full histogram:

enter image description here

And code:

import cv2
import numpy as np

fra = cv2.imread('images/rgb.png')
height, width, channels = fra.shape

hsv = cv2.cvtColor(fra, cv2.COLOR_BGR2HSV_FULL)

mask = cv2.inRange(hsv, np.array([50, 0, 0]), np.array([115, 255, 255]))

ones = cv2.countNonZero(mask)

percent_color = (ones/(height*width)) * 100print("Non Zeros Pixels:{:d} and Area Percentage:{:.2f}".format(ones,percent_color))
cv2.imshow("mask", mask)

cv2.waitKey(0)
cv2.destroyAllWindows()
# Blue Color  [130, 0, 0] - [200, 255, 255]# Non Zeros Pixels:39357 and Area Percentage:15.43# Green Color  [50, 0, 0] - [115, 255, 255]# Non Zeros Pixels:38962 and Area Percentage:15.28

Blue and Green segmented. enter image description here

Note that results show near same percentage and non zero pixels for both segmentation indicating the good approach to measure colors.

# Blue Color  [130, 0, 0] - [200, 255, 255]# Non Zeros Pixels:39357 and Area Percentage:15.43# Green Color  [50, 0, 0] - [115, 255, 255]# Non Zeros Pixels:38962 and Area Percentage:15.28

Good Luck!

Post a Comment for "Return Boolean From Cv2.inrange() If Color Is Present In Mask"