{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Autonomous Driving - Car Detection\n", "\n", "Welcome to the Week 3 programming assignment! In this notebook, you'll implement object detection using the very powerful YOLO model. Many of the ideas in this notebook are described in the two YOLO papers: [Redmon et al., 2016](https://arxiv.org/abs/1506.02640) and [Redmon and Farhadi, 2016](https://arxiv.org/abs/1612.08242). \n", "\n", "**By the end of this assignment, you'll be able to**:\n", "\n", "- Detect objects in a car detection dataset\n", "- Implement non-max suppression to increase accuracy\n", "- Implement intersection over union\n", "- Handle bounding boxes, a type of image annotation popular in deep learning " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Table of Contents\n", "\n", "- [Packages](#0)\n", "- [1 - Problem Statement](#1)\n", "- [2 - YOLO](#2)\n", " - [2.1 - Model Details](#2-1)\n", " - [2.2 - Filtering with a Threshold on Class Scores](#2-2)\n", " - [Exercise 1 - yolo_filter_boxes](#ex-1)\n", " - [2.3 - Non-max Suppression](#2-3)\n", " - [Exercise 2 - iou](#ex-2)\n", " - [2.4 - YOLO Non-max Suppression](#2-4)\n", " - [Exercise 3 - yolo_non_max_suppression](#ex-3)\n", " - [2.5 - Wrapping Up the Filtering](#2-5)\n", " - [Exercise 4 - yolo_eval](#ex-4)\n", "- [3 - Test YOLO Pre-trained Model on Images](#3)\n", " - [3.1 - Defining Classes, Anchors and Image Shape](#3-1)\n", " - [3.2 - Loading a Pre-trained Model](#3-2)\n", " - [3.3 - Convert Output of the Model to Usable Bounding Box Tensors](#3-3)\n", " - [3.4 - Filtering Boxes](#3-4)\n", " - [3.5 - Run the YOLO on an Image](#3-5)\n", "- [4 - Summary for YOLO](#4)\n", "- [5 - References](#5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## Packages\n", "\n", "Run the following cell to load the packages and dependencies that will come in handy as you build the object detector!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import argparse\n", "import os\n", "import matplotlib.pyplot as plt\n", "from matplotlib.pyplot import imshow\n", "import scipy.io\n", "import scipy.misc\n", "import numpy as np\n", "import pandas as pd\n", "import PIL\n", "from PIL import ImageFont, ImageDraw, Image\n", "import tensorflow as tf\n", "from tensorflow.python.framework.ops import EagerTensor\n", "\n", "from tensorflow.keras.models import load_model\n", "from yad2k.models.keras_yolo import yolo_head\n", "from yad2k.utils.utils import draw_boxes, get_colors_for_classes, scale_boxes, read_classes, read_anchors, preprocess_image\n", "\n", "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 1 - Problem Statement\n", "\n", "You are working on a self-driving car. Go you! 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 (meaning the front) of the car, which takes pictures of the road ahead every few seconds as you drive around. \n", "\n", "
\n", "\n", "
\n", "\n", "
Pictures taken from a car-mounted camera while driving around Silicon Valley.
Dataset provided by drive.ai.\n", "
\n", "\n", "You've gathered all these images into a folder and labelled them by drawing bounding boxes around every car you found. Here's an example of what your bounding boxes look like:\n", "\n", "\n", "
Figure 1: Definition of a box
\n", "\n", "If there are 80 classes 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. The video lectures used the latter representation; in this notebook, you'll use both representations, depending on which is more convenient for a particular step. \n", "\n", "In this exercise, you'll discover how YOLO (\"You Only Look Once\") performs object detection, and then apply it to car detection. Because the YOLO model is very computationally expensive to train, the pre-trained weights are already loaded for you to use. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 2 - YOLO" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\"You Only Look Once\" (YOLO) is a popular algorithm because it achieves high accuracy while 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.\n", "\n", "\n", "### 2.1 - Model Details\n", "\n", "#### Inputs and outputs\n", "- The **input** is a batch of images, and each image has the shape (m, 608, 608, 3)\n", "- The **output** is a list of bounding boxes along with the recognized classes. Each bounding box is represented by 6 numbers $(p_c, b_x, b_y, b_h, b_w, c)$ as explained above. If you expand $c$ into an 80-dimensional vector, each bounding box is then represented by 85 numbers. \n", "\n", "#### Anchor Boxes\n", "* Anchor boxes are chosen by exploring the training data to choose reasonable height/width ratios that represent the different classes. For this assignment, 5 anchor boxes were chosen for you (to cover the 80 classes), and stored in the file './model_data/yolo_anchors.txt'\n", "* The dimension for anchor boxes is the second to last dimension in the encoding: $(m, n_H,n_W,anchors,classes)$.\n", "* The YOLO architecture is: IMAGE (m, 608, 608, 3) -> DEEP CNN -> ENCODING (m, 19, 19, 5, 85). \n", "\n", "\n", "#### Encoding\n", "Let's look in greater detail at what this encoding represents. \n", "\n", "\n", "
Figure 2 : Encoding architecture for YOLO
\n", "\n", "If the center/midpoint of an object falls into a grid cell, that grid cell is responsible for detecting that object." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since you're using 5 anchor boxes, each of the 19 x19 cells thus encodes information about 5 boxes. Anchor boxes are defined only by their width and height.\n", "\n", "For simplicity, you'll flatten the last two dimensions of the shape (19, 19, 5, 85) encoding, so the output of the Deep CNN is (19, 19, 425).\n", "\n", "\n", "
Figure 3 : Flattening the last two last dimensions
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Class score\n", "\n", "Now, for each box (of each cell) you'll compute the following element-wise product and extract a probability that the box contains a certain class. \n", "The class score is $score_{c,i} = p_{c} \\times c_{i}$: the probability that there is an object $p_{c}$ times the probability that the object is a certain class $c_{i}$.\n", "\n", "\n", "
Figure 4: Find the class detected by each box
\n", "\n", "##### Example of figure 4\n", "* In figure 4, let's say for box 1 (cell 1), the probability that an object exists is $p_{1}=0.60$. So there's a 60% chance that an object exists in box 1 (cell 1). \n", "* The probability that the object is the class \"category 3 (a car)\" is $c_{3}=0.73$. \n", "* The score for box 1 and for category \"3\" is $score_{1,3}=0.60 \\times 0.73 = 0.44$. \n", "* Let's say you 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 you'll assign the score 0.44 and class \"3\" to this box \"1\".\n", "\n", "#### Visualizing classes\n", "Here's one way to visualize what YOLO is predicting on an image:\n", "\n", "- For each of the 19x19 grid cells, find the maximum of the probability scores (taking a max across the 80 classes, one maximum for each of the 5 anchor boxes).\n", "- Color that grid cell according to what object that grid cell considers the most likely.\n", "\n", "Doing this results in this picture: \n", "\n", "\n", "
Figure 5: Each one of the 19x19 grid cells is colored according to which class has the largest predicted probability in that cell.
\n", "\n", "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. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Visualizing bounding boxes\n", "Another way to visualize YOLO's output is to plot the bounding boxes that it outputs. Doing that results in a visualization like this: \n", "\n", "\n", "
Figure 6: Each cell gives you 5 boxes. In total, the model predicts: 19x19x5 = 1805 boxes just by looking once at the image (one forward pass through the network)! Different colors denote different classes.
\n", "\n", "#### Non-Max suppression\n", "In the figure above, the only boxes plotted are ones for which the model had assigned a high probability, but this is still too many boxes. You'd like to reduce the algorithm's output to a much smaller number of detected objects. \n", "\n", "To do so, you'll use **non-max suppression**. Specifically, you'll carry out these steps: \n", "- 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.\n", "- Select only one box when several boxes overlap with each other and detect the same object." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### 2.2 - Filtering with a Threshold on Class Scores\n", "\n", "You're going to first apply a filter by thresholding, meaning you'll get rid of any box for which the class \"score\" is less than a chosen threshold. \n", "\n", "The model gives you a total of 19x19x5x85 numbers, with each box described by 85 numbers. It's convenient to rearrange the (19,19,5,85) (or (19,19,425)) dimensional tensor into the following variables: \n", "- `box_confidence`: tensor of shape $(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.\n", "- `boxes`: tensor of shape $(19, 19, 5, 4)$ containing the midpoint and dimensions $(b_x, b_y, b_h, b_w)$ for each of the 5 boxes in each cell.\n", "- `box_class_probs`: tensor of shape $(19, 19, 5, 80)$ containing the \"class probabilities\" $(c_1, c_2, ... c_{80})$ for each of the 80 classes for each of the 5 boxes per cell.\n", "\n", "\n", "### Exercise 1 - yolo_filter_boxes\n", "\n", "Implement `yolo_filter_boxes()`.\n", "1. Compute box scores by doing the elementwise product as described in Figure 4 ($p \\times c$). \n", "The following code may help you choose the right operator: \n", "```python\n", "a = np.random.randn(19, 19, 5, 1)\n", "b = np.random.randn(19, 19, 5, 80)\n", "c = a * b # shape of c will be (19, 19, 5, 80)\n", "```\n", "This is an example of **broadcasting** (multiplying vectors of different sizes).\n", "\n", "2. For each box, find:\n", " - the index of the class with the maximum box score\n", " - the corresponding box score\n", " \n", " **Useful References**\n", " * [tf.math.argmax](https://www.tensorflow.org/api_docs/python/tf/math/argmax)\n", " * [tf.math.reduce_max](https://www.tensorflow.org/api_docs/python/tf/math/reduce_max)\n", "\n", " **Helpful Hints**\n", " * For the `axis` parameter of `argmax` and `reduce_max`, if you want to select the **last** axis, one way to do so is to set `axis=-1`. This is similar to Python array indexing, where you can select the last position of an array using `arrayname[-1]`.\n", " * Applying `reduce_max` normally collapses the axis for which the maximum is applied. `keepdims=False` is the default option, and allows that dimension to be removed. You don't need to keep the last dimension after applying the maximum here.\n", "\n", "\n", "3. Create a mask by using a threshold. As a reminder: `([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. \n", "\n", "4. Use TensorFlow to apply the mask to `box_class_scores`, `boxes` and `box_classes` to filter out the boxes you don't want. You should be left with just the subset of boxes you want to keep. \n", "\n", " **One more useful reference**:\n", " * [tf.boolean mask](https://www.tensorflow.org/api_docs/python/tf/boolean_mask) \n", "\n", " **And one more helpful hint**: :) \n", " * For the `tf.boolean_mask`, you can keep the default `axis=None`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "nbgrader": { "cell_type": "code", "checksum": "08f29f6200340f3ea6223aece625671b", "grade": false, "grade_id": "cell-125a819999f836d1", "locked": false, "schema_version": 3, "solution": true, "task": false } }, "outputs": [], "source": [ "# GRADED FUNCTION: yolo_filter_boxes\n", "\n", "def yolo_filter_boxes(boxes, box_confidence, box_class_probs, threshold = 0.6):\n", " \"\"\"Filters YOLO boxes by thresholding on object and class confidence.\n", " \n", " Arguments:\n", " boxes -- tensor of shape (19, 19, 5, 4)\n", " box_confidence -- tensor of shape (19, 19, 5, 1)\n", " box_class_probs -- tensor of shape (19, 19, 5, 80)\n", " threshold -- real value, if [ highest class probability score < threshold],\n", " then get rid of the corresponding box\n", "\n", " Returns:\n", " scores -- tensor of shape (None,), containing the class probability score for selected boxes\n", " boxes -- tensor of shape (None, 4), containing (b_x, b_y, b_h, b_w) coordinates of selected boxes\n", " classes -- tensor of shape (None,), containing the index of the class detected by the selected boxes\n", "\n", " Note: \"None\" is here because you don't know the exact number of selected boxes, as it depends on the threshold. \n", " For example, the actual output size of scores would be (10,) if there are 10 boxes.\n", " \"\"\"\n", " \n", " x = 10\n", " y = tf.constant(100)\n", " \n", " # YOUR CODE STARTS HERE\n", "\n", " # Step 1: Compute box scores\n", " ##(≈ 1 line)\n", " box_scores = box_class_probs*box_confidence\n", " \n", " # Step 2: Find the box_classes using the max box_scores, keep track of the corresponding score\n", " ##(≈ 2 lines)\n", " box_classes = tf.math.argmax(box_scores,axis=-1)\n", " box_class_scores = tf.math.reduce_max(box_scores,axis=-1)\n", " \n", " # Step 3: Create a filtering mask based on \"box_class_scores\" by using \"threshold\". The mask should have the\n", " # same dimension as box_class_scores, and be True for the boxes you want to keep (with probability >= threshold)\n", " ## (≈ 1 line)\n", " filtering_mask = (box_class_scores >= threshold)\n", " \n", " # Step 4: Apply the mask to box_class_scores, boxes and box_classes\n", " ## (≈ 3 lines)\n", " scores = tf.boolean_mask(box_class_scores,filtering_mask)\n", " boxes = tf.boolean_mask(boxes,filtering_mask)\n", " classes = tf.boolean_mask(box_classes,filtering_mask)\n", " \n", " # YOUR CODE ENDS HERE\n", " \n", " return scores, boxes, classes" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "code", "checksum": "615c94cc11aa6ce681b0ee798e137364", "grade": true, "grade_id": "cell-b1c9aaf8e3305fee", "locked": true, "points": 10, "schema_version": 3, "solution": false, "task": false } }, "outputs": [], "source": [ "tf.random.set_seed(10)\n", "box_confidence = tf.random.normal([19, 19, 5, 1], mean=1, stddev=4, seed = 1)\n", "boxes = tf.random.normal([19, 19, 5, 4], mean=1, stddev=4, seed = 1)\n", "box_class_probs = tf.random.normal([19, 19, 5, 80], mean=1, stddev=4, seed = 1)\n", "scores, boxes, classes = yolo_filter_boxes(boxes, box_confidence, box_class_probs, threshold = 0.5)\n", "print(\"scores[2] = \" + str(scores[2].numpy()))\n", "print(\"boxes[2] = \" + str(boxes[2].numpy()))\n", "print(\"classes[2] = \" + str(classes[2].numpy()))\n", "print(\"scores.shape = \" + str(scores.shape))\n", "print(\"boxes.shape = \" + str(boxes.shape))\n", "print(\"classes.shape = \" + str(classes.shape))\n", "\n", "assert type(scores) == EagerTensor, \"Use tensorflow functions\"\n", "assert type(boxes) == EagerTensor, \"Use tensorflow functions\"\n", "assert type(classes) == EagerTensor, \"Use tensorflow functions\"\n", "\n", "assert scores.shape == (1789,), \"Wrong shape in scores\"\n", "assert boxes.shape == (1789, 4), \"Wrong shape in boxes\"\n", "assert classes.shape == (1789,), \"Wrong shape in classes\"\n", "\n", "assert np.isclose(scores[2].numpy(), 9.270486), \"Values are wrong on scores\"\n", "assert np.allclose(boxes[2].numpy(), [4.6399336, 3.2303846, 4.431282, -2.202031]), \"Values are wrong on boxes\"\n", "assert classes[2].numpy() == 8, \"Values are wrong on classes\"\n", "\n", "print(\"\\033[92m All tests passed!\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Expected Output**:\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "\n", "
\n", " scores[2]\n", " \n", " 9.270486\n", "
\n", " boxes[2]\n", " \n", " [ 4.6399336 3.2303846 4.431282 -2.202031 ]\n", "
\n", " classes[2]\n", " \n", " 8\n", "
\n", " scores.shape\n", " \n", " (1789,)\n", "
\n", " boxes.shape\n", " \n", " (1789, 4)\n", "
\n", " classes.shape\n", " \n", " (1789,)\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note** In the test for `yolo_filter_boxes`, you're using random numbers to test the function. In real data, the `box_class_probs` would contain non-zero values between 0 and 1 for the probabilities. The box coordinates in `boxes` would also be chosen so that lengths and heights are non-negative." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### 2.3 - Non-max Suppression\n", "\n", "Even after filtering by thresholding over the class scores, you still end up with a lot of overlapping boxes. A second filter for selecting the right boxes is called non-maximum suppression (NMS). " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
Figure 7 : In this example, the model has predicted 3 cars, but it's actually 3 predictions of the same car. Running non-max suppression (NMS) will select only the most accurate (highest probability) of the 3 boxes.
\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Non-max suppression uses the very important function called **\"Intersection over Union\"**, or IoU.\n", "\n", "
Figure 8 : Definition of \"Intersection over Union\".
\n", "\n", "\n", "### Exercise 2 - iou\n", "\n", "Implement `iou()` \n", "\n", "Some hints:\n", "- This code uses the convention that (0,0) is the top-left corner of an image, (1,0) is the upper-right corner, and (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, you move to the right. As y increases, you move down.\n", "- For this exercise, a box is defined using its two corners: upper left $(x_1, y_1)$ and lower right $(x_2,y_2)$, instead of using the midpoint, height and width. This makes it a bit easier to calculate the intersection.\n", "- To calculate the area of a rectangle, multiply its height $(y_2 - y_1)$ by its width $(x_2 - x_1)$. Since $(x_1,y_1)$ is the top left and $x_2,y_2$ are the bottom right, these differences should be non-negative.\n", "- To find the **intersection** of the two boxes $(xi_{1}, yi_{1}, xi_{2}, yi_{2})$: \n", " - Feel free to draw some examples on paper to clarify this conceptually.\n", " - The top left corner of the intersection $(xi_{1}, yi_{1})$ is found by comparing the top left corners $(x_1, y_1)$ of the two boxes and finding a vertex that has an x-coordinate that is closer to the right, and y-coordinate that is closer to the bottom.\n", " - The bottom right corner of the intersection $(xi_{2}, yi_{2})$ is found by comparing the bottom right corners $(x_2,y_2)$ of the two boxes and finding a vertex whose x-coordinate is closer to the left, and the y-coordinate that is closer to the top.\n", " - The two boxes **may have no intersection**. You can detect this if the intersection coordinates you calculate end up being the top right and/or bottom left corners of an intersection box. Another way to think of this is if you calculate the height $(y_2 - y_1)$ or width $(x_2 - x_1)$ and find that at least one of these lengths is negative, then there is no intersection (intersection area is zero). \n", " - 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.\n", "\n", "\n", "**Additional Hints**\n", "\n", "- `xi1` = **max**imum of the x1 coordinates of the two boxes\n", "- `yi1` = **max**imum of the y1 coordinates of the two boxes\n", "- `xi2` = **min**imum of the x2 coordinates of the two boxes\n", "- `yi2` = **min**imum of the y2 coordinates of the two boxes\n", "- `inter_area` = You can use `max(height, 0)` and `max(width, 0)`\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#########################################################################\n", "######################## USELESS BELOW ##################################\n", "#########################################################################" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "nbgrader": { "cell_type": "code", "checksum": "15fb8b9d060ca2737fc7495a4fefe342", "grade": false, "grade_id": "cell-43008d769892f26f", "locked": false, "schema_version": 3, "solution": true, "task": false } }, "outputs": [], "source": [ "# GRADED FUNCTION: iou\n", "\n", "def iou(box1, box2):\n", " \"\"\"Implement the intersection over union (IoU) between box1 and box2\n", "    \n", " Arguments:\n", " box1 -- first box, list object with coordinates (box1_x1, box1_y1, box1_x2, box_1_y2)\n", "    box2 -- second box, list object with coordinates (box2_x1, box2_y1, box2_x2, box2_y2)\n", "    \"\"\"\n", "\n", "\n", " (box1_x1, box1_y1, box1_x2, box1_y2) = box1\n", " (box2_x1, box2_y1, box2_x2, box2_y2) = box2\n", "\n", " # YOUR CODE STARTS HERE\n", " \n", " # Calculate the (yi1, xi1, yi2, xi2) coordinates of the intersection of box1 and box2. Calculate its Area.\n", " ##(≈ 7 lines)\n", " xi1 = max(box1_x1,box2_x1)\n", " yi1 = max(box1_y1,box2_y1)\n", " xi2 = min(box1_x2,box2_x2)\n", " yi2 = min(box1_y2,box2_y2)\n", " inter_width = max(0,yi2 - yi1)\n", " inter_height = max(0,xi2 - xi1)\n", " inter_area = inter_width*inter_height\n", "\n", " # Calculate the Union area by using Formula: Union(A,B) = A + B - Inter(A,B)\n", " ## (≈ 3 lines)\n", " box1_area = (box1_x2-box1_x1)*((box1_y2-box1_y1))\n", " box2_area = (box2_x2-box2_x1)*((box2_y2-box2_y1))\n", " union_area = box1_area + box2_area - inter_area\n", " \n", " # compute the IoU\n", " ## (≈ 1 line)\n", " iou = inter_area/union_area\n", " \n", " # YOUR CODE ENDS HERE\n", " \n", " return iou" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "code", "checksum": "202215a02b8a1547256fc79eecf93783", "grade": true, "grade_id": "cell-e990c04efb445600", "locked": true, "points": 10, "schema_version": 3, "solution": false, "task": false } }, "outputs": [], "source": [ "## Test case 1: boxes intersect\n", "box1 = (2, 1, 4, 3)\n", "box2 = (1, 2, 3, 4)\n", "\n", "print(\"iou for intersecting boxes = \" + str(iou(box1, box2)))\n", "assert iou(box1, box2) < 1, \"The intersection area must be always smaller or equal than the union area.\"\n", "assert np.isclose(iou(box1, box2), 0.14285714), \"Wrong value. Check your implementation. Problem with intersecting boxes\"\n", "\n", "## Test case 2: boxes do not intersect\n", "box1 = (1,2,3,4)\n", "box2 = (5,6,7,8)\n", "print(\"iou for non-intersecting boxes = \" + str(iou(box1,box2)))\n", "assert iou(box1, box2) == 0, \"Intersection must be 0\"\n", "\n", "## Test case 3: boxes intersect at vertices only\n", "box1 = (1,1,2,2)\n", "box2 = (2,2,3,3)\n", "print(\"iou for boxes that only touch at vertices = \" + str(iou(box1,box2)))\n", "assert iou(box1, box2) == 0, \"Intersection at vertices must be 0\"\n", "\n", "## Test case 4: boxes intersect at edge only\n", "box1 = (1,1,3,3)\n", "box2 = (2,3,3,4)\n", "print(\"iou for boxes that only touch at edges = \" + str(iou(box1,box2)))\n", "assert iou(box1, box2) == 0, \"Intersection at edges must be 0\"\n", "\n", "print(\"\\033[92m All tests passed!\")\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Expected Output**:\n", "\n", "```\n", "iou for intersecting boxes = 0.14285714285714285\n", "iou for non-intersecting boxes = 0.0\n", "iou for boxes that only touch at vertices = 0.0\n", "iou for boxes that only touch at edges = 0.0\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### 2.4 - YOLO Non-max Suppression\n", "\n", "You are now ready to implement non-max suppression. The key steps are: \n", "1. Select the box that has the highest score.\n", "2. Compute the overlap of this box with all other boxes, and remove boxes that overlap significantly (iou >= `iou_threshold`).\n", "3. Go back to step 1 and iterate until there are no more boxes with a lower score than the currently selected box.\n", "\n", "This will remove all boxes that have a large overlap with the selected boxes. Only the \"best\" boxes remain.\n", "\n", "\n", "### Exercise 3 - yolo_non_max_suppression\n", "\n", "Implement `yolo_non_max_suppression()` using TensorFlow. TensorFlow has two built-in functions that are used to implement non-max suppression (so you don't actually need to use your `iou()` implementation):\n", "\n", "**Reference documentation**: \n", "\n", "- [tf.image.non_max_suppression()](https://www.tensorflow.org/api_docs/python/tf/image/non_max_suppression)\n", "```\n", "tf.image.non_max_suppression(\n", " boxes,\n", " scores,\n", " max_output_size,\n", " iou_threshold=0.5,\n", " name=None\n", ")\n", "```\n", "Note that in the version of TensorFlow used here, there is no parameter `score_threshold` (it's shown in the documentation for the latest version) so trying to set this value will result in an error message: *got an unexpected keyword argument `score_threshold`.*\n", "\n", "- [tf.gather()](https://www.tensorflow.org/api_docs/python/tf/gather)\n", "```\n", "keras.gather(\n", " reference,\n", " indices\n", ")\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "nbgrader": { "cell_type": "code", "checksum": "2b46fc75134940f8dc2b63be892a5342", "grade": false, "grade_id": "cell-45dde3252e543bbd", "locked": false, "schema_version": 3, "solution": true, "task": false } }, "outputs": [], "source": [ "# GRADED FUNCTION: yolo_non_max_suppression\n", "\n", "def yolo_non_max_suppression(scores, boxes, classes, max_boxes = 10, iou_threshold = 0.5):\n", " \"\"\"\n", " Applies Non-max suppression (NMS) to set of boxes\n", " \n", " Arguments:\n", " scores -- tensor of shape (None,), output of yolo_filter_boxes()\n", " boxes -- tensor of shape (None, 4), output of yolo_filter_boxes() that have been scaled to the image size (see later)\n", " classes -- tensor of shape (None,), output of yolo_filter_boxes()\n", " max_boxes -- integer, maximum number of predicted boxes you'd like\n", " iou_threshold -- real value, \"intersection over union\" threshold used for NMS filtering\n", " \n", " Returns:\n", " scores -- tensor of shape (, None), predicted score for each box\n", " boxes -- tensor of shape (4, None), predicted box coordinates\n", " classes -- tensor of shape (, None), predicted class for each box\n", " \n", " Note: The \"None\" dimension of the output tensors has obviously to be less than max_boxes. Note also that this\n", " function will transpose the shapes of scores, boxes, classes. This is made for convenience.\n", " \"\"\"\n", " \n", " max_boxes_tensor = tf.Variable(max_boxes, dtype='int32') # tensor to be used in tf.image.non_max_suppression()\n", " \n", " # Use tf.image.non_max_suppression() to get the list of indices corresponding to boxes you keep\n", " ##(≈ 1 line)\n", " nms_indices = tf.image.non_max_suppression(boxes,scores,max_boxes_tensor,iou_threshold)\n", " \n", " # Use tf.gather() to select only nms_indices from scores, boxes and classes\n", " ##(≈ 3 lines)\n", " scores = tf.gather(scores,nms_indices)\n", " boxes = tf.gather(boxes,nms_indices)\n", " classes = tf.gather(classes,nms_indices)\n", " # YOUR CODE STARTS HERE\n", " \n", " \n", " # YOUR CODE ENDS HERE\n", "\n", " \n", " return scores, boxes, classes" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "code", "checksum": "fdebc94241d8b19eea5d275e1c944ab7", "grade": true, "grade_id": "cell-07e64f2138d66235", "locked": true, "points": 10, "schema_version": 3, "solution": false, "task": false } }, "outputs": [], "source": [ "tf.random.set_seed(10)\n", "scores = tf.random.normal([54,], mean=1, stddev=4, seed = 1)\n", "boxes = tf.random.normal([54, 4], mean=1, stddev=4, seed = 1)\n", "classes = tf.random.normal([54,], mean=1, stddev=4, seed = 1)\n", "scores, boxes, classes = yolo_non_max_suppression(scores, boxes, classes)\n", "\n", "assert type(scores) == EagerTensor, \"Use tensoflow functions\"\n", "print(\"scores[2] = \" + str(scores[2].numpy()))\n", "print(\"boxes[2] = \" + str(boxes[2].numpy()))\n", "print(\"classes[2] = \" + str(classes[2].numpy()))\n", "print(\"scores.shape = \" + str(scores.numpy().shape))\n", "print(\"boxes.shape = \" + str(boxes.numpy().shape))\n", "print(\"classes.shape = \" + str(classes.numpy().shape))\n", "\n", "assert type(scores) == EagerTensor, \"Use tensoflow functions\"\n", "assert type(boxes) == EagerTensor, \"Use tensoflow functions\"\n", "assert type(classes) == EagerTensor, \"Use tensoflow functions\"\n", "\n", "assert scores.shape == (10,), \"Wrong shape\"\n", "assert boxes.shape == (10, 4), \"Wrong shape\"\n", "assert classes.shape == (10,), \"Wrong shape\"\n", "\n", "assert np.isclose(scores[2].numpy(), 8.147684), \"Wrong value on scores\"\n", "assert np.allclose(boxes[2].numpy(), [ 6.0797963, 3.743308, 1.3914018, -0.34089637]), \"Wrong value on boxes\"\n", "assert np.isclose(classes[2].numpy(), 1.7079165), \"Wrong value on classes\"\n", "\n", "print(\"\\033[92m All tests passed!\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Expected Output**:\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "\n", "
\n", " scores[2]\n", " \n", " 8.147684\n", "
\n", " boxes[2]\n", " \n", " [ 6.0797963 3.743308 1.3914018 -0.34089637]\n", "
\n", " classes[2]\n", " \n", " 1.7079165\n", "
\n", " scores.shape\n", " \n", " (10,)\n", "
\n", " boxes.shape\n", " \n", " (10, 4)\n", "
\n", " classes.shape\n", " \n", " (10,)\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### 2.5 - Wrapping Up the Filtering\n", "\n", "It's time to implement a function taking the output of the deep CNN (the 19x19x5x85 dimensional encoding) and filtering through all the boxes using the functions you've just implemented. \n", "\n", "\n", "### Exercise 4 - yolo_eval\n", "\n", "Implement `yolo_eval()` which takes the output of the YOLO encoding and filters the boxes using score threshold and NMS. There's just one last implementational detail you have to know. There're 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 (which are provided): \n", "\n", "```python\n", "boxes = yolo_boxes_to_corners(box_xy, box_wh) \n", "```\n", "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`\n", "```python\n", "boxes = scale_boxes(boxes, image_shape)\n", "```\n", "YOLO's network was trained to run on 608x608 images. If you are testing this data on a different size image -- for example, the car detection dataset had 720x1280 images -- this step rescales the boxes so that they can be plotted on top of the original 720x1280 image. \n", "\n", "Don't worry about these two functions; you'll see where they need to be called below. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def yolo_boxes_to_corners(box_xy, box_wh):\n", " \"\"\"Convert YOLO box predictions to bounding box corners.\"\"\"\n", " box_mins = box_xy - (box_wh / 2.)\n", " box_maxes = box_xy + (box_wh / 2.)\n", "\n", " return tf.keras.backend.concatenate([\n", " box_mins[..., 1:2], # y_min\n", " box_mins[..., 0:1], # x_min\n", " box_maxes[..., 1:2], # y_max\n", " box_maxes[..., 0:1] # x_max\n", " ])\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "nbgrader": { "cell_type": "code", "checksum": "b86b734e67da53186508d3e73aa5e413", "grade": false, "grade_id": "cell-baa7fe688d21f2dc", "locked": false, "schema_version": 3, "solution": true, "task": false } }, "outputs": [], "source": [ "# GRADED FUNCTION: yolo_eval\n", "\n", "def yolo_eval(yolo_outputs, image_shape = (720, 1280), max_boxes=10, score_threshold=.6, iou_threshold=.5):\n", " \"\"\"\n", " Converts the output of YOLO encoding (a lot of boxes) to your predicted boxes along with their scores, box coordinates and classes.\n", " \n", " Arguments:\n", " yolo_outputs -- output of the encoding model (for image_shape of (608, 608, 3)), contains 4 tensors:\n", " box_xy: tensor of shape (None, 19, 19, 5, 2)\n", " box_wh: tensor of shape (None, 19, 19, 5, 2)\n", " box_confidence: tensor of shape (None, 19, 19, 5, 1)\n", " box_class_probs: tensor of shape (None, 19, 19, 5, 80)\n", " image_shape -- tensor of shape (2,) containing the input shape, in this notebook we use (608., 608.) (has to be float32 dtype)\n", " max_boxes -- integer, maximum number of predicted boxes you'd like\n", " score_threshold -- real value, if [ highest class probability score < threshold], then get rid of the corresponding box\n", " iou_threshold -- real value, \"intersection over union\" threshold used for NMS filtering\n", " \n", " Returns:\n", " scores -- tensor of shape (None, ), predicted score for each box\n", " boxes -- tensor of shape (None, 4), predicted box coordinates\n", " classes -- tensor of shape (None,), predicted class for each box\n", " \"\"\"\n", " \n", " \n", " # Retrieve outputs of the YOLO model (≈1 line)\n", " box_xy, box_wh, box_confidence, box_class_probs = yolo_outputs\n", "\n", " # Convert boxes to be ready for filtering functions (convert boxes box_xy and box_wh to corner coordinates)\n", " boxes = yolo_boxes_to_corners(box_xy, box_wh)\n", "\n", " # Use one of the functions you've implemented to perform Score-filtering with a threshold of score_threshold (≈1 line)\n", " scores, boxes, classes = yolo_filter_boxes(boxes, box_confidence, box_class_probs, score_threshold)\n", " \n", " # Scale boxes back to original image shape (720, 1280 or whatever)\n", " boxes = scale_boxes(boxes, image_shape) # Network was trained to run on 608x608 images\n", "\n", " # Use one of the functions you've implemented to perform Non-max suppression with \n", " # maximum number of boxes set to max_boxes and a threshold of iou_threshold (≈1 line)\n", " scores, boxes, classes = yolo_non_max_suppression(scores, boxes, classes, max_boxes, iou_threshold)\n", " \n", " # YOUR CODE STARTS HERE\n", " \n", " \n", " # YOUR CODE ENDS HERE\n", " \n", " return scores, boxes, classes" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "code", "checksum": "fb065ca29f88e9410dd8a23824833771", "grade": true, "grade_id": "cell-8433ee3146a7deda", "locked": true, "points": 10, "schema_version": 3, "solution": false, "task": false } }, "outputs": [], "source": [ "tf.random.set_seed(10)\n", "yolo_outputs = (tf.random.normal([19, 19, 5, 2], mean=1, stddev=4, seed = 1),\n", " tf.random.normal([19, 19, 5, 2], mean=1, stddev=4, seed = 1),\n", " tf.random.normal([19, 19, 5, 1], mean=1, stddev=4, seed = 1),\n", " tf.random.normal([19, 19, 5, 80], mean=1, stddev=4, seed = 1))\n", "scores, boxes, classes = yolo_eval(yolo_outputs)\n", "print(\"scores[2] = \" + str(scores[2].numpy()))\n", "print(\"boxes[2] = \" + str(boxes[2].numpy()))\n", "print(\"classes[2] = \" + str(classes[2].numpy()))\n", "print(\"scores.shape = \" + str(scores.numpy().shape))\n", "print(\"boxes.shape = \" + str(boxes.numpy().shape))\n", "print(\"classes.shape = \" + str(classes.numpy().shape))\n", "\n", "assert type(scores) == EagerTensor, \"Use tensoflow functions\"\n", "assert type(boxes) == EagerTensor, \"Use tensoflow functions\"\n", "assert type(classes) == EagerTensor, \"Use tensoflow functions\"\n", "\n", "assert scores.shape == (10,), \"Wrong shape\"\n", "assert boxes.shape == (10, 4), \"Wrong shape\"\n", "assert classes.shape == (10,), \"Wrong shape\"\n", " \n", "assert np.isclose(scores[2].numpy(), 171.60194), \"Wrong value on scores\"\n", "assert np.allclose(boxes[2].numpy(), [-1240.3483, -3212.5881, -645.78, 2024.3052]), \"Wrong value on boxes\"\n", "assert np.isclose(classes[2].numpy(), 16), \"Wrong value on classes\"\n", " \n", "print(\"\\033[92m All tests passed!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Expected Output**:\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "\n", "
\n", " scores[2]\n", " \n", " 171.60194\n", "
\n", " boxes[2]\n", " \n", " [-1240.3483 -3212.5881 -645.78 2024.3052]\n", "
\n", " classes[2]\n", " \n", " 16\n", "
\n", " scores.shape\n", " \n", " (10,)\n", "
\n", " boxes.shape\n", " \n", " (10, 4)\n", "
\n", " classes.shape\n", " \n", " (10,)\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 3 - Test YOLO Pre-trained Model on Images\n", "\n", "In this section, you are going to use a pre-trained model and test it on the car detection dataset. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### 3.1 - Defining Classes, Anchors and Image Shape\n", "\n", "You're trying to detect 80 classes, and are using 5 anchor boxes. The information on the 80 classes and 5 boxes is gathered in two files: \"coco_classes.txt\" and \"yolo_anchors.txt\". You'll read class names and anchors from text files. The car detection dataset has 720x1280 images, which are pre-processed into 608x608 images." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class_names = read_classes(\"model_data/coco_classes.txt\")\n", "anchors = read_anchors(\"model_data/yolo_anchors.txt\")\n", "model_image_size = (608, 608) # Same as yolo_model input layer size" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### 3.2 - Loading a Pre-trained Model\n", "\n", "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. You are going to load an existing pre-trained Keras YOLO model stored in \"yolo.h5\". 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 notebook. Technically, these are the parameters from the \"YOLOv2\" model, but are simply referred to as \"YOLO\" in this notebook.\n", "\n", "Run the cell below to load the model from this file." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "yolo_model = load_model(\"model_data/\", compile=False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This loads the weights of a trained YOLO model. Here's a summary of the layers your model contains:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "yolo_model.summary()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note**: On some computers, you may see a warning message from Keras. Don't worry about it if you do -- this is fine!\n", "\n", "**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)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### 3.3 - Convert Output of the Model to Usable Bounding Box Tensors\n", "\n", "The output of `yolo_model` is a (m, 19, 19, 5, 85) tensor that needs to pass through non-trivial processing and conversion. You will need to call `yolo_head` to format the encoding of the model you got from `yolo_model` into something decipherable:\n", "\n", "`yolo_model_outputs = yolo_model(image_data)`\n", "\n", "`yolo_outputs = yolo_head(yolo_model_outputs, anchors, len(class_names))`\n", "\n", "The variable `yolo_outputs` will be defined as a set of 4 tensors that you can then use as input by your yolo_eval function. If you are curious about how yolo_head is implemented, you can find the function definition in the file `keras_yolo.py`. The file is also located in your workspace in this path: `yad2k/models/keras_yolo.py`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### 3.4 - Filtering Boxes\n", "\n", "`yolo_outputs` gave you all the predicted boxes of `yolo_model` in the correct format. To perform filtering and select only the best boxes, you will call `yolo_eval`, which you had previously implemented, to do so:\n", "\n", " out_scores, out_boxes, out_classes = yolo_eval(yolo_outputs, [image.size[1], image.size[0]], 10, 0.3, 0.5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### 3.5 - Run the YOLO on an Image\n", "\n", "Let the fun begin! You will create a graph that can be summarized as follows:\n", "\n", "`yolo_model.input` is given to `yolo_model`. The model is used to compute the output `yolo_model.output`\n", "`yolo_model.output` is processed by `yolo_head`. It gives you `yolo_outputs`\n", "`yolo_outputs` goes through a filtering function, `yolo_eval`. It outputs your predictions: `out_scores`, `out_boxes`, `out_classes`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, we have implemented for you the `predict(image_file)` function, which runs the graph to test YOLO on an image to compute `out_scores`, `out_boxes`, `out_classes`.\n", "\n", "The code below also uses the following function:\n", "\n", " image, image_data = preprocess_image(\"images/\" + image_file, model_image_size = (608, 608))\n", "which opens the image file and scales, reshapes and normalizes the image. It returns the outputs:\n", "\n", " image: a python (PIL) representation of your image used for drawing boxes. You won't need to use it.\n", " image_data: a numpy-array representing the image. This will be the input to the CNN." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def predict(image_file):\n", " \"\"\"\n", " Runs the graph to predict boxes for \"image_file\". Prints and plots the predictions.\n", " \n", " Arguments:\n", " image_file -- name of an image stored in the \"images\" folder.\n", " \n", " Returns:\n", " out_scores -- tensor of shape (None, ), scores of the predicted boxes\n", " out_boxes -- tensor of shape (None, 4), coordinates of the predicted boxes\n", " out_classes -- tensor of shape (None, ), class index of the predicted boxes\n", " \n", " Note: \"None\" actually represents the number of predicted boxes, it varies between 0 and max_boxes. \n", " \"\"\"\n", "\n", " # Preprocess your image\n", " image, image_data = preprocess_image(\"images/\" + image_file, model_image_size = (608, 608))\n", " \n", " yolo_model_outputs = yolo_model(image_data) # It's output is of shape (m, 19, 19, 5, 85) \n", " # But yolo_eval takes input a tensor contains 4 tensors: box_xy,box_wh, box_confidence & box_class_probs\n", " yolo_outputs = yolo_head(yolo_model_outputs, anchors, len(class_names))\n", " \n", " out_scores, out_boxes, out_classes = yolo_eval(yolo_outputs, [image.size[1], image.size[0]], 10, 0.3, 0.5)\n", "\n", " # Print predictions info\n", " print('Found {} boxes for {}'.format(len(out_boxes), \"images/\" + image_file))\n", " # Generate colors for drawing bounding boxes.\n", " colors = get_colors_for_classes(len(class_names))\n", " # Draw bounding boxes on the image file\n", " #draw_boxes2(image, out_scores, out_boxes, out_classes, class_names, colors, image_shape)\n", " draw_boxes(image, out_boxes, out_classes, class_names, out_scores)\n", " # Save the predicted bounding box on the image\n", " image.save(os.path.join(\"out\", str(image_file).split('.')[0]+\"_annotated.\" +str(image_file).split('.')[1] ), quality=100)\n", " # Display the results in the notebook\n", " output_image = Image.open(os.path.join(\"out\", str(image_file).split('.')[0]+\"_annotated.\" +str(image_file).split('.')[1] ))\n", " imshow(output_image)\n", "\n", " return out_scores, out_boxes, out_classes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Run the following cell on the \"test.jpg\" image to verify that your function is correct." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "out_scores, out_boxes, out_classes = predict(\"0001.jpg\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Expected Output**:\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
\n", " Found 10 boxes for images/test.jpg\n", "
\n", " car\n", " \n", " 0.89 (367, 300) (745, 648)\n", "
\n", " car\n", " \n", " 0.80 (761, 282) (942, 412)\n", "
\n", " car\n", " \n", " 0.74 (159, 303) (346, 440)\n", "
\n", " car\n", " \n", " 0.70 (947, 324) (1280, 705)\n", "
\n", " bus\n", " \n", " 0.67 (5, 266) (220, 407)\n", "
\n", " car\n", " \n", " 0.66 (706, 279) (786, 350)\n", "
\n", " car\n", " \n", " 0.60 (925, 285) (1045, 374)\n", "
\n", " car\n", " \n", " 0.44 (336, 296) (378, 335)\n", "
\n", " car\n", " \n", " 0.37 (965, 273) (1022, 292)\n", "
\n", " traffic light\n", " \n", " 00.36 (681, 195) (692, 214)\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The model you've just run is actually able to detect 80 different classes listed in \"coco_classes.txt\". To test the model on your own images:\n", " 1. Click on \"File\" in the upper bar of this notebook, then click \"Open\" to go on your Coursera Hub.\n", " 2. Add your image to this Jupyter Notebook's directory, in the \"images\" folder\n", " 3. Write your image's name in the cell above code\n", " 4. Run the code and see the output of the algorithm!\n", "\n", "If you were to run your session in a for loop over all your images. Here's what you would get:\n", "\n", "
\n", "\n", "
\n", "\n", "
Predictions of the YOLO model on pictures taken from a camera while driving around the Silicon Valley
Thanks to drive.ai for providing this dataset!
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 4 - Summary for YOLO\n", "\n", "- Input image (608, 608, 3)\n", "- The input image goes through a CNN, resulting in a (19,19,5,85) dimensional output. \n", "- After flattening the last two dimensions, the output is a volume of shape (19, 19, 425):\n", " - Each cell in a 19x19 grid over the input image gives 425 numbers. \n", " - 425 = 5 x 85 because each cell contains predictions for 5 boxes, corresponding to 5 anchor boxes, as seen in lecture. \n", " - 85 = 5 + 80 where 5 is because $(p_c, b_x, b_y, b_h, b_w)$ has 5 numbers, and 80 is the number of classes we'd like to detect\n", "- You then select only few boxes based on:\n", " - Score-thresholding: throw away boxes that have detected a class with a score less than the threshold\n", " - Non-max suppression: Compute the Intersection over Union and avoid selecting overlapping boxes\n", "- This gives you YOLO's final output. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", " \n", "**What you should remember**:\n", " \n", "- YOLO is a state-of-the-art object detection model that is fast and accurate\n", "- It runs an input image through a CNN, which outputs a 19x19x5x85 dimensional volume. \n", "- The encoding can be seen as a grid where each of the 19x19 cells contains information about 5 boxes.\n", "- You filter through all the boxes using non-max suppression. Specifically: \n", " - Score thresholding on the probability of detecting a class to keep only accurate (high probability) boxes\n", " - Intersection over Union (IoU) thresholding to eliminate overlapping boxes\n", "- Because training a YOLO model from randomly initialized weights is non-trivial and requires a large dataset as well as lot of computation, previously trained model parameters were used 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. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Congratulations!** You've come to the end of this assignment. \n", "\n", "Here's a quick recap of all you've accomplished.\n", "\n", "You've: \n", "\n", "- Detected objects in a car detection dataset\n", "- Implemented non-max suppression to achieve better accuracy\n", "- Implemented intersection over union as a function of NMS\n", "- Created usable bounding box tensors from the model's predictions\n", "\n", "Amazing work! If you'd like to know more about the origins of these ideas, spend some time on the papers referenced below. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## 5 - References\n", "\n", "The ideas presented in this notebook 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. \n", "- Joseph Redmon, Santosh Divvala, Ross Girshick, Ali Farhadi - [You Only Look Once: Unified, Real-Time Object Detection](https://arxiv.org/abs/1506.02640) (2015)\n", "- Joseph Redmon, Ali Farhadi - [YOLO9000: Better, Faster, Stronger](https://arxiv.org/abs/1612.08242) (2016)\n", "- Allan Zelener - [YAD2K: Yet Another Darknet 2 Keras](https://github.com/allanzelener/YAD2K)\n", "- The official YOLO website (https://pjreddie.com/darknet/yolo/) \n", "\n", "### Car detection dataset\n", "\n", "\"Creative
The Drive.ai Sample Dataset (provided by drive.ai) is licensed under a Creative Commons Attribution 4.0 International License. Thanks to Brody Huval, Chih Hu and Rahul Patel for providing this data. " ] } ], "metadata": { "coursera": { "course_slug": "convolutional-neural-networks", "graded_item_id": "OMdut", "launcher_item_id": "bbBOL" }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" } }, "nbformat": 4, "nbformat_minor": 2 }