Traffic Signs Classification using Deep Learning & Flask

Updated: Sep 16, 2021

Hello readers, I am back with another Machine Learning project. In this project, we are going to learn about Traffic Signs Recognition. So let's see how we can do it using Python. So let's create a project from scratch.






So we need to first download the dataset.


Let's Start the code.

  • Create the working directory, extract the dataset into it.

  • Open Jupyter notebook ( I have used Anaconda 3.7)

  • Create a new python ipynb file.

Now import the necessary library.



import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cv2import tensorflow as tf
from PIL import Image
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
from keras.models import Sequential, load_model
from keras.layers import Conv2D, MaxPool2D, Dense, Flatten, Dropout
import os
os.chdir('D:/Traffic_Sign_Recognition')

We have more than 50K images for the 43 classes of traffic signs. Now we need to process all those images.



data =[]
labels = []
classes =43 
cur_path = os.getcwd()
for i inrange(classes):     
    path = os.path.join(cur_path,'train',str(i))     
    images = os.listdir(path)
    for a in images:
        try:             
            image = Image.open(path +'\\'+ a)             
            image = image.resize((30,30)) 
            # Resizing all images into 30*30                                                 
            image =np.array(image)             
            data.append(image)             
            labels.append(i)
        except Exceptionas e:
            print(e)

Now, we need to convert the image data list into NumPy array.


data = np.array(data) 
labels = np.array(labels)
print(data.shape, labels.shape) 
# (78418,30,30,3)(78418,)

Now we need to split the data into training and testing.

X_train, X_test, y_train, y_test =train_test_split(data, labels, test_size=0.2, random_state=0)
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape) 
# (62734,30,30,3)(15684,30,30,3)(62734,)(15684,)

Now convert labels into one hot encoding.

y_train = to_categorical(y_train,43) 
y_test = to_categorical(y_test,43)

Now, it's time to build the model.


model =Sequential() 
model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu', input_shape=X_train.shape[1:])) 
model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu')) model.add(MaxPool2D(pool_size=(2,2))) model.add(Dropout(rate=0.25)) model.add(Conv2D(filters=64, kernel_size=(3,3), activation='relu')) model.add(Conv2D(filters=64, kernel_size=(3,3), activation='relu')) 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))
# We have 43 classes that's why we have defined 43in the dense model.add(Dense(43, activation='softmax'))

Let's compile & train the model.

#Compilation of the model 
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) 
epochs = 20 
history = model.fit(X_train, y_train, batch_size=32, epochs=epochs, validation_data=(X_test, y_test))

The last epoch result is

Epoch 20/2062734/62734[==============================]-60s 949us/step - loss:0.2276- accuracy:0.9529- val_loss:0.0581- val_accuracy:0.98

Save the model

model.save("./training/TSR.h5")


We have done the most important part of Deep Learning, now we need to implement it in the flask app. Check out the full code & app files in my repository.




Now this is my App.py

from flask import *
import os
from werkzeug.utils import secure_filename
from keras.models import load_model
import numpy as np
from PIL import Image

app = Flask(__name__)

# Classes of trafic signs
classes = { 0:'Speed limit (20km/h)',
            1:'Speed limit (30km/h)',
            2:'Speed limit (50km/h)',
            3:'Speed limit (60km/h)',
            4:'Speed limit (70km/h)',
            5:'Speed limit (80km/h)',
            6:'End of speed limit (80km/h)',
            7:'Speed limit (100km/h)',
            8:'Speed limit (120km/h)',
            9:'No passing',
            10:'No passing veh over 3.5 tons',
            11:'Right-of-way at intersection',
            12:'Priority road',
            13:'Yield',
            14:'Stop',
            15:'No vehicles',
            16:'Vehicle > 3.5 tons prohibited',
            17:'No entry',
            18:'General caution',
            19:'Dangerous curve left',
            20:'Dangerous curve right',
            21:'Double curve',
            22:'Bumpy road',
            23:'Slippery road',
            24:'Road narrows on the right',
            25:'Road work',
            26:'Traffic signals',
            27:'Pedestrians',
            28:'Children crossing',
            29:'Bicycles crossing',
            30:'Beware of ice/snow',
            31:'Wild animals crossing',
            32:'End speed + passing limits',
            33:'Turn right ahead',
            34:'Turn left ahead',
            35:'Ahead only',
            36:'Go straight or right',
            37:'Go straight or left',
            38:'Keep right',
            39:'Keep left',
            40:'Roundabout mandatory',
            41:'End of no passing',
            42:'End no passing vehicle > 3.5 tons' }

def image_processing(img):
    model = load_model('./model/TSR.h5')
    data=[]
    image = Image.open(img)
    image = image.resize((30,30))
    data.append(np.array(image))
    X_test=np.array(data)
    Y_pred = model.predict_classes(X_test)
    return Y_pred

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/predict', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        # Get the file from post request
        f = request.files['file']
        file_path = secure_filename(f.filename)
        f.save(file_path)
        # Make prediction
        result = image_processing(file_path)
        s = [str(i) for i in result]
        a = int("".join(s))
        result = "Predicted Traffic🚦Sign is: " +classes[a]
        os.remove(file_path)
        return result
    return None

if __name__ == '__main__':
    app.run(debug=True)


Now run this code using python App.py It will give you the one localhost URL. For CSS, JS & HTML files visit my full project on GitHub.


Thanks for the reading to the last, I hope you all try this project by yourself.


Full Code:- GitHub



You can see the full tutorial on YouTube.


#machinelearning #trafficsignclassificaion#machinelearninghub#trafficsigns


Donation

Here we are just asking for the donations, if you want to donate us something then my UPI id and Paypal ID are mentioned below. We are creating quality content on youtube and making blogs for the same and publishing code openly. We are doing an open-source contribution.


UPI ID - kushalbhavsar58@ybl

Paypal - https://paypal.me/spidy1820

Wise - kushalbhavsar58@gmail.com


Note - We are just asking for donations.


Thanks & Regards

Machine Learning Hub

5,997 views0 comments