Traffic Signs Recognition
Traffic Signs Recognition
There are several different types of traffic signs like speed limits, no entry, traffic signals, turn left
or right, children crossing, no passing of heavy vehicles, etc. Traffic signs classification is the
process of identifying which class a traffic sign belongs to.
Prerequisites
This project requires prior knowledge of Keras, Matplotlib, Scikit-learn, Pandas, PIL and image
classification.
To install the necessary packages used for this Python data science project, enter the below
command in your terminal:
Our approach to building this traffic sign classification model is discussed in four steps:
Finally, we have stored all the images and their labels into lists (data and labels).
We need to convert the list into numpy arrays for feeding to the model.
The shape of data is (39209, 30, 30, 3) which means that there are 39,209 images of size 30×30
pixels and the last 3 means the data contains colored images (RGB value).
With the sklearn package, we use the train_test_split() method to split training and testing data.
From the keras.utils package, we use to_categorical method to convert the labels present in
y_train and t_test into one-hot encoding.
Plotting Accuracy
Accuracy and Loss Graphs
In the end, we are going to save the model that we have trained using the Keras model.save()
function.
model.save(‘traffic_classifier.h5’)
import pandas as pd
import cv2
import tensorflow as tf
data = []
labels = []
classes = 43
cur_path = os.getcwd()
for i in range(classes):
path = os.path.join(cur_path,'train',str(i))
images = os.listdir(path)
for a in images:
try:
image = image.resize((30,30))
image = np.array(image)
#sim = Image.fromarray(image)
data.append(image)
labels.append(i)
except:
data = np.array(data)
labels = np.array(labels)
print(data.shape, labels.shape)
model = Sequential()
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Dropout(rate=0.25))
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Dropout(rate=0.25))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(rate=0.5))
model.add(Dense(43, activation='softmax'))
epochs = 15
model.save("my_model.h5")
plt.figure(0)
plt.title('Accuracy')
plt.xlabel('epochs')
plt.ylabel('accuracy')
plt.legend()
plt.show()
plt.figure(1)
plt.title('Loss')
plt.xlabel('epochs')
plt.ylabel('loss')
plt.legend()
plt.show()
y_test = pd.read_csv('Test.csv')
labels = y_test["ClassId"].values
imgs = y_test["Path"].values
data=[]
image = Image.open(img)
image = image.resize((30,30))
data.append(np.array(image))
X_test=np.array(data)
pred = model.predict_classes(X_test)
print(accuracy_score(labels, pred))
model.save(‘traffic_classifier.h5’)
Traffic Signs Classifier GUI
Now we are going to build a graphical user interface for our traffic signs classifier with Tkinter.
Tkinter is a GUI toolkit in the standard python library. Make a new file in the project folder and
copy the below code. Save it as gui.py and you can run the code by typing python gui.py in the
command line.
In this file, we have first loaded the trained model ‘traffic_classifier.h5’ using Keras. And then we
build the GUI for uploading the image and a button is used to classify which calls the classify()
function. The classify() function is converting the image into the dimension of shape (1, 30, 30,
3). This is because to predict the traffic sign we have to provide the same dimension we have used
when building the model. Then we predict the class, the model.predict_classes(image) returns us
a number between (0-42) which represents the class it belongs to. We use the dictionary to get
the information about the class. Here’s the code for the gui.py file.
Code:
import tkinter as tk
import numpy
model = load_model('traffic_classifier.h5')
10:'No passing',
12:'Right-of-way at intersection',
13:'Priority road',
14:'Yield',
15:'Stop',
16:'No vehicles',
18:'No entry',
19:'General caution',
23:'Bumpy road',
24:'Slippery road',
26:'Road work',
27:'Traffic signals',
28:'Pedestrians',
29:'Children crossing',
30:'Bicycles crossing',
31:'Beware of ice/snow',
36:'Ahead only',
39:'Keep right',
40:'Keep left',
41:'Roundabout mandatory',
42:'End of no passing',
#initialise GUI
top=tk.Tk()
top.geometry('800x600')
top.configure(background='#CDCDCD')
label=Label(top,background='#CDCDCD', font=('arial',15,'bold'))
sign_image = Label(top)
def classify(file_path):
global label_packed
image = Image.open(file_path)
image = image.resize((30,30))
image = numpy.array(image)
pred = model.predict_classes([image])[0]
sign = classes[pred+1]
print(sign)
label.configure(foreground='#011638', text=sign)
def show_classify_button(file_path):
classify_b.configure(background='#364156', foreground='white',font=('arial',10,'bold'))
classify_b.place(relx=0.79,rely=0.46)
def upload_image():
try:
file_path=filedialog.askopenfilename()
uploaded=Image.open(file_path)
uploaded.thumbnail(((top.winfo_width()/2.25),(top.winfo_height()/2.25)))
im=ImageTk.PhotoImage(uploaded)
sign_image.configure(image=im)
sign_image.image=im
label.configure(text='')
show_classify_button(file_path)
except:
pass
upload=Button(top,text="Upload an image",command=upload_image,padx=10,pady=5)
upload.configure(background='#364156', foreground='white',font=('arial',10,'bold'))
upload.pack(side=BOTTOM,pady=50)
sign_image.pack(side=BOTTOM,expand=True)
label.pack(side=BOTTOM,expand=True)
heading.configure(background='#CDCDCD',foreground='#364156')
heading.pack()
top.mainloop()
Output: