整个项目源码:
GitHub
前面我们讲完交通标志的识别,现在我们开始尝试来实现交通信号灯的识别
接下来我们将按照自己的思路来实现并完善整个Project.
在这个项目中,我们使用HSV色彩空间来识别交通灯,可以改善及提高的地方:
-
可以采用Faster-RCNN或SSD来实现交通灯的识别
首先我们第一步是导入数据,并在RGB及HSV色彩空间可视化部分数据。这里的数据,我们采用
MIT自动驾驶课程
的图片,
总共三类:红绿黄,1187张图片,其中,723张红色交通灯图片,429张绿色交通灯图片,35张黄色交通灯图片。
import cv2
import os
import glob
import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline
IMAGE_DIR_TRAINING = "traffic_light_images/training/"
IMAGE_DIR_TEST = "traffic_light_images/test/"
def load_dataset(image_dir):
This function loads in images and their labels and places them in a list
image_dir:directions where images stored
im_list =[]
image_types= ['red','yellow','green']
for im_type in image_types:
file_lists = glob.glob(os.path.join(image_dir,im_type,'*'))
print(len(file_lists))
for file in file_lists:
im = mpimg.imread(file)
if not im is None:
im_list.append((im,im_type))
return im_list
IMAGE_LIST = load_dataset(IMAGE_DIR_TRAINING)
这里可视化主要实现:
_,ax = plt.subplots(1,3,figsize=(5,2))
img_red = IMAGE_LIST[0][0]
ax[0].imshow(img_red)
ax[0].annotate(IMAGE_LIST[0][1],xy=(2,5),color='blue',fontsize='10')
ax[0].axis('off')
ax[0].set_title(img_red.shape,fontsize=10)
img_yellow = IMAGE_LIST[730][0]
ax[1].imshow(img_yellow)
ax[1].annotate(IMAGE_LIST[730][1],xy=(2,5),color='blue',fontsize='10')
ax[1].axis('off')
ax[1].set_title(img_yellow.shape,fontsize=10)
img_green = IMAGE_LIST[800][0]
ax[2].imshow(img_green)
ax[2].annotate(IMAGE_LIST[800][1],xy=(2,5),color='blue',fontsize='10')
ax[2].axis('off')
ax[2].set_title(img_green.shape,fontsize=10)
plt.show()
在导入了上述数据后,接下来我们需要标准化输入及输出
从上图,我们可以看出,每张图片的大小并不一样,我们需要标准化输入
将每张图图片的大小resize成相同的大小,
因为对于分类任务来说,我们需要
在每张图片上应用相同的算法,因此标准化图像尤其重要
这里我们的标签数据是类别数据:‘red’,‘yellow’,‘green’,因此我们可以利用one_hot方法将类别数据转换成数值数据
def standardize(image_list):
This function takes a rgb image as input and return a standardized version
image_list: image and label
standard_list = []
for item in image_list:
image = item[0]
label = item[1]
standardized_im = standardize_input(image)
one_hot_label = one_hot_encode(label)
standard_list.append((standardized_im,one_hot_label))
return standard_list
def standardize_input(image):
standard_im = cv2.resize(image,(32,32))
return standard_im
def one_hot_encode(label):
# one_hot_encode("red") should return: [1, 0, 0]
# one_hot_encode("yellow") should return: [0, 1, 0]
# one_hot_encode("green") should return: [0, 0, 1]
if label=='red':
return [1,0,0]
elif label=='yellow':
return [0,1,0]
else:
return [0,0,1]
实现完了上述标准化代码后,我们需要进一步确定我们的代码是正确的,因此接下来我们可以实现一个函数来实现上述代码功能的检验
用Python搭建自动化测试框架,我们需要组织用例以及测试执行,这里我们推荐Python的标准库——unittest。
import unittest
from IPython.display import Markdown,display
def printmd(string):
display(Markdown(string))
def print_fail
():
printmd('**<span style=="color: red;">Test Failed</span>**')
def print_pass():
printmd('**<span style="color:green;">Test Passed</span>**')
class Tests(unittest.TestCase):
def test_one_hot(self,one_hot_function):
try:
self.assertEqual([1,0,0],one_hot_function('red'))
self.assertEqual([0,1,0],one_hot_function('yellow'))
self.assertEqual([0,0,1],one_hot_function('green'))
except self.failureException as e:
print_fail()
print('Your function did not return the excepted one-hot label')
print('\n'+str(e))
return
print_pass()
def test_red_aa_green(self,misclassified_images):
for im,predicted_label,true_label in misclassified_images:
if(true_label==[1,0,0]):
try:
self.assertNotEqual(true_label,[0,1,0])
except self.failureException as e:
print_fail()
print('Warning:A red light is classified as green.')
print('\n'+str(e))
return
print_pass()
tests = Tests()
tests.test_one_hot(one_hot_encode)
Test Passed
Standardized_Train_List = standardize(IMAGE_LIST)
image_num = 0
test_im = Standardized_Train_List[image_num][0]
test_label = Standardized_Train_List[image_num][1]
hsv = cv2.cvtColor(test_im, cv2.COLOR_RGB2HSV)
print('Label [red, yellow, green]: ' + str(test_label))
h = hsv[:,:,0]
s = hsv[:,:,1]
v = hsv[:,:,2]
_, ax = plt.subplots(1, 4, figsize=(20,10))
ax[0].set_title('Standardized image')
ax[0].imshow(test_im)
ax[1].set_title('H channel')
ax[1].imshow(h, cmap='gray')
ax[2].set_title('S channel')
ax[2].imshow(s, cmap='gray')
ax[3].set_title('V channel')
ax[3].imshow(v, cmap='gray')
Label [red, yellow, green]: [1, 0, 0]
HSV即色相、饱和度、明度(英语:Hue, Saturation, Value),又称HSB,其中B即英语:Brightness。
色相(H)是色彩的基本属性,就是平常所说的颜色名称,如红色、黄色等。
饱和度(S)是指色彩的纯度,越高色彩越纯,低则逐渐变灰,取0-100%的数值。
明度(V),亮度(L),取0-100%。
def create_feature(rgb_image):
Basic brightness feature
rgb_image : a rgb_image
hsv = cv2.cvtColor(rgb_image,cv2.COLOR_RGB2HSV)
sum_brightness = np.sum(hsv[:,:,2])
area = 32*32
avg_brightness = sum_brightness / area
return avg_brightness
def high_saturation_pixels(rgb_image,threshold=80):
Returns average red and green content from high saturation pixels
Usually, the traffic light contained the highest saturation pixels in the image.
The threshold was experimentally determined to be 80
high_sat_pixels = []
hsv = cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV)
for i in range(32):
for j in range(32):
if hsv[i][j][1] > threshold:
high_sat_pixels.append(rgb_image[i][j])
if not high_sat_pixels:
return highest_sat_pixel(rgb_image)
sum_red = 0
sum_green = 0
for pixel in high_sat_pixels:
sum_red+=pixel[0]
sum_green+=
pixel[1]
avg_red = sum_red / len(high_sat_pixels)
avg_green = sum_green / len(high_sat_pixels)*0.8
return avg_red,avg_green
def highest_sat_pixel(rgb_image):
Finds the highest saturation pixels, and checks if it has a higher green
or a higher red content
hsv = cv2.cvtColor(rgb_image,cv2.COLOR_RGB2HSV)
s = hsv[:,:,1]
x,y = (np.unravel_index(np.argmax(s),s.shape))
if rgb_image[x,y,0] > rgb_image[x,y,1]*0.9:
return 1,0
return 0,1
接下来我们导入测试集来看看,上述方法的测试精度
上述方法我们实现了:
1.求平均的brightness
2.求red及green的色彩饱和度
有人或许会提出疑问,为啥没有进行yellow的判断,因此我们作出以下的改善
reference url
这里部分阈值,我们直接参考WIKI上的数据:

