gpt4 book ai didi

python - 检查图像是否包含蓝色像素

转载 作者:太空宇宙 更新时间:2023-11-03 22:08:16 25 4
gpt4 key购买 nike

我有这张图片:

enter image description here

我正在尝试用 Python 编写一个函数,如果图像包含蓝色像素,它将返回 True,否则返回 False。该图像只是一个例子。如果蓝色可能略有不同,我会有其他人。但它们始终是黑色背景上的蓝色字母。

到目前为止我有这个:

def contains_blue(img):
# Convert the image to HSV colour space
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Define a range for blue color
hsv_l = np.array([100, 150, 0])
hsv_h = np.array([140, 255, 255])
# Find blue pixels in the image
#
# cv2.inRange will create a mask (binary array) where the 1 values
# are blue pixels and 0 values are any other colour out of the blue
# range defined by hsv_l and hsv_h
return 1 in cv2.inRange(hsv, hsv_l, hsv_h)

该函数总是返回 False,因为在 cv2.inRange 返回的数组中找不到 1 值。也许hsv_lhsv_h定义的范围不好?我是从这里拿来的:OpenCV & Python -- Can't detect blue objects

感谢任何帮助。谢谢。

最佳答案

你可以使用 np.any()反而。如果任何一个像素的值为 255,它将返回 True

所以代替

在 cv2.inRange(hsv, hsv_l, hsv_h) 中返回 1,

您可以只添加以下内容:

返回 np.any(cv2.inRange(hsv, hsv_l, hsv_h))

更新:

正如@AKX 在评论中提到的,您更愿意尝试以下方法:

返回 cv2.inRange(hsv, hsv_l, hsv_h).any()

关于python - 检查图像是否包含蓝色像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51324202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com