【发布时间】:2020-03-02 15:11:12
【问题描述】:
我是 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]
【问题讨论】:
-
我得到的错误是####### ---> 40 如果 hsv_frame[i][j][1]>= low_red 和 hsv_frame[i][j][1]
-
low_red和upper_red (high_red)是数组,您将它们与hsv_frame[i][j][1]进行比较。hsv_frame[i][j][1]的内容是什么? -
beer44 hsv_frame 正在将素材转换为 hsv。而对于 hsv_frame[i][j][1] 我实际上不知道我是新手。你能帮我修一下吗?
-
low_red是一个 numpy 数组。hsv_array[i][j][1]返回一个标量值。您不能将标量值与数组进行比较。hsv_array[i,j]应该为您提供一个 numpy 数组,如果您愿意,您可以将其与low_red进行比较。但是您不能使用<=或相关运算符,因为它们仅适用于标量。 (至少据我所知;我对 python opencv 不是很熟悉) -
如果它是实时的,你应该设置你的常量在主循环之外(low_red、high_red、low_blue、high_blue...)更关键的是,你应该' t 在循环内有嵌套的
for循环 - 在那里使用 Numpy。
标签: python python-3.x opencv machine-learning computer-vision