Skip to main content

Road & Safety Signs Detection

 

 Traffic Signs Recognition

Download your files from here: 


Here I've done project using pickle files that you can easily download from above link

Kindly read and follow the below these comments for understanding the codes

For better convenient use visual code. It's free and intelligent IDLE


# %% Importing libraries

import pickle
import numpy as np
import matplotlib.pyplot as plt


# %%  Extracting train data

train_file = 'train.p'
train_obj = open(train_file, 'rb')
train_data = pickle.load(train_obj)
print(train_data)

# %%  Extracting test data

test_file = 'test.p'
test_obj = open(test_file, 'rb')
test_data = pickle.load(test_obj)
print(test_data)

# %%  Extracting valid data

valid_file = 'valid.p'
valid_obj = open(valid_file, 'rb')
valid_data = pickle.load(valid_obj)
print(valid_data)

# %%  Keys
train_data.keys()
output: dict_keys(['coords', 'labels', 'features', 'sizes'])

# %%  Extracting training feature and training labels

train_features = train_data['features']
train_labels = train_data['labels']

# %%  Extracting testing feature and testing labels

test_features = test_data['features']
test_labels = test_data['labels']

# %%  Extracting valid feature and testing labels

valid_features = valid_data['features']
valid_labels = valid_data['labels']


#%%  Verify the data

plt.figure(figsize=(20,20))
for i in range(50):
    plt.subplot(10,10,i+1)
    plt.grid(False)
    plt.axis('off')
    plt.imshow(test_features[i])  # cmap=plt.get_cmap('gray')
    plt.xlabel(class_names[i])
    plt.show()



# %%  Converting into float 

x_train = train_features.astype('float32')
x_test = test_features.astype('float32')
x_valid = valid_features.astype('float32')

# %%  Normalizing 0 to 1
# here 255 because color range lies between 0 - 255
x_train /= 255.0
x_test /= 255.0
x_valid /= 255.0 

# %% Convert class metrix to binary metrix 

y_train = train_labels
y_test = test_labels
y_valid = valid_labels

# %%   Import TensorFlow

import keras
from keras.models import Model
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Dense, Input ,Dropout, Flatten
from keras.utils import to_categorical
from keras.preprocessing import image

# %%   Create the convolutional base

input_x = Input(shape=(32,32,3))
layer_1 = Conv2D(32, kernel_size=(3,3), activation='relu') (input_x)
layer_2 = MaxPooling2D((22))(layer_1)
layer_3 = Dropout(0.5) (layer_2) # To prevent overfitting
layer_4 = Flatten() (layer_3)
layer_5 = Dense(150, activation='relu') (layer_4)
layer_6 = Dense(80, activation='relu') (layer_5)
layer_7 = Dense(43, activation='softmax') (layer_6)


# %%  Displaying the architecture of model

model = Model(input_x, layer_8)
model.summary()


# %%  Compile and train the model

Epochs=10
BatchSize=200


process = model.fit(
    x_train,
    y_train, 
    epochs= Epochs,
    batch_size= BatchSize,
    validation_data= (x_valid, y_valid ),
    # steps_per_epoch= len(x_train)//BatchSize,
    # validation_data=(valid_test, y_test )
    shuffle=True
    )


# %%  Loss Visualization


plt.style.use('ggplot')
plt.figure(1)
plt.plot(process.history['loss'],label='training loss')
plt.plot(process.history['val_loss'],label='testing loss')
plt.title('Loss')
plt.xlabel('Epochs')
plt.legend(loc='upper right')

plt.savefig('../Loss.png')





# %%  Accuracy Visualization

plt.style.use('ggplot')
plt.figure(2)
plt.plot(process.history['accuracy'], label='training accuracy')
plt.plot(process.history['val_accuracy'], label='testing accuracy')
plt.title('Accuracy')
plt.xlabel('Epochs')
plt.legend(loc='lower right')

plt.savefig('../Accuracy.png')




# %%  Evaluate the score 

score = model.evaluate(x_test, y_test, verbose=0)

print('loss=', score[0])
print('accuracy=',score[1])

# %% labels name

label_names = {
    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 for vehicles over 3.5 metric tons',
    11 : 'Right-of-way at the next intersection',
    12 : 'Priority road',
    13 : 'Yield' ,
    14 : 'Stop' ,
    15 : 'No vehicles',
    16 : 'Vehicles over 3.5 metric tons prohibited' ,
    17 : 'No entry',
    18 : 'General caution' ,
    19 : 'Dangerous curve to the left',
    20 : 'Dangerous curve to the right' ,
    21 : 'Double curve',
    22 : 'dumpy road' ,
    23 : 'Slippery road',
    24 : 'Road narrows on the right' ,
    25 : 'Road work',
    26 : 'Traffic signals' ,
    27 : 'Pedestrians' ,
    28 : 'Children crossing',
    29 : 'cycles crossing' ,
    30 : 'aware of ice/snow',
    31 : 'Wild animals crossing',
    32 : 'End of all speed and 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 of no passing y vehicles over 3.5 metric tons'
}

labels =label_names.values()
val = list(labels)


