用vscode编写python代码,请写出利用opencv实现对单张图片traffic.jpg进行交通灯颜色(红,绿,蓝)的颜色识别的完整代码
时间: 2024-11-23 13:39:09 浏览: 18
在VSCode中编写Python代码并使用OpenCV进行交通灯颜色识别,你需要安装`opencv-python-headless`库,因为对于仅显示图像而不需要GUI的情况,它是轻量级的选择。以下是一个基本的步骤示例:
```python
# 导入必要的库
import cv2
import numpy as np
# 加载图片
image_path = 'traffic.jpg'
img = cv2.imread(image_path)
# 将图像转换为HSV颜色空间,方便区分颜色
hsv_image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# 定义交通灯颜色范围 (这里是红色、绿色和蓝色的基本值,需要根据实际图片调整)
red_lower = np.array([0, 45, 70])
red_upper = np.array([10, 255, 255])
green_lower = np.array([36, 45, 70])
green_upper = np.array([86, 255, 255])
blue_lower = np.array([100, 45, 70])
blue_upper = np.array([130, 255, 255])
# 使用掩码获取每个颜色区域的像素
mask_red = cv2.inRange(hsv_image, red_lower, red_upper)
mask_green = cv2.inRange(hsv_image, green_lower, green_upper)
mask_blue = cv2.inRange(hsv_image, blue_lower, blue_upper)
# 对每个颜色应用计数
red_pixels = np.sum(mask_red)
green_pixels = np.sum(mask_green)
blue_pixels = np.sum(mask_blue)
# 判断哪种颜色占主导
dominant_color = None
if red_pixels > green_pixels and red_pixels > blue_pixels:
dominant_color = "Red"
elif green_pixels > red_pixels and green_pixels > blue_pixels:
dominant_color = "Green"
else:
dominant_color = "Blue"
print(f"The dominant color is {dominant_color}.")
#
阅读全文