Users Online

· Guests Online: 40

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Python Project on Traffic Signs Recognition with 95% Accuracy using CNN & Keras

Python Project on Traffic Signs Recognition with 95% Accuracy using CNN & Keras

Python Project – Traffic Signs Recognition 

 

 

You must have heard about the self-driving cars in which the passenger can fully depend on the car for traveling. But to achieve level 5 autonomous, it is necessary for vehicles to understand and follow all traffic rules.

In the world of Artificial Intelligence and advancement in technologies, many researchers and big companies like Tesla, Uber, Google, Mercedes-Benz, Toyota, Ford, Audi, etc are working on autonomous vehicles and self-driving cars. So, for achieving accuracy in this technology, the vehicles should be able to interpret traffic signs and make decisions accordingly.

 

 

What is 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.

Traffic Signs Recognition – About the Python Project

In this Python project example, we will build a deep neural network model that can classify traffic signs present in the image into different categories. With this model, we are able to read and understand traffic signs which are a very important task for all autonomous vehicles.

traffic sign recognition python project idea

The Dataset of Python Project

For this project, we are using the public dataset available at Kaggle:

Traffic Signs Dataset

The dataset contains more than 50,000 images of different traffic signs. It is further classified into 43 different classes. The dataset is quite varying, some of the classes have many images while some classes have few images. The size of the dataset is around 300 MB. The dataset has a train folder which contains images inside each class and a test folder which we will use for testing our model.

Python Project on Traffic Signs Recognition Meme

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:

  1. pip install tensorflow keras sklearn matplotlib pandas pil

 

Want to become a pro in Python?

Check out 270+ Free Python Tutorials

Steps to Build the Python Project

To get started with the project, download and unzip the file from this link – Traffic Signs Recognition Zip File

And extract the files into a folder such that you will have a train, test and a meta folder.

Python Project Dataset

Create a Python script file and name it traffic_signs.py in the project folder.

Our approach to building this traffic sign classification model is discussed in four steps:

  • Explore the dataset
  • Build a CNN model
  • Train and validate the model
  • Test the model with test dataset

Step 1: Explore the dataset

Our ‘train’ folder contains 43 folders each representing a different class. The range of the folder is from 0 to 42. With the help of the OS module, we iterate over all the classes and append images and their respective labels in the data and labels list.

The PIL library is used to open image content into an array.

exploring dataset in python project

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.

splitting dataset in python project

Step 2: Build a CNN model

To classify the images into their respective categories, we will build a CNN model (Convolutional Neural Network). CNN is best for image classification purposes.

The architecture of our model is:

  • 2 Conv2D layer (filter=32, kernel_size=(5,5), activation=”relu”)
  • MaxPool2D layer ( pool_size=(2,2))
  • Dropout layer (rate=0.25)
  • 2 Conv2D layer (filter=64, kernel_size=(3,3), activation=”relu”)
  • MaxPool2D layer ( pool_size=(2,2))
  • Dropout layer (rate=0.25)
  • Flatten layer to squeeze the layers into 1 dimension
  • Dense Fully connected layer (256 nodes, activation=”relu”)
  • Dropout layer (rate=0.5)
  • Dense layer (43 nodes, activation=”softmax”)

We compile the model with Adam optimizer which performs well and loss is “categorical_crossentropy” because we have multiple classes to categorise.

cnn model in python data science project

Steps 3: Train and validate the model

After building the model architecture, we then train the model using model.fit(). I tried with batch size 32 and 64. Our model performed better with 64 batch size. And after 15 epochs the accuracy was stable.

training the model in project in python

Our model got a 95% accuracy on the training dataset. With matplotlib, we plot the graph for accuracy and the loss.

plotting accuracy in python project example

Plotting Accuracy

accuracy & loss in python machine learning project

Accuracy and Loss Graphs

Step 4: Test our model with test dataset

Our dataset contains a test folder and in a test.csv file, we have the details related to the image path and their respective class labels. We extract the image path and labels using pandas. Then to predict the model, we have to resize our images to 30×30 pixels and make a numpy array containing all image data. From the sklearn.metrics, we imported the accuracy_score and observed how our model predicted the actual labels. We achieved a 95% accuracy in this model.

testing accuracy in advanced python project

In the end, we are going to save the model that we have trained using the Keras model.save() function.

  1. model.save(‘traffic_classifier.h5’)

Full Source code:

  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. #Converting lists into numpy arrays
  34. data = np.array(data)
  35. labels = np.array(labels)
  36. print(data.shape, labels.shape)
  37. #Splitting training and testing dataset
  38. X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, random_state=42)
  39. print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
  40. #Converting the labels into one hot encoding
  41. y_train = to_categorical(y_train, 43)
  42. y_test = to_categorical(y_test, 43)
  43. #Building the model
  44. model = Sequential()
  45. model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu', input_shape=X_train.shape[1:]))
  46. model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu'))
  47. model.add(MaxPool2D(pool_size=(2, 2)))
  48. model.add(Dropout(rate=0.25))
  49. model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))
  50. model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))
  51. model.add(MaxPool2D(pool_size=(2, 2)))
  52. model.add(Dropout(rate=0.25))
  53. model.add(Flatten())
  54. model.add(Dense(256, activation='relu'))
  55. model.add(Dropout(rate=0.5))
  56. model.add(Dense(43, activation='softmax'))
  57. #Compilation of the model
  58. model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
  59. epochs = 15
  60. history = model.fit(X_train, y_train, batch_size=32, epochs=epochs, validation_data=(X_test, y_test))
  61. model.save("my_model.h5")
  62. #plotting graphs for accuracy
  63. plt.figure(0)
  64. plt.plot(history.history['accuracy'], label='training accuracy')
  65. plt.plot(history.history['val_accuracy'], label='val accuracy')
  66. plt.title('Accuracy')
  67. plt.xlabel('epochs')
  68. plt.ylabel('accuracy')
  69. plt.legend()
  70. plt.show()
  71. plt.figure(1)
  72. plt.plot(history.history['loss'], label='training loss')
  73. plt.plot(history.history['val_loss'], label='val loss')
  74. plt.title('Loss')
  75. plt.xlabel('epochs')
  76. plt.ylabel('loss')
  77. plt.legend()
  78. plt.show()
  79. #testing accuracy on test dataset
  80. from sklearn.metrics import accuracy_score
  81. y_test = pd.read_csv('Test.csv')
  82. labels = y_test["ClassId"].values
  83. imgs = y_test["Path"].values
  84. data=[]
  85. for img in imgs:
  86. image = Image.open(img)
  87. image = image.resize((30,30))
  88. data.append(np.array(image))
  89. X_test=np.array(data)
  90. pred = model.predict_classes(X_test)
  91. #Accuracy with the test data
  92. from sklearn.metrics import accuracy_score
  93. print(accuracy_score(labels, pred))
  94. model.save(‘traffic_classifier.h5’)

