opencv同时检测三种颜色并输出
时间: 2023-08-01 08:11:36 浏览: 71
可以使用HSV色彩空间来实现对多种颜色的检测。以下是一个示例代码,可以同时检测红、绿和蓝三种颜色并输出检测到的位置:
```python
import cv2
import numpy as np
# 设置三种颜色的HSV范围
lower_red = np.array([0, 100, 100])
upper_red = np.array([10, 255, 255])
lower_green = np.array([50, 100, 100])
upper_green = np.array([70, 255, 255])
lower_blue = np.array([110, 100, 100])
upper_blue = np.array([130, 255, 255])
# 读入图像并转换为HSV色彩空间
img = cv2.imread('image.jpg')
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# 对三种颜色分别进行掩码处理
mask_red = cv2.inRange(hsv, lower_red, upper_red)
mask_green = cv2.inRange(hsv, lower_green, upper_green)
mask_blue = cv2.inRange(hsv, lower_blue, upper_blue)
# 腐蚀和膨胀操作,用于去除噪声和连接分散的部分
kernel = np.ones((5,5), np.uint8)
mask_red = cv2.erode(mask_red, kernel)
mask_red = cv2.dilate(mask_red, kernel)
mask_green = cv2.erode(mask_green, kernel)
mask_green = cv2.dilate(mask_green, kernel)
mask_blue = cv2.erode(mask_blue, kernel)
mask_blue = cv2.dilate(mask_blue, kernel)
# 在原图上绘制检测到的位置
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(img,(x,y),(x+w,y+h),(0,0,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(img,(x,y),(x+w,y+h),(0,255,0),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(img,(x,y),(x+w,y+h),(255,0,0),2)
# 显示结果图像
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
注意,这只是一个示例代码,实际应用中需要根据具体情况调整颜色范围和其他参数。
阅读全文