用python调用摄像头识别红,绿,黄三种颜色,并且红色输出1,绿色输出2,黄色输出3,并标记出来
时间: 2023-06-09 12:07:40 浏览: 102
好的,您可以使用OpenCV库来实现这个功能。以下是一段可能的代码:
```python
import cv2
# 定义红、绿、黄三种颜色的颜色范围
lower_red = (0, 0, 100)
upper_red = (30, 30, 255)
lower_green = (0, 100, 0)
upper_green = (30, 255, 30)
lower_yellow = (0, 200, 200)
upper_yellow = (30, 255, 255)
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取一帧图像
ret, img = cap.read()
# 转换图像颜色空间为HSV
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_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)
# 对掩码图像进行形态学操作,去除噪音
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
mask_red = cv2.morphologyEx(mask_red, cv2.MORPH_OPEN, kernel)
mask_green = cv2.morphologyEx(mask_green, cv2.MORPH_OPEN, kernel)
mask_yellow = cv2.morphologyEx(mask_yellow, cv2.MORPH_OPEN, kernel)
# 找出红色区域并输出1
contours, hierarchy = cv2.findContours(mask_red, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
cv2.drawContours(img, [cnt], 0, (0, 0, 255), 2)
cv2.putText(img, '1', (cnt[0][0][0], cnt[0][0][1]), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
# 找出绿色区域并输出2
contours, hierarchy = cv2.findContours(mask_green, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
cv2.drawContours(img, [cnt], 0, (0, 255, 0), 2)
cv2.putText(img, '2', (cnt[0][0][0], cnt[0][0][1]), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# 找出黄色区域并输出3
contours, hierarchy = cv2.findContours(mask_yellow, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
cv2.drawContours(img, [cnt], 0, (0, 255, 255), 2)
cv2.putText(img, '3', (cnt[0][0][0], cnt[0][0][1]), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2)
# 显示图像
cv2.imshow('result', img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 关闭摄像头并释放资源
cap.release()
cv2.destroyAllWindows()
```
注意,本段代码只是基本示例,您可能需要根据实际情况进行调整和优化。
阅读全文