python - 如何知道 opencv 上是否检测到颜色

标签 python opencv colors detection

我目前正在研究一个包括颜色检测的项目。我在 python 上使用 opencv 来做到这一点,我可以检测到我想要的颜色,即蓝色,但我无法让软件知道这种颜色已被检测到。 这是我的代码。

` hsv_frame = cv2.cvtColor(帧, cv2.COLOR_BGR2HSV) 边界 = [([94, 90, 45], [145, 255, 255])]

# loop over the boundaries
for (lower, upper) in boundaries:
    # create NumPy arrays from the boundaries
    lower = np.array(lower, dtype="uint8")
    upper = np.array(upper, dtype="uint8")

    # find the colors within the specified boundaries and apply
    # the mask
    mask = cv2.inRange(hsv_frame, lower, upper)
    output = cv2.bitwise_and(frame, frame, mask=mask)
    imageOut = np.hstack([frame, output])`

它像这样正确地隔离了蓝色 output of my code.

我的问题是,从那里我不知道如何让我的软件知道蓝色已被检测到并隔离。

最佳答案

这是一个基本方法:

定义您要检测的颜色。对该颜色的图像设置阈值 - 这将产生一个 mask ,其中所需的颜色是白色,其余的颜色是黑色。对 mask 求和,如果有任何白色(意味着如果检测到任何颜色),则总和将大于 0。

我创建了一个示例,其中还显示了图像以帮助理解该过程,但这不是必需的。 我使用 HSV 色彩空间进行分色。您可以使用this script找到良好的下/上颜色范围。它还可以帮助您了解 HSV 的工作原理。

enter image description here

import cv2
import numpy as np
# load image
img = cv2.imread("img.jpg")
# Convert to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# define range wanted color in HSV
lower_val = np.array([37,42,0]) 
upper_val = np.array([84,255,255]) 

# Threshold the HSV image - any green color will show up as white
mask = cv2.inRange(hsv, lower_val, upper_val)

# if there are any white pixels on mask, sum will be > 0
hasGreen = np.sum(mask)
if hasGreen > 0:
    print('Green detected!')

# show image 
# apply mask to image
res = cv2.bitwise_and(img,img,mask=mask)
fin = np.hstack((img,res))
# display image
cv2.imshow("Res", fin)
cv2.imshow("Mask", mask)
cv2.waitKey(0)
cv2.destroyAllWindows()

关于python - 如何知道 opencv 上是否检测到颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58288014/

相关文章:

python - 相关对象上的 Django 多维查询集

python - 从备份恢复表后出现完整性错误,PostgreSQL + Django

opencv - 安装opencv AWS实例

opencv - 在 '__init__.py 中找不到引用 'ximgproc'

c++ - 如何创建特定(R,G,B)颜色的openCV图像并获取该颜色名称?

python - 如何在 Python 中找到有多少层字典

python - 类型错误 : object() takes no parameters

visual-c++ - 将 Triclops 中的图像转换为 opencv RGB 图像垫。

C++ SDL2 如何为单个图 block 着色

python - Matplotlib pandas plot_date 颜色类别