WAIT! Have you checked our latest tutorial on OpenCV & Computer Vision

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:

  1. import tkinter as tk
  2. from tkinter import filedialog
  3. from tkinter import *
  4. from PIL import ImageTk, Image
  5. import numpy
  6. #load the trained model to classify sign
  7. from keras.models import load_model
  8. model = load_model('traffic_classifier.h5')
  9. #dictionary to label all traffic signs class.
  10. classes = { 1:'Speed limit (20km/h)',
  11. 2:'Speed limit (30km/h)',
  12. 3:'Speed limit (50km/h)',
  13. 4:'Speed limit (60km/h)',
  14. 5:'Speed limit (70km/h)',
  15. 6:'Speed limit (80km/h)',
  16. 7:'End of speed limit (80km/h)',
  17. 8:'Speed limit (100km/h)',
  18. 9:'Speed limit (120km/h)',
  19. 10:'No passing',
  20. 11:'No passing veh over 3.5 tons',
  21. 12:'Right-of-way at intersection',
  22. 13:'Priority road',
  23. 14:'Yield',
  24. 15:'Stop',
  25. 16:'No vehicles',
  26. 17:'Veh > 3.5 tons prohibited',
  27. 18:'No entry',
  28. 19:'General caution',
  29. 20:'Dangerous curve left',
  30. 21:'Dangerous curve right',
  31. 22:'Double curve',
  32. 23:'Bumpy road',
  33. 24:'Slippery road',
  34. 25:'Road narrows on the right',
  35. 26:'Road work',
  36. 27:'Traffic signals',
  37. 28:'Pedestrians',
  38. 29:'Children crossing',
  39. 30:'Bicycles crossing',
  40. 31:'Beware of ice/snow',
  41. 32:'Wild animals crossing',
  42. 33:'End speed + passing limits',
  43. 34:'Turn right ahead',
  44. 35:'Turn left ahead',
  45. 36:'Ahead only',
  46. 37:'Go straight or right',
  47. 38:'Go straight or left',
  48. 39:'Keep right',
  49. 40:'Keep left',
  50. 41:'Roundabout mandatory',
  51. 42:'End of no passing',
  52. 43:'End no passing veh > 3.5 tons' }
  53. #initialise GUI
  54. top=tk.Tk()
  55. top.geometry('800x600')
  56. top.title('Traffic sign classification')
  57. top.configure(background='#CDCDCD')
  58. label=Label(top,background='#CDCDCD', font=('arial',15,'bold'))
  59. sign_image = Label(top)
  60. def classify(file_path):
  61. global label_packed
  62. image = Image.open(file_path)
  63. image = image.resize((30,30))
  64. image = numpy.expand_dims(image, axis=0)
  65. image = numpy.array(image)
  66. pred = model.predict_classes([image])[0]
  67. sign = classes[pred+1]
  68. print(sign)
  69. label.configure(foreground='#011638', text=sign)
  70. def show_classify_button(file_path):
  71. classify_b=Button(top,text="Classify Image",command=lambda: classify(file_path),padx=10,pady=5)
  72. classify_b.configure(background='#364156', foreground='white',font=('arial',10,'bold'))
  73. classify_b.place(relx=0.79,rely=0.46)
  74. def upload_image():
  75. try:
  76. file_path=filedialog.askopenfilename()
  77. uploaded=Image.open(file_path)
  78. uploaded.thumbnail(((top.winfo_width()/2.25),(top.winfo_height()/2.25)))
  79. im=ImageTk.PhotoImage(uploaded)
  80. sign_image.configure(image=im)
  81. sign_image.image=im
  82. label.configure(text='')
  83. show_classify_button(file_path)
  84. except:
  85. pass
  86. upload=Button(top,text="Upload an image",command=upload_image,padx=10,pady=5)
  87. upload.configure(background='#364156', foreground='white',font=('arial',10,'bold'))
  88. upload.pack(side=BOTTOM,pady=50)
  89. sign_image.pack(side=BOTTOM,expand=True)
  90. label.pack(side=BOTTOM,expand=True)
  91. heading = Label(top, text="Know Your Traffic Sign",pady=20, font=('arial',20,'bold'))
  92. heading.configure(background='#CDCDCD',foreground='#364156')
  93. heading.pack()
  94. top.mainloop()

Output:

graphical user interface for project in python

Summary

In this Python project with source code, we have successfully classified the traffic signs classifier with 95% accuracy and also visualized how our accuracy and loss changes with time, which is pretty good from a simple CNN model.


Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.73 seconds
10,820,440 unique visits