如何知道打开时是否检测到颜色

2024-06-17 16:20:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在做一个项目,包括颜色检测。我使用的是python上的opencv,我可以检测到我想要的颜色,即蓝色,但是我无法让软件知道已经检测到了这种颜色。 这是我的密码。你知道吗

你知道吗` hsv\u frame=cv2.cvt颜色(frame,cv2.COLOR\u 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.

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


Tags: theoutput软件颜色npmaskarraycv2
1条回答
网友
1楼 · 发布于 2024-06-17 16:20:04

以下是一个基本方法:

定义要检测的颜色。对该颜色的图像设置阈值-这将生成一个所需颜色为白色,其余颜色为黑色的遮罩。对遮罩求和,如果有任何白色(意味着如果检测到任何颜色),求和将大于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()

相关问题 更多 >