python - 如何在 RGB 颜色检测中使用“if 条件”?
问题描述
我是 OpenCV 和 python 的新手。我正在尝试使用相机实时检测颜色。当检测到的颜色是红色、绿色或蓝色时,我想放置一个“if 条件”。如果它检测到红色,那么它应该打印“颜色是红色”我想应用绿色和蓝色的情况也是如此。这是分别显示 RGB 颜色的代码。有没有人可以帮助我解决这个问题?提前致谢 :)
import cv2
import numpy as np
import matplotlib.pyplot as plt
cap = 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:
break
cap.release()
cv2.waitKey(1)
cv2.destroyAllWindows()
我得到的错误是
---> 40 if hsv_frame[i][j][1]>= low_red and hsv_frame[i][j][1]<=upper_red: ValueError: 具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()
解决方案
看起来您想计算图像是否为红色,red
由您的low_red
和high_red
边界定义。
你已经有了带有红色区域的面具,为什么不使用它呢?
countRed = cv2.countNonZero(red_mask)
if countRed > 0: #choose whatever condition you want
print("Red found")
推荐阅读
- java - Java 对与 HashMap
- javascript - 尝试淡入/淡出 html5 音频文件 vuejs / vanilla js
- html - 使用 CSS 和 Bootstrap 4 自定义边缘平滑的边框
- sql - 创建新列,所有内容都在另一列的第三和第四之间
- c++ - 来自 C++ 的 Angelscript 传输数组
- ruby - Ruby 地图给出了奇怪的结果
- c++ - 计算每个节点的树高,帮我解释一下这个代码解决方案
- javascript - 谷歌地图 Angular9 打开信息窗口时出错,找不到 getAnchor()
- javascript - 如何在不使用 filter() 的情况下过滤数组?
- django - 限制用户可以上传的文件数量