简单方法识别红绿灯 Python opencv
时间: 2023-10-16 15:11:02 浏览: 141
python红绿灯检测opencv识别红绿灯信号灯检测
5星 · 资源好评率100%
以下是一种简单的方法来识别红绿灯。它使用Python和OpenCV库。
步骤1:导入库
```
import cv2
import numpy as np
```
步骤2:读取图像
```
img = cv2.imread('image.jpg')
```
步骤3:将图像转换为HSV颜色空间
```
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
```
步骤4:定义颜色范围
```
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])
```
步骤5:创建掩码
```
mask_red = cv2.inRange(hsv, lower_red, upper_red)
mask_green = cv2.inRange(hsv, lower_green, upper_green)
```
步骤6:应用形态学操作
```
kernel = np.ones((5,5),np.uint8)
mask_red = cv2.morphologyEx(mask_red, cv2.MORPH_OPEN, kernel)
mask_red = cv2.morphologyEx(mask_red, cv2.MORPH_CLOSE, kernel)
mask_green = cv2.morphologyEx(mask_green, cv2.MORPH_OPEN, kernel)
mask_green = cv2.morphologyEx(mask_green, cv2.MORPH_CLOSE, kernel)
```
步骤7:计算轮廓
```
contours_red, _ = cv2.findContours(mask_red, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours_green, _ = cv2.findContours(mask_green, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
```
步骤8:绘制轮廓
```
cv2.drawContours(img, contours_red, -1, (0, 0, 255), 3)
cv2.drawContours(img, contours_green, -1, (0, 255, 0), 3)
```
步骤9:显示结果
```
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
完整代码如下:
```
import cv2
import numpy as np
img = cv2.imread('image.jpg')
hsv = cv2.cvtColor(img, 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])
mask_red = cv2.inRange(hsv, lower_red, upper_red)
mask_green = cv2.inRange(hsv, lower_green, upper_green)
kernel = np.ones((5,5),np.uint8)
mask_red = cv2.morphologyEx(mask_red, cv2.MORPH_OPEN, kernel)
mask_red = cv2.morphologyEx(mask_red, cv2.MORPH_CLOSE, kernel)
mask_green = cv2.morphologyEx(mask_green, cv2.MORPH_OPEN, kernel)
mask_green = cv2.morphologyEx(mask_green, cv2.MORPH_CLOSE, kernel)
contours_red, _ = cv2.findContours(mask_red, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours_green, _ = cv2.findContours(mask_green, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours_red, -1, (0, 0, 255), 3)
cv2.drawContours(img, contours_green, -1, (0, 255, 0), 3)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文