Guide to Car Detection using YOLO | by Bryan Tan | Towards Data Science

You are working on a self-driving car. As a critical component of this project, you’d like to first build a car detection system. To collect data, you’ve mounted a camera to the hood of the car, which takes pictures of the road ahead every few seconds while you drive around.
You’ve gathered all these images into a folder and have labelled them by drawing bounding boxes around every car you found. Here’s an example of what your bounding boxes look like:
If you have 80 classes that you want the object detector to recognize, you can represent the class label c either as an integer from 1 to 80, or as an 80-dimensional vector (with 80 numbers) — one component of which is 1 and the rest of which are 0. In this article, I will be using both representations, depending on which is more convenient for a particular step.
“You Only Look Once” (YOLO) is a popular algorithm because it achieves high accuracy whilst also being able to run in real-time. This algorithm “only looks once” at the image in the sense that it requires only one forward propagation pass through the network to make predictions. After non-max suppression, it then outputs recognized objects together with the bounding boxes.
The input is a batch of images, and each image has the shape (m, 608, 608, 3).
The output is a list of bounding boxes along with the recognized classes. Each bounding box is represented by 6 numbers — pc, bx, by, bh, bw, c — as explained above. If you expand c into an 80-dimensional vector, each bounding box is then represented by 85 numbers.
Anchor boxes are chosen by exploring the training data to choose reasonable height/width ratios that represent the different classes.
The dimension for anchor boxes is the second to last dimension in the encoding: m, nH, nW, anchors, classes.
The YOLO architecture is: IMAGE (m, 608, 608, 3) -> DEEP CNN -> ENCODING (m, 19, 19, 5, 85).
Let’s look in greater detail at what this encoding represents.
If the center/midpoint of an object falls into a grid cell, that grid cell is responsible for detecting that object.
Since we are using 5 anchor boxes, each of the 19 x 19 cells thus encodes information about 5 boxes. Anchor boxes are defined only by their width and height.
For simplicity, we will flatten the last two last dimensions of the shape (19, 19, 5, 85) encoding. So the output of the Deep CNN is (19, 19, 425).
Now, for each box (of each cell), we will compute the following element-wise product and extract a probability that the box contains a certain class.
The class score is score_ci = p_c * ci — the probability that there is an object p_c times the probability that the object is a certain class ci.
In Figure 4, let’s say for box 1 (cell 1), the probability that an object exists is p1 = 0.60. So there’s a 60% chance that an object exists in box 1 (cell 1).
The probability that the object is the class category 3 (a car) is c3 = 0.73.
The score for box 1 and for category 3 is score_c1,3 = 0.60 * 0.73 = 0.44.
Let’s say we calculate the score for all 80 classes in box 1 and find that the score for the car class (class 3) is the maximum. So we’ll assign the score 0.44 and class 3 to this box 1.
Here’s one way to visualize what YOLO is predicting on an image:
For each of the 19 x 19 grid cells, find the maximum of the probability scores, that is, taking a max across the 80 classes, one maximum for each of the 5 anchor boxes).
Colour that grid cell according to what object that grid cell considers the most likely.
Doing this results in this picture:
Note that this visualization isn’t a core part of the YOLO algorithm itself for making predictions; it’s just a nice way of visualizing an intermediate result of the algorithm.
Another way to visualize YOLO’s output is to plot the bounding boxes that it outputs. Doing that results in a visualization like this:
In the figure above, we plotted only boxes for which the model had assigned a high probability, but this is still too many boxes. We’d like to reduce the algorithm’s output to a much smaller number of detected objects.
To do so, we’ll use non-max suppression. Specifically, we’ll carry out these steps:
Get rid of boxes with a low score. Meaning, the box is not very confident about detecting a class; either due to the low probability of any object, or low probability of this particular class.
Select only one box when several boxes overlap with each other and detect the same object.
We are going to first apply a filter by thresholding. We would like to get rid of any box for which the class “score” is less than a chosen threshold.
The model gives us a total of 19 x 19 x 5 x 85 numbers, with each box described by 85 numbers. It is convenient to rearrange the (19, 19, 5, 85), or (19, 19, 425) dimensional tensor into the following variables:
box_confidence: tensor of shape (19×19, 5, 1)(19×19, 5, 1) containing p_c — confidence probability that there’s some object — for each of the 5 boxes predicted in each of the 19x19 cells.
boxes: tensor of shape (19×19, 5, 4) containing the midpoint and dimensions (bx, by , bh, bw) for each of the 5 boxes in each cell.
box_class_probs: tensor of shape (19×19, 5, 80) containing the "class probabilities" (c1, c2,...,c80) for each of the 80 classes for each of the 5 boxes per cell.
Implementing yolo_filter_boxes()
Compute box scores by doing the element-wise product(p * c) as described in Figure 4.For each box, find the index of the class with the maximum box score, and the corresponding box score.Create a mask by using a threshold. As a heads-up: ([0.9, 0.3, 0.4, 0.5, 0.1] < 0.4) returns: [False, True, False, False, True]. The mask should be True for the boxes you want to keep.Use TensorFlow to apply the mask to box_class_scores, boxes and box_classes to filter out the boxes we don't want. You should be left with just the subset of boxes you want to keep.
Compute box scores by doing the element-wise product(p * c) as described in Figure 4.
For each box, find the index of the class with the maximum box score, and the corresponding box score.
Create a mask by using a threshold. As a heads-up: ([0.9, 0.3, 0.4, 0.5, 0.1] < 0.4) returns: [False, True, False, False, True]. The mask should be True for the boxes you want to keep.
Use TensorFlow to apply the mask to box_class_scores, boxes and box_classes to filter out the boxes we don't want. You should be left with just the subset of boxes you want to keep.
Useful references
Keras argmax
Keras max
boolean mask
Even after filtering by thresholding over the class scores, we might still end up with a lot of overlapping boxes. A second filter for selecting the right boxes is called non-maximum suppression (NMS).
Non-max suppression uses the very crucial function called Intersection over Union, or IoU.
Implementing iou()
In this code, I’ll be using the convention that (0, 0) is the top-left corner of an image; (1, 0) is the upper-right corner; (1, 1) is the lower-right corner. In other words, the (0, 0) origin starts at the top left corner of the image. As x increases, we move to the right. As y increases, we move downwards.
I’ll define a box using its two corners: upper left (x1, y1) and lower right (x2, y2) instead of using the midpoint, height and width. This makes it a bit easier to calculate the intersection.
To calculate the area of a rectangle, multiply its height (y2 − y1) by its width (x2 − x1). Since (x1, y1) is the top left and (x2, y2) is the bottom right, these differences should be non-negative.
Feel free to draw some examples on paper to clarify this conceptually. To find the intersection of the two boxes (xi1, yi1, xi2, yi2):
The top left corner of the intersection (xi1, yi1) is found by comparing the top left corners (x1, y1) of the two boxes, then finding a vertex that has an x-coordinate that is closer to the right, and y-coordinate that is closer to the bottom.
The bottom right corner of the intersection ( xi2, yi2) is found by comparing the bottom right corners (x2, y2) of the two boxes, then finding a vertex whose x-coordinate is closer to the left, and the y-coordinate that is closer to the top.
The two boxes may have no intersection. We can detect this if the intersection coordinates we calculated end up being the top right and/or bottom left corners of an intersection box. Another way to think of this is if you calculated the height (y2 − y1) or width (x2 − x1) and find that at least one of these lengths is negative, then there is no intersection (intersection area is zero).
The two boxes may intersect at the edges or vertices, in which case the intersection area is still zero. This happens when either the height or width (or both) of the calculated intersection is zero.
We are now ready to implement non-max suppression. The key steps are:
Select the box that has the highest score.Compute the overlap of this box with all other boxes, and remove boxes that overlap significantly (iou >= iou_threshold).Go back to step 1 and iterate until there are no more boxes with a lower score than the currently selected box.
Select the box that has the highest score.
Compute the overlap of this box with all other boxes, and remove boxes that overlap significantly (iou >= iou_threshold).
Go back to step 1 and iterate until there are no more boxes with a lower score than the currently selected box.
This will remove all boxes that have a large overlap with the selected boxes. Only the “best” boxes remain.
Implementing yolo_non_max_suppression()
Reference documentation
tf.image.non_max_suppression()
It’s time to implement a function taking the output of the deep CNN (the 19 x 19 x 5 x 85 dimensional encoding) and filtering through all the boxes using the functions we’ve just implemented.
Implementing yolo_eval()
This function takes the output of the YOLO encoding and filters the boxes using score threshold and NMS.
There’s one implementations detail you need to know. There are a few ways of representing boxes, such as via their corners or via their midpoint and height/width. YOLO converts between a few such formats at different times, using the following functions:
boxes = yolo_boxes_to_corners(box_xy, box_wh)
which converts the YOLO box coordinates (x, y, w, h) to box corners’ coordinates (x1, y1, x2, y2) to fit the input of yolo_filter_boxes .
boxes = scale_boxes(boxes, image_shape)
YOLO’s network was trained to run on 608 x 608 images. If you are testing this data on a different size image — for example, a car detection dataset with 720 x 1280 images — this step rescales the boxes so that they can be plotted on top of the original 720 x 1280 image.
Input image (608, 608, 3)
The input image goes through a CNN, resulting in a (19, 19, 5, 85) dimensional output.
After flattening the last two dimensions, the output is a volume of shape (19, 19, 425). Each cell in a 19 x 19 grid over the input image gives 425 numbers: 425 = 5 x 85 because each cell contains predictions for 5 boxes, corresponding to 5 anchor boxes; 85 = 5 + 80 where 5 is because (pc, bx, by, bh, bw) has 5 numbers, and 80 is the number of classes we’d like to detect.
We then select only a few boxes based on score-thresholding — discarding boxes that have detected a class with a score less than the threshold, and non-max suppression — computing the Intersection over Union (IOU) and avoiding selecting overlapping boxes.
This gives you YOLO’s final output.
In this part, we are going to use a pre-trained model and test it on the car detection dataset. We’ll need a session to execute the computation graph and evaluate the tensors:
sess = K.get_session()
Recall that we were trying to detect 80 classes, and are using 5 anchor boxes. We will read the names and anchors of the 80 classes and 5 boxes that are stored in two files — coco_classes.txt and yolo_anchors.txt (more info in Github repo). The car detection dataset has 720 x 1280 images, which are pre-processed into 608 x 608 images.
Training a YOLO model takes a very long time and requires a fairly large dataset of labelled bounding boxes for a large range of target classes. So we are instead going to load an existing pre-trained Keras YOLO model. (more info in Github repo). These weights come from the official YOLO website and were converted using a function written by Allan Zelener. References are at the end of this article. Technically, these are the parameters from the YOLOv2 model, but we will simply refer to it as YOLO in this article.
yolo_model = load_model(“model_data/yolo.h5”)
This loads the weights of a trained YOLO model. You can take a look at the summary of the layers the model contains in the notebook in the Github repo.
Reminder: this model converts a preprocessed batch of input images (shape: (m, 608, 608, 3)) into a tensor of shape (m, 19, 19, 5, 85) as explained in Figure 2.
The output of yolo_model is a (m, 19, 19, 5, 85) tensor that needs to pass through non-trivial processing and conversion. The following code does that for us:
yolo_outputs = yolo_head(yolo_model.output, anchors, len(class_names))
If you are curious about how yolo_head is implemented, you can find the function definition in the file 'keras_yolo.py' in the Github repo.
After adding yolo_outputs to our graph. This set of 4 tensors is ready to be used as input by the yolo_eval function.
yolo_outputs gave us all the predicted boxes of yolo_model in the correct format. We’re now ready to perform filtering and selecting only the best boxes by calling yolo_eval, which we had previously implemented, to do this.
scores, boxes, classes = yolo_eval(yolo_outputs, image_shape)
Let the fun begin. We have created a graph that can be summarized as follows:
yolo_model.input is given to yolo_model. The model is used to compute the output yolo_model.output.yolo_model.output is processed by yolo_head. It gives you yolo_outputs.yolo_outputs goes through a filtering function, yolo_eval. It outputs your predictions: scores, boxes, classes.
yolo_model.input is given to yolo_model. The model is used to compute the output yolo_model.output.
yolo_model.output is processed by yolo_head. It gives you yolo_outputs.
yolo_outputs goes through a filtering function, yolo_eval. It outputs your predictions: scores, boxes, classes.
Implementing predict()
predict()runs the graph to test YOLO on an image. You will need to run a TensorFlow session, to have it compute scores, boxes, classes.
The code below also uses the following function:
image, image_data = preprocess_image("images/" + image_file, model_image_size = (608, 608))
which outputs:
image: a python (PIL) representation of your image used for drawing boxes. You won’t need to use it.
image_data: a numpy-array representing the image. This will be the input to the CNN.
Testing the function on a test image:
out_scores, out_boxes, out_classes = predict(sess, “test.jpg”)
The model we’ve just run is actually able to detect 80 different classes listed in coco_classes.txt. Feel free to try with on with your own images by downloading the files in the Github repo.
If we were to run the session in a for loop over all the images. Here’s what we would get:
YOLO is a state-of-the-art object detection model that is fast and accurate.
It runs an input image through a CNN which outputs a 19 x 19 x 5 x 85 dimensional volume.
The encoding can be seen as a grid where each of the 19 x 19 cells contains information about 5 boxes.
Filter through all the boxes using non-max suppression. Specifically, use score thresholding on the probability of detecting a class to keep only accurate (high probability) boxes, and Intersection over Union (IoU) thresholding to eliminate overlapping boxes.
Because training a YOLO model from randomly initialized weights is non-trivial and requires a large dataset as well as a lot of computation, we used previously trained model parameters in this exercise. If you wish, you can also try fine-tuning the YOLO model with your own dataset, though this would be a fairly non-trivial exercise.
Special thanks to deeplearning.ai.
All figures by courtesy of deeplearning.ai.
The ideas presented in this article came primarily from the two YOLO papers. The implementation here also took significant inspiration and used many components from Allan Zelener’s GitHub repository. The pre-trained weights used in this exercise came from the official YOLO website.
Joseph Redmon, Santosh Divvala, Ross Girshick, Ali Farhadi — You Only Look Once: Unified, Real-Time Object Detection (2015)
Joseph Redmon, Ali Farhadi — YOLO9000: Better, Faster, Stronger (2016)
Allan Zelener — YAD2K: Yet Another Darknet 2 Keras
The official YOLO website (https://pjreddie.com/darknet/yolo/)
Car detection dataset: The Drive.ai Sample Dataset (provided by drive.ai) is licensed under a Creative Commons Attribution 4.0 International License.
Github repo: https://github.com/TheClub4/car-detection-yolov2