Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
757 views
in Technique[技术] by (71.8m points)

python - 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('color present') if the color between the ranges is present. Here is some sample code:

    from cv2 import cv2
    import numpy as np
    
    img = cv2.imread('test_img.jpg', cv2.COLOR_RGB2HSV)
    
    lower_range = np.array([0, 0, 0])
    upper_range = np.array([100, 100, 100])
    
    mask = cv2.inRange(img_hsv, lower_range, upper_range)
    
   #this is where I need an IF THEN statement. IF the image contains the hsv color between the hsv color range THEN print('color present')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)) * 100

print("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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...