如何知道是否在opencv上检测到颜色 [英] how to know if a color is detected on opencv

查看:111
本文介绍了如何知道是否在opencv上检测到颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在从事一个包括色彩检测的项目.我在python上使用opencv这样做,我可以检测到想要的颜色,即蓝色,但是我无法设法使软件知道已检测到该颜色. 这是我的代码.

I'm currently working on a project including color detection. I'm using opencv on python to do so, I can detect the color I want, i.e. blue, but I cannot manage to make the software know that this color has been detected. Here is the code I have.

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

` hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) boundaries = [([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])`

这样可以正确隔离蓝色 我的代码输出.

It isolates the color blue properly like this output of my code.

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

My problem is that from there I don't know how I can have my software to know that the color blue has been detected and isolated.

推荐答案

这是一种基本方法:

定义要检测的颜色.将该图像的阈值设为该颜色-这将导致蒙版,其中所需的颜色为白色,而其余的颜色为黑色.求和蒙版,如果有任何白色(意味着如果检测到任何颜色),则总和将大于0.

Define the color you want to detect. Threshold the image for that color - this will result in a mask where the wanted color is white and the rest is black. Sum the mask, if there is any white (meaning if any color is detected) the sum will be larger then 0.

我创建了一个示例,其中还显示了图像以帮助理解该过程,但这不是必需的. 我使用HSV色彩空间进行颜色分离.您可以使用此脚本查找良好的较低/较高的颜色范围.它还可以帮助您了解HSV的工作原理.

I created an example, where I also show the images to help understand the process, but that is not necessary. I use the HSV colorspace to do the color separation. You can use this script to find good lower / upper color ranges. It can also help you understand how HSV works.

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

这篇关于如何知道是否在opencv上检测到颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