问题描述
我有一个代码可以检测绿色和蓝色两种颜色。我想检查是否检测到
绿色以打印按摩,如果检测到蓝色也打印另一条消息
I have a code to detect two colors green and blue. I want to check ifgreen color is detected to print a massage and if blue color is detected to print another message too
这是代码:
import cv2 import numpy as np cap = cv2.VideoCapture(0) while(1): # Take each frame _, frame = cap.read() # Convert BGR to HSV hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # define range of blue color in HSV lower_blue = np.array([110,50,50]) upper_blue = np.array([130,255,255]) lower_green = np.array([50, 50, 120]) upper_green = np.array([70, 255, 255]) green_mask = cv2.inRange(hsv, lower_green, upper_green) # I have the Green threshold image. # Threshold the HSV image to get only blue colors blue_mask = cv2.inRange(hsv, lower_blue, upper_blue) mask = blue_mask + green_mask ############this is the Error #################### if mask==green_mask: print "DOne" ################################################ # Bitwise-AND mask and original image res = cv2.bitwise_and(frame,frame, mask= mask) cv2.imshow('frame',frame) cv2.imshow('mask',mask) cv2.imshow('res',res) k = cv2.waitKey(5) & 0xFF if k == 27: break cv2.destroyAllWindows()
运行上面的代码会出现以下错误:
Running the above code gives me following error:
ValueError:比一个元素多
的数组的真值是不明确的。使用a.any()或a.all()
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
任何想法如何解决这个问题?
Any ideas how to fix this?
推荐答案
比较如果mask == green_mask 返回其维度的布尔值数组,该数组无法满足一个 if 条件需要一个布尔值。
On comparing if mask==green_mask returns an array of boolean value of their dimension which can not satisfy an if condition which require a single boolean.
你需要使用一个返回<$ c $的函数c> true 如果矩阵掩码和 green_mask 全部相同并返回 false 否则。如果条件,则应在此下调用该函数。
You need to use a function which will return true if matrix mask and green_mask are all same and return false otherwise. That function should be called under this if condition.
编辑:
如果np.array_equal(mask,green_mask)替换代码
Replace the code with
:
它将解决您的问题。
这篇关于检查Colors Opencv Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!