写一段python代码,识别到红色或者黄色指出来
时间: 2023-05-28 14:06:39 浏览: 62
这里提供一种基于OpenCV的简单实现,可以实时从摄像头读取图像,识别红色和黄色,并在图像上用方框标记出来。
```python
import cv2
# 颜色范围,可以根据实际情况进行调整
lower_red = (0, 100, 100)
upper_red = (10, 255, 255)
lower_yellow = (26, 43, 46)
upper_yellow = (34, 255, 255)
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取一帧图像
ret, frame = cap.read()
if not ret:
break
# 将图像转换为HSV色彩空间
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# 提取红色区域并标记
mask_red = cv2.inRange(hsv, lower_red, upper_red)
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), (0, 0, 255), 2)
# 提取黄色区域并标记
mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)
contours_yellow, _ = cv2.findContours(mask_yellow, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours_yellow:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 255), 2)
# 显示结果
cv2.imshow('frame', frame)
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
运行代码后,会打开摄像头并实时显示图像。如果检测到红色或黄色,会在图像上用红色或黄色的方框标记出来。按下键盘上的“q”键可以退出程序。