Recognition of traffic signs

CNN with Keras

Let's build and train a CNN to recognise traffic signs. First, we import the required dependecies.

In [ ]:
import os
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from keras.utils.np_utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense, Flatten, Dropout
from keras.layers import Conv2D, MaxPooling2D
import skimage.transform
import random

We will be using the Belgian Traffic Sign Dataset. You have to download the two .zip files in BelgiumTS for Classification (cropped images). The images in the dataset are in a .ppm format. We convert this into a form usable for analysis using the library skimage with the following function:

In [4]:
def load_data(data_dir):
    # Get all subdirectories of data_dir. Each represents a label.
    directories = [d for d in os.listdir(data_dir)
                  if os.path.isdir(os.path.join(data_dir, d))]
    # Loop through the label directories and collect the data in
    # two lists, labels and images.
    labels = []
    images = []
    for d in directories:
        label_dir = os.path.join(data_dir, d)
        file_names = [os.path.join(label_dir, f)
                      for f in os.listdir(label_dir) if f.endswith(".ppm")]
        for f in file_names:
    return images, labels
In [5]:
train_data_dir = "Training/"
images, labels = load_data(train_data_dir)

The images are organized in folders, which name corresponds to the label. Each folder contains several examples of the same traffic sign.

In [6]:
def display_images_and_labels(images, labels):
    # Display the first image of each label.
    unique_labels = set(labels)
    plt.figure(figsize=(15, 15))
    i = 1
    for label in unique_labels:
        # Pick the first image for each label.
        image = images[labels.index(label)]
        plt.subplot(8, 8, i)  # A grid of 8 rows x 8 columns
        plt.title("Label {0} ({1})".format(label, labels.count(label)))
        i += 1
        _ = plt.imshow(image)
In [7]:
display_images_and_labels(images, labels)