如何在RGB颜色检测中使用“如果条件”?

我是OpenCV和Python的新手。我正在尝试使用摄像头实时检测颜色。我想在检测到红色、绿色或蓝色时设置一个“如果条件”。如果检测到红色,它应该打印“颜色是红色”。同样,我希望对绿色和蓝色也应用这种情况。这里有代码展示了单独的RGB颜色。是否有人可以帮我解决这个问题?提前感谢 🙂

import cv2import numpy as npimport matplotlib.pyplot as pltcap = cv2.VideoCapture(0)while True:    _, frame = cap.read()    hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)    # Red color    low_red = np.array([161, 155, 84])    high_red = np.array([179, 255, 255])    red_mask = cv2.inRange(hsv_frame, low_red, high_red)    red = cv2.bitwise_and(frame, frame, mask=red_mask)    # Blue color    low_blue = np.array([94, 80, 2])    high_blue = np.array([126, 255, 255])    blue_mask = cv2.inRange(hsv_frame, low_blue, high_blue)    blue = cv2.bitwise_and(frame, frame, mask=blue_mask)    # Green color    low_green = np.array([25, 52, 72])    high_green = np.array([102, 255, 255])    green_mask = cv2.inRange(hsv_frame, low_green, high_green)    green = cv2.bitwise_and(frame, frame, mask=green_mask)    # Every color except white    low = np.array([0, 42, 0])    high = np.array([179, 255, 255])    mask = cv2.inRange(hsv_frame, low, high)    result = cv2.bitwise_and(frame, frame, mask=mask)#   plt.imshow(mask,cmap='gray')######## Chech if the shown object has red color or not ##########    img_height, img_width, _=hsv_frame.shape    for i in range(img_height):        for j in range(img_width):            if hsv_frame[i][j][1]>= low_red and hsv_frame[i][j][1]<=upper_red:                print("Red found")#     cv2.imshow("Red", red)#     cv2.imshow("Blue", blue)#     cv2.imshow("Green", green)    if cv2.waitKey(1)==13:        breakcap.release()cv2.waitKey(1)cv2.destroyAllWindows()

我遇到的错误是

—> 40 if hsv_frame[i][j][1]>= low_red and hsv_frame[i][j][1]<=upper_red: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


回答:

这一行

if hsv_frame[i][j][1]>= low_red and hsv_frame[i][j][1]<=upper_red:

比较了两个数组,即像素 (r,g,b) <= (r,g,b),这将返回3个值,即 (True/False, True/False, True/False)。

因此,您需要使用以下之一:

any()(至少一个为真)

或者

all()(全部为真)

考虑到这是像素比较,我建议您使用all,

将其替换为下面的代码。

if (hsv_frame[i][j][1]>= low_red).all() and (hsv_frame[i][j][1]<=upper_red).all():

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注