Skip to content

Commit 9283902

Browse files
authored
Merge pull request larymak#230 from sohamdc/patch-1
Add Trafic Sign Recognition using CNN and Keras.
2 parents 3f1c35b + 73cf24d commit 9283902

File tree

3 files changed

+228
-0
lines changed

3 files changed

+228
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
Download the CSV file from the following link https://www.kaggle.com/datasets/meowmeowmeowmeowmeow/gtsrb-german-traffic-sign
2+
You've probably heard about self-driving automobiles, in which the driver is completely dependent on the vehicle for transportation. But for vehicles to reach level 5 autonomy, all traffic regulations must be understood and adhered to.
3+
Speed limits, no entry, traffic signals, turns to the left or right, children crossing, no passage of heavy trucks, etc. are just a few examples of the various types of traffic signs. The process of determining which class a traffic sign belongs to is known as categorization of traffic signs.
4+
5+
![traffic signjpg1](https://user-images.githubusercontent.com/61727479/198211059-8629caa2-e441-4c5e-9f24-d12feaf2199a.jpg)
6+
![traffic signjpg2](https://user-images.githubusercontent.com/61727479/198211180-66c94d0e-1586-44d1-adec-ca9de1f1122c.jpg)
7+
![traffic signjpg3](https://user-images.githubusercontent.com/61727479/198211202-d636ddd4-94ba-4e34-92ff-20f67076e084.jpg)
8+
9+
Follow the instructions below to run the project:-
10+
*install Python, jupyter notebook to run the project.
11+
*Import the relative path of the dataset clone the project and install all the required libraries and run the ipynb file in jupyter notebook.
12+
*Download the CSV file from the following link https://www.kaggle.com/datasets/meowmeowmeowmeowmeow/gtsrb-german-traffic-sign.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import tkinter as tk
2+
from tkinter import filedialog
3+
from tkinter import *
4+
from PIL import ImageTk, Image
5+
6+
import numpy
7+
#load the trained model to classify sign
8+
from keras.models import load_model
9+
model = load_model('traffic_classifier.h5')
10+
11+
#dictionary to label all traffic signs class.
12+
classes = { 1:'Speed limit (20km/h)',
13+
2:'Speed limit (30km/h)',
14+
3:'Speed limit (50km/h)',
15+
4:'Speed limit (60km/h)',
16+
5:'Speed limit (70km/h)',
17+
6:'Speed limit (80km/h)',
18+
7:'End of speed limit (80km/h)',
19+
8:'Speed limit (100km/h)',
20+
9:'Speed limit (120km/h)',
21+
10:'No passing',
22+
11:'No passing veh over 3.5 tons',
23+
12:'Right-of-way at intersection',
24+
13:'Priority road',
25+
14:'Yield',
26+
15:'Stop',
27+
16:'No vehicles',
28+
17:'Veh > 3.5 tons prohibited',
29+
18:'No entry',
30+
19:'General caution',
31+
20:'Dangerous curve left',
32+
21:'Dangerous curve right',
33+
22:'Double curve',
34+
23:'Bumpy road',
35+
24:'Slippery road',
36+
25:'Road narrows on the right',
37+
26:'Road work',
38+
27:'Traffic signals',
39+
28:'Pedestrians',
40+
29:'Children crossing',
41+
30:'Bicycles crossing',
42+
31:'Beware of ice/snow',
43+
32:'Wild animals crossing',
44+
33:'End speed + passing limits',
45+
34:'Turn right ahead',
46+
35:'Turn left ahead',
47+
36:'Ahead only',
48+
37:'Go straight or right',
49+
38:'Go straight or left',
50+
39:'Keep right',
51+
40:'Keep left',
52+
41:'Roundabout mandatory',
53+
42:'End of no passing',
54+
43:'End no passing veh > 3.5 tons' }
55+
56+
#initialise GUI
57+
top=tk.Tk()
58+
top.geometry('800x600')
59+
top.title('Traffic sign classification')
60+
top.configure(background='#CDCDCD')
61+
62+
label=Label(top,background='#CDCDCD', font=('arial',15,'bold'))
63+
sign_image = Label(top)
64+
65+
def classify(file_path):
66+
global label_packed
67+
image = Image.open(file_path)
68+
image = image.resize((30,30))
69+
image = numpy.expand_dims(image, axis=0)
70+
image = numpy.array(image)
71+
print(image.shape)
72+
pred = model.predict_classes([image])[0]
73+
sign = classes[pred+1]
74+
print(sign)
75+
label.configure(foreground='#011638', text=sign)
76+
77+
78+
def show_classify_button(file_path):
79+
classify_b=Button(top,text="Classify Image",command=lambda: classify(file_path),padx=10,pady=5)
80+
classify_b.configure(background='#364156', foreground='white',font=('arial',10,'bold'))
81+
classify_b.place(relx=0.79,rely=0.46)
82+
83+
def upload_image():
84+
try:
85+
file_path=filedialog.askopenfilename()
86+
uploaded=Image.open(file_path)
87+
uploaded.thumbnail(((top.winfo_width()/2.25),(top.winfo_height()/2.25)))
88+
im=ImageTk.PhotoImage(uploaded)
89+
90+
sign_image.configure(image=im)
91+
sign_image.image=im
92+
label.configure(text='')
93+
show_classify_button(file_path)
94+
except:
95+
pass
96+
97+
upload=Button(top,text="Upload an image",command=upload_image,padx=10,pady=5)
98+
upload.configure(background='#364156', foreground='white',font=('arial',10,'bold'))
99+
100+
upload.pack(side=BOTTOM,pady=50)
101+
sign_image.pack(side=BOTTOM,expand=True)
102+
label.pack(side=BOTTOM,expand=True)
103+
heading = Label(top, text="Know Your Traffic Sign",pady=20, font=('arial',20,'bold'))
104+
heading.configure(background='#CDCDCD',foreground='#364156')
105+
heading.pack()
106+
top.mainloop()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import numpy as np
2+
import pandas as pd
3+
import matplotlib.pyplot as plt
4+
import cv2
5+
import tensorflow as tf
6+
from PIL import Image
7+
import os
8+
from sklearn.model_selection import train_test_split
9+
from keras.utils import to_categorical
10+
from keras.models import Sequential, load_model
11+
from keras.layers import Conv2D, MaxPool2D, Dense, Flatten, Dropout
12+
13+
data = []
14+
labels = []
15+
classes = 43
16+
cur_path = os.getcwd()
17+
18+
#Retrieving the images and their labels
19+
for i in range(classes):
20+
path = os.path.join(cur_path,'train',str(i))
21+
images = os.listdir(path)
22+
23+
for a in images:
24+
try:
25+
image = Image.open(path + '\\'+ a)
26+
image = image.resize((30,30))
27+
image = np.array(image)
28+
#sim = Image.fromarray(image)
29+
data.append(image)
30+
labels.append(i)
31+
except:
32+
print("Error loading image")
33+
34+
#Converting lists into numpy arrays
35+
data = np.array(data)
36+
labels = np.array(labels)
37+
38+
print(data.shape, labels.shape)
39+
#Splitting training and testing dataset
40+
X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, random_state=42)
41+
42+
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
43+
44+
#Converting the labels into one hot encoding
45+
y_train = to_categorical(y_train, 43)
46+
y_test = to_categorical(y_test, 43)
47+
48+
#Building the model
49+
model = Sequential()
50+
model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu', input_shape=X_train.shape[1:]))
51+
model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu'))
52+
model.add(MaxPool2D(pool_size=(2, 2)))
53+
model.add(Dropout(rate=0.25))
54+
model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))
55+
model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))
56+
model.add(MaxPool2D(pool_size=(2, 2)))
57+
model.add(Dropout(rate=0.25))
58+
model.add(Flatten())
59+
model.add(Dense(256, activation='relu'))
60+
model.add(Dropout(rate=0.5))
61+
model.add(Dense(43, activation='softmax'))
62+
63+
#Compilation of the model
64+
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
65+
66+
epochs = 15
67+
history = model.fit(X_train, y_train, batch_size=32, epochs=epochs, validation_data=(X_test, y_test))
68+
model.save("my_model.h5")
69+
70+
#plotting graphs for accuracy
71+
plt.figure(0)
72+
plt.plot(history.history['accuracy'], label='training accuracy')
73+
plt.plot(history.history['val_accuracy'], label='val accuracy')
74+
plt.title('Accuracy')
75+
plt.xlabel('epochs')
76+
plt.ylabel('accuracy')
77+
plt.legend()
78+
plt.show()
79+
80+
plt.figure(1)
81+
plt.plot(history.history['loss'], label='training loss')
82+
plt.plot(history.history['val_loss'], label='val loss')
83+
plt.title('Loss')
84+
plt.xlabel('epochs')
85+
plt.ylabel('loss')
86+
plt.legend()
87+
plt.show()
88+
89+
#testing accuracy on test dataset
90+
from sklearn.metrics import accuracy_score
91+
92+
y_test = pd.read_csv('Test.csv')
93+
94+
labels = y_test["ClassId"].values
95+
imgs = y_test["Path"].values
96+
97+
data=[]
98+
99+
for img in imgs:
100+
image = Image.open(img)
101+
image = image.resize((30,30))
102+
data.append(np.array(image))
103+
104+
X_test=np.array(data)
105+
106+
pred = model.predict_classes(X_test)
107+
108+
#Accuracy with the test data
109+
from sklearn.metrics import accuracy_score
110+
print(accuracy_score(labels, pred))

0 commit comments

Comments
 (0)