帮我使用python调用OpenCV库来实现颜色识别完整代码
时间: 2023-03-30 18:03:44 浏览: 134
很高兴回答你的问题。以下是使用 Python 调用 OpenCV 库实现颜色识别的完整代码:
```
import cv2
import numpy as np
# 定义颜色范围
lower_red = np.array([, 50, 50])
upper_red = np.array([10, 255, 255])
lower_blue = np.array([110, 50, 50])
upper_blue = np.array([130, 255, 255])
lower_green = np.array([50, 50, 50])
upper_green = np.array([70, 255, 255])
# 打开摄像头
cap = cv2.VideoCapture()
while True:
# 读取摄像头中的图像
ret, frame = cap.read()
# 将图像转换为 HSV 格式
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# 根据颜色范围进行颜色识别
mask_red = cv2.inRange(hsv, lower_red, upper_red)
mask_blue = cv2.inRange(hsv, lower_blue, upper_blue)
mask_green = cv2.inRange(hsv, lower_green, upper_green)
# 将识别出的颜色用矩形框出来
contours_red, _ = cv2.findContours(mask_red, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours_red:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (, , 255), 2)
contours_blue, _ = cv2.findContours(mask_blue, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours_blue:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, , ), 2)
contours_green, _ = cv2.findContours(mask_green, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours_green:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (, 255, ), 2)
# 显示识别结果
cv2.imshow('frame', frame)
# 按下 q 键退出程序
if cv2.waitKey(1) & xFF == ord('q'):
break
# 释放摄像头并关闭窗口
cap.release()
cv2.destroyAllWindows()
```
希望这个代码对你有所帮助!
阅读全文