# %%  single value prediction

number = 5

prediction = model.predict(x_valid)
warning = np.argmax(np.round(prediction[number]))
print(val[warning])

plt.axis('off')
plt.imshow(x_valid[number], cmap = plt.cm.binary)
plt.show()

Also You can deploy your successful model making real life application by
saving your model.

# %%  Save the model to the disk

model.save('../traffic_sign_recognitor.model')


Create a new file and use OpenCV for making camera application
you can simple copy this code

# %%  Import libraries

from keras.preprocessing import image
from keras.models import load_model

import numpy as np
import cv2 as cv

# %%  Load model

model = load_model('traffic_sign_recognitor.model')

# %%   Camera resolution

frame_width = 900
frame_height = 600
font = cv.FONT_HERSHEY_PLAIN

# %%  Webcam

webcam = cv.VideoCapture(0) # here 0 will take the default (laptop) camera
webcam.set(3, frame_width)
webcam.set(4, frame_height)

# %% labels name

label_names = {
    0 : 'Speed limit 20 km/h'
    1 : 'Speed limit 30 km/h',
    2 : 'Speed limit 50 km/h',
    3 : 'Speed limit 60 km/h',
    4 : 'Speed limit 70 km/h' , 
    5 : 'Speed limit 80 km/h',
    6 : 'End of speed limit 80 km/h' ,
    7 : 'Speed limit 100 km/h' , 
    8 : 'Speed limit 120 km/h' , 
    9 : 'No passing',
    10 : 'No passing for vehicles over 3.5 metric tons',
    11 : 'Right-of-way at the next intersection',
    12 : 'Priority road',
    13 : 'Yield' ,
    14 : 'Stop' ,
    15 : 'No vehicles',
    16 : 'Vehicles over 3.5 metric tons prohibited' ,
    17 : 'No entry',
    18 : 'General caution' ,
    19 : 'Dangerous curve to the left',
    20 : 'Dangerous curve to the right' ,
    21 : 'Double curve',
    22 : 'dumpy road' ,
    23 : 'Slippery road',
    24 : 'Road narrows on the right' ,
    25 : 'Road work',
    26 : 'Traffic signals' ,
    27 : 'Pedestrians' ,
    28 : 'Children crossing',
    29 : 'cycles crossing' ,
    30 : 'aware of ice/snow',
    31 : 'Wild animals crossing',
    32 : 'End of all speed and 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 of no passing y vehicles over 3.5 metric tons'
}

labels = list(label_names.values())


# %%   Preprocessing function

def preprocessing(img):
    img = image.img_to_array(img)
    img = img.astype(np.float32)/255.0  
    img = np.expand_dims(img, axis=0)
    return img

# %%  loop through the frames

while webcam.isOpened():

    # read frames through the webcam
    status, frame = webcam.read()

    # process image ; detect object region 
    img = cv.resize(frame, (32,32))
    img = preprocessing(img)

    # predict the image
    pred = model.predict(img)

    # get the model with max accuracy
    index = np.argmax(pred)
    label = labels[index]

    # write label above the object
    cv.putText(frame, 'CLASS: ', (20,35), font, 1.6, (255,10,0), 2)
    cv.putText(frame, label, (120,35), font, 1.6, (10,100,150), 2)
    cv.imshow('Traffic Sign Recognition', frame)


    if cv.waitKey(1) & 0xff == ord('q'):
        break

# release resources
webcam.release()
cv.destroyAllWindows()


Then you have to put your image in front of your computer camera
And your application will take decision like this







Comments

Popular posts from this blog

Gradient Descent with RSME

Optimization Alorithms Ex : G.D. , S.D. ,  Adam, RMS prop , momentum , adelta Gradient Descent is an  optimization algorithm that find a best fit line and local minima of a differentiable function for given training data set. S imply used to find the coefficients (weights) and intercept (bias) that minimize a cost function as far as possible.  There are three types of  g radient descent techniques:   Regular Batch GD (Gradient Descent) -  Studiously descend the curve in one path towards one minima ; every hop calculates the cost function for entire training data. If training data is large, one should not use this. Random GD (Stochastic GD) -   Calculates the Cost function for only one (randomly selected) training data per hop ; tend to jump all over the place due to randomness but due to it actually jump across minima’s.  Mini Batch gradient descent - Somewhere midway between the above 2. Does the calculation for a bunch of random data poin...

Why python ? What is Python?

Python is a generally interpreted and  interactive dynamic symmetric   high-level  object oriented programming language. It is widely used in Machine Learning today. Pretty easy to understand, learn, code and explain because it has very crisp and clear syntaxes than other languages.  Guido van Rossum made Python in 1991, named his programming language after the television show Monty Python's Flying Circus. Python has got features or derived features from ABC named programming language. Interactive - The result will be printed on the screen, immediately return, in the next line as we entered. High-level - Humans can easy to interpret; the source code contains easy-to-read syntax that is later converted into a low-level language (0 , 1) Dynamic-symmetric – Don’t need to clarify the data type. It Allows the type casting. Type Casting –  We can transform the one data type in another data type Object Oriented – language is focused on Object...