利用opencv识别红绿蓝色块的代码
时间: 2023-10-23 18:09:54 浏览: 84
以下是一个简单的利用 OpenCV 实现颜色块检测的代码:
```python
import cv2
import numpy as np
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取视频帧
ret, frame = cap.read()
# 转换为 HSV 颜色空间
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# 设定颜色阈值
lower_red = np.array([0, 50, 50])
upper_red = np.array([10, 255, 255])
lower_green = np.array([50, 50, 50])
upper_green = np.array([70, 255, 255])
lower_blue = np.array([110, 50, 50])
upper_blue = np.array([130, 255, 255])
# 利用颜色阈值进行掩膜操作,提取颜色块
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.morphologyEx(mask_red, cv2.MORPH_CLOSE, kernel)
mask_green = cv2.morphologyEx(mask_green, cv2.MORPH_CLOSE, kernel)
mask_blue = cv2.morphologyEx(mask_blue, cv2.MORPH_CLOSE, kernel)
# 查找轮廓
contours_red, _ = cv2.findContours(mask_red, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours_green, _ = cv2.findContours(mask_green, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours_blue, _ = cv2.findContours(mask_blue, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 绘制轮廓
cv2.drawContours(frame, contours_red, -1, (0, 0, 255), 2)
cv2.drawContours(frame, contours_green, -1, (0, 255, 0), 2)
cv2.drawContours(frame, contours_blue, -1, (255, 0, 0), 2)
# 显示结果
cv2.imshow('frame', frame)
# 按下 q 键退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
```
这段代码利用了 OpenCV 的颜色阈值、掩膜、形态学操作和轮廓查找等功能,可以实现对红、绿、蓝色块的识别和绘制。
阅读全文