def estimate_label(rgb_image,display=False):
rgb_image:Standardized RGB image
return red_green_yellow(rgb_image,display)
def findNoneZero(rgb_image):
rows,cols,_ = rgb_image.shape
counter = 0
for row in range(rows):
for col in range(cols):
pixels = rgb_image[row,col]
if sum(pixels)!=0:
counter = counter+1
return counter
def red_green_yellow(rgb_image,display):
Determines the red , green and yellow content in each image using HSV and experimentally
determined thresholds. Returns a Classification based on the values
hsv = cv2.cvtColor(rgb_image,cv2.COLOR_RGB2HSV)
sum_saturation = np.sum(hsv[:,:,1])
area = 32*32
avg_saturation = sum_saturation / area
sat_low = int(avg_saturation*1.3)
val_low = 140
lower_green = np.array([70,sat_low,val_low])
upper_green = np.array([100,255,255])
green_mask = cv2.inRange(hsv,lower_green,upper_green)
green_result = cv2.bitwise_and(rgb_image,rgb_image,mask = green_mask)
lower_yellow = np.array([10,sat_low,val_low])
upper_yellow = np.array([60,255,255])
yellow_mask = cv2.inRange(hsv,lower_yellow,upper_yellow)
yellow_result = cv2.bitwise_and(rgb_image,rgb_image,mask=yellow_mask)
lower_red = np.array([150,sat_low,val_low])
upper_red = np.array([180,255,255])
red_mask = cv2.inRange(hsv,lower_red,upper_red)
red_result = cv2.bitwise_and(rgb_image,rgb_image,mask = red_mask)
if display==True:
_,ax = plt.subplots(1,5,figsize=(20,10))
ax[0].set_title('rgb image')
ax[0].imshow(rgb_image)
ax[1].set_title('red result')
ax[1].imshow(red_result)
ax[2].set_title('yellow result')
ax[2].imshow(yellow_result)
ax[3].set_title('green result')
ax[3].imshow(green_result)
ax[4].set_title('hsv image')
ax[4].imshow(hsv)
plt.show()
sum_green = findNoneZero(green_result)
sum_red = findNoneZero(red_result)
sum_yellow = findNoneZero(yellow_result)
if sum_red >= sum_yellow and sum_red>=sum_green:
return [1,0,0]
if sum_yellow>=sum_green:
return [0,1,0]
return [0,0,1]
接下来我们选择三张图片来看看测试效果
img_red,img_yellow,img_green
img_test = [(img_red,'red'),(img_yellow,'yellow'),(img_green,'green')]
standardtest = standardize(img_test)
for img in standardtest:
predicted_label = estimate_label(img[0],display = True)
print('Predict label :',predicted_label)
print('True label:',img[1])
Predict label : [1, 0, 0]
True label: [1, 0, 0]
Predict label : [0, 1, 0]
True label: [0, 1, 0]
Predict label : [0, 0, 1]
True label: [0, 0, 1]
TEST_IMAGE_LIST = load_dataset(IMAGE_DIR_TEST)
STANDARDIZED_TEST_LIST = standardize(TEST_IMAGE_LIST)
random.shuffle(STANDARDIZED_TEST_LIST)
接下来我们来看看咱们算法在测试集上的准确率。下面我们实现的代码存储所有的被错分的图片以及它们被预测的结果及真实标签。
这些数据被存储在MISCLASSIFIED.
def get_misclassified_images(test_images,display=False):
misclassified_images_labels = []
for image in test_images:
im = image[0]
true_label = image[1]
assert (len(true_label)==3),'This true_label is not the excepted length (3).'
predicted_label = estimate_label(im,display=False)
assert(len(predicted_label)==3),'This predicted_label is not the excepted length (3).'
if(predicted_label!=true_label):
misclassified_images_labels.append((im,predicted_label,true_label))
return misclassified_images_labels
MISCLASSIFIED = get_misclassified_images(STANDARDIZED_TEST_LIST,display=False)
total = len(STANDARDIZED_TEST_LIST)
num_correct = total-len(MISCLASSIFIED)
accuracy = num_correct / total
print('Accuracy:'+str(accuracy))
print('Number of misclassfied images = '+str(len(MISCLASSIFIED))+' out of '+str(total))
Accuracy:0.9797979797979798
Number of misclassfied images = 6 out of 297
使用单独模型的物体(交通灯)检测和分类。
考虑到红绿灯始终处于相同状态,并专注于创建轻量级和快速模型,我们选择了对整个图像进行分类的方向。
这种方法使用卷积神经网络,它将前置摄像头的整个图像作为输入,并预测交通灯状态(我们决定使用红色/无预测类)作为输出。
MobileNet
架构上使用了迁移学习技术和
Tensorflow
Image
Retraining
Example(教程:,代码:)。
有多个数据集可用于模型训练:
Udacity
模拟器的图像(图像以及来自前置摄像头的地面实况可作为
主题提供);
rosbag,在
Udacity
的测试站点上捕获
简介:OpenCV是一个强大的计算机视觉库,它在自动驾驶和智能交通系统中发挥重要作用。本文将讨论使用OpenCV进行红绿灯识别和运动物体识别的关键技术,包括图像预处理、色彩空间转换、形状检测、特征提取和分类器的使用。同时,也会探讨运动物体识别中涉及的背景建模、区域分割、去除误报、物体跟踪和分类识别。这些技术能够帮助开发者实现复杂视觉算法,如实时红绿灯状态检测和移动物体的识别与跟踪。
基于YOLOv11的交通信号灯检测系统主要用于日常生活中的红绿灯检测,显示目标在图像中的类别、位置、数目、置信度等;可对单张图片、文件夹、视频文件读取的图像,或从摄像头获取的实时画面中的交通灯进行识别,算法模型可选择替换;(这里,支持多种算法切换-从YOLOv8-YOLOv11都是可以用的,如果你手头有训练好的不是YOLOv11的模型,那也可以使用,直接选择就能使用;兼容性比较高);界面包含识别结果可视化,结果实时显示并能够进行目标逐个标注、显示和数据展示;画面显示窗口可缩放、拖动、自适应,结果可点击按钮保
毕业设计:基于深度学习的交通灯识别算法系统为了提升模型的性能,我们自制了一个交通灯数据集,并进行了数据扩充。通过大量的实验验证,我们的算法系统在不同的光照、天气和遮挡条件下均表现出较高的识别准确率。为计算机毕业设计提供了一个创新的方向,结合了深度学习和计算机视觉技术,为毕业生提供了一个有意义的研究课题。对于计算机专业、软件工程专业、人工智能专业、大数据专业的毕业生而言,这是一个具有挑战性和创新性的研究课题。无论您对深度学习技术保持浓厚兴趣,还是希望探索机器学习、算法或人工智能的领域的同学,都能为您提供灵感。
突然想起来我还有个博客,好久不更了,就来个使用tensorflow识别红绿灯的项目吧。
现在深度学习大行其道,目前最火热的深度学习框架就是tensorflow了,tensorflow大幅度的减小了我们使用深度学习的成本。今天我们就利用tensorflow来训练一个可以识别红绿灯的项目(训练数据来自MIT开源的数据集)。
首先先明确一下,要完成一个CNN项目的训练和使用,至少需要一下N个步骤:...
红绿灯识别是自动驾驶中最为基础的功能,识别方法主要有两种,一种基于视觉图像识别,一种基于v2x。
v2x,即通过红绿灯自己实时发送信号状态,再由车辆低延迟接收信号。该方法要对红绿灯进行改造,不仅对基础设备信号能力要求过高,而且对网络传输要求也不低,虽说目前5G出来了,但要大规模试用还需要一段时间,除却基础的要求外,对异常信号的处理等由于尚未实验环境,同样难以得到可以论证的方案。
基于视觉图像识别,即通过对2d图像进行检测分类识别获取交通灯的各项状态信息。该方法目前也有两种实现方案,一种基于高精地图位置获
Hello大家好,我是Dream。 OpenCV是一个开源的计算机视觉库,可以用于实现各种图像和视频处理任务,包括红绿灯识别。可以帮助自动驾驶汽车、智能交通系统等设备准确地识别红绿灯的状态,以便做出正确的决策。今天,就有Dream带领大家复盘一下计算机视觉中最经典的实验:OpenCV进行红绿灯识别,一起来看看吧~
随着智能交通的发展,准确识别交通信号灯对提高道路安全和交通效率有重要的作用。传统的交通信号灯识别方法主要依靠传感器,存在安装成本高、维护困难等问题。为解决这些问题,我们利用YOLOV8技术,开发了基于车载摄像头的交通信号灯自动识别系统。