Return boolean from cv2.inRange() if color is present in mask

我的未来我决定 提交于 2021-01-07 02:40:38

问题


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')

回答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.

Then the HSV full histogram:

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.

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!



来源:https://stackoverflow.com/questions/65509486/return-boolean-from-cv2-inrange-if-color-is-present-in-mask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!