Moroccan Traffic Sign Detection
a school project about exploring the challenges and techniques in detecting and recognizing traffic signs in the unique road environments of Morocco. The aim of this project is to develop a Morocco-specific model utilizing convolutional neural networks (CNNs) for accurate traffic light detection.
exploring first dataset
1 / 5
Technology Stack...
- YOLO V8YOLOv8 is the latest iteration in the YOLO (You Only Look Once) series of real-time object detection models
- TensorFlowTensorFlow is a software library for machine learning and artificial intelligence. It is primarily used for training and inference of neural networks
- Annotation LabAnnotation Lab YOLO: A comprehensive annotation tool for YOLO (You Only Look Once) object detection models. It enables users to annotate images and generate segmentation masks using a YOLO object detection model
Resources...
- KaggelKaggle is an online community platform for data scientists and machine learning enthusiasts. Founded in 2010 by Anthony Goldbloom and Jeremy Howard,
Data Sources
collected Moroccan traffic sign detection
285
Traffic Sign Preprocessed
4180
Code Samples
Traffic sign detection sript
# -*- coding: utf-8 -*-
"""Copy of traffic_signs_detection1.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1727PZD_LY3hPDybzLfsd5n3rmoebMvGW
# CNN Keras
## Data importation
"""
! pip install -q kaggle
!pip install --upgrade --force-reinstall --no-deps kaggle
!mkdir -p ~/.kaggle
!cp kaggle.json ~/.kaggle/
!ls ~/.kaggle
!chmod 600 ~/.kaggle/kaggle.json
!kaggle competitions -h
!kaggle competitions download -c DATASET
from IPython.display import clear_output
clear_output(wait=True)
print("All Good")
!kaggle datasets download -d valentynsichkar/traffic-signs-preprocessed
from IPython.display import clear_output
# clear_output(wait=True)
print("DataSet Downloaded Seccessfully")
!ls
!mkdir trafficSigns
!unzip traffic-signs-preprocessed.zip -d trafficSigns
clear_output(wait=True)
print("file unziped seccessfully")
import pandas as pd
Data = pd.read_pickle("/content/trafficSigns/data0.pickle")
len(Data)
Data.keys()
X_train = Data["x_train"]
Y_train = Data["y_train"]
X_test = Data["x_test"]
Y_test = Data["y_test"]
X_validation = Data["x_validation"]
Y_validation = Data["y_validation"]
labels = Data["labels"]
import matplotlib.pyplot as plt
s = Data["x_train"][2].swapaxes(0,1)
s = s.swapaxes(1,2)
plt.imshow(s)
plt.show()
X_train.shape
X_train = X_train.swapaxes(1,2)
X_train = X_train.swapaxes(2,3)
X_test = X_test.swapaxes(1,2)
X_test = X_test.swapaxes(2,3)
X_validation = X_validation.swapaxes(1,2)
X_validation = X_validation.swapaxes(2,3)
from tabulate import tabulate
data = [["X_train", X_train.shape],
["X_test", X_test.shape],
["X_validation", X_validation.shape]
]
print(tabulate(data, headers=["Data Array", "Shape"], tablefmt="grid"))
len(labels)
plt.figure(figsize=(15,15))
for i in range(len(labels)):
plt.subplot(11,4,i+1)
plt.title(labels[Y_train[i]])
plt.imshow(X_train[i])
plt.axis("off")
plt.show()
from tensorflow.keras.utils import to_categorical
Y_train = to_categorical(Y_train,43)
Y_test = to_categorical(Y_test,43)
from keras.layers import Dense,Flatten,Conv2D,MaxPool2D
from keras import Sequential
from numpy import matrix
Model = Sequential(
[
Conv2D(64, kernel_size = 3, padding = "Same", activation = "relu", input_shape = (32,32,3)),
MaxPool2D(2),
Flatten(),
Dense(500, activation='relu'),
Dense(43,activation="softmax")
]
)
Model.compile(
optimizer = 'adamax',
loss = 'categorical_crossentropy',
metrics = ['accuracy']
)
Model.fit(X_train , Y_train , epochs=2)
Model.evaluate(X_test,Y_test)
Model.save('Traffic-Model1.h5')
Model.fit(X_train , Y_train , epochs=10)
Model.save('Traffic-Model2.h5')
Model.evaluate(X_test,Y_test)
predict = Model.predict(X_validation)
import numpy as np
pred = labels[np.argmax(predict[1])]
print(pred)
plt.imshow(X_validation[1]/255)
plt.show()
"""# YOLOv8
## Importing necessary libraries.
"""
from IPython.display import Image, display
from IPython import display
import os
import random
"""## Installing ultralytics"""
!pip install ultralytics
display.clear_output()
print("Installed successfully!")
"""## Importing YOLO and checking requirements"""
from ultralytics import YOLO
display.clear_output()
!yolo checks
"""## LOADING data from drive"""
!pip install gdown
import gdown
file_id = '1b0fct37QWyRHWpcw31zpeV_nd8KF20ux'
url = f'https://drive.google.com/uc?id={file_id}'
# Specify the destination file path
output = 'data.zip' # You can change the name if needed
# Download the file
gdown.download(url, output, quiet=False)
# Specify the path to the zip file
zip_file_path = '/content/data.zip'
# Specify the extraction path
extracted_path = '/content/'
# Unzip the file
!unzip {zip_file_path} -d {extracted_path}
"""## Distribution of annotations (classes)"""
Image(filename=f"/content/runs/detect/train/labels.jpg", width=1300)
Image(filename=f"/content/runs/detect/train2/train_batch0.jpg", width=1000)
"""## Start the training with yolo"""
!yolo task=detect mode=train model=yolov8m.pt data=/content/data/data.yaml epochs=40 imgsz=640
"""## Evolution of metrics during the training"""
Image(filename=f"/content/runs/detect/train/results.png", width=1000)
"""## Using the best weights generated from the training to check the validation"""
!yolo task=detect mode=val model=/content/runs/detect/train/weights/best.pt data=/content/data/data.yaml
!yolo task=detect mode=val model=/content/runs/detect/train/weights/last.pt data=/content/data/data.yaml
"""## Samples
### Real labels
"""
Image(filename=f"/content/runs/detect/val/val_batch2_labels.jpg", width=1400)
"""### predicted labels"""
Image(filename=f"/content/runs/detect/val/val_batch2_pred.jpg", width=1400)
"""## Prediction on the test sets"""
!yolo task=detect mode=predict model=/content/runs/detect/train/weights/best.pt conf=0.25 source=/content/data/test/images
!yolo task=detect mode=predict model=/content/runs/detect/train/weights/last.pt conf=0.25 source=/content/data/test/images
"""### samples of the predicted labels
### From best.pt
"""
from IPython.display import Image, display
import os
import random
# Path to the directory containing your images
directory_path = '/content/runs/detect/predict'
# Get a list of all image files in the directory
image_files = [f for f in os.listdir(directory_path) if f.endswith(('.jpg', '.jpeg', '.png', '.gif'))]
# Choose 10 random images
random_images = random.sample(image_files, 10)
# Display the selected images
for image_file in random_images:
image_path = os.path.join(directory_path, image_file)
display(Image(filename=image_path))
# Path to the directory containing your images
directory_path = '/content/runs/detect/predict'
# Get a list of all image files in the directory
image_files = [f for f in os.listdir(directory_path) if f.endswith(('.jpg', '.jpeg', '.png', '.gif'))]
# Choose 10 random images
random_images = random.sample(image_files, 10)
# Display the selected images
for image_file in random_images:
image_path = os.path.join(directory_path, image_file)
display(Image(filename=image_path))
"""### From last.pt"""
# Path to the directory containing your images
directory_path = '/content/runs/detect/predict3'
# Get a list of all image files in the directory
image_files = [f for f in os.listdir(directory_path) if f.endswith(('.jpg', '.jpeg', '.png', '.gif'))]
# Choose 10 random images
random_images = random.sample(image_files, 10)
# Display the selected images
for image_file in random_images:
image_path = os.path.join(directory_path, image_file)
display(Image(filename=image_path))
# Path to the directory containing your images
directory_path = '/content/runs/detect/predict3'
# Get a list of all image files in the directory
image_files = [f for f in os.listdir(directory_path) if f.endswith(('.jpg', '.jpeg', '.png', '.gif'))]
# Choose 10 random images
random_images = random.sample(image_files, 10)
# Display the selected images
for image_file in random_images:
image_path = os.path.join(directory_path, image_file)
display(Image(filename=image_path))
"""## Doing further training hoping for better results"""
!yolo task=detect mode=train model=/content/runs/detect/train/weights/last.pt data=/content/data/data.yaml epochs=20 imgsz=640
!yolo task=detect mode=val model=/content/runs/detect/train2/weights/best.pt data=/content/data/data.yaml
!yolo task=detect mode=val model=/content/runs/detect/train2/weights/last.pt data=/content/data/data.yaml