DevStory

Part 3. Creating a Custom YOLO v3 Model

Sharing how to train YOLO, a real-time object detection model.

Part 1. Building a More Realistic AR App with Deep Learning
Part 2. Building an iOS AR App with ARKit
✔︎ Part 3. Creating a Custom YOLO v3 Model
Part 4. Deploying a YOLO v3 Model on iOS with CoreML


What is the YOLO?

Before starting, let's go over a brief explanation of YOLO and how to train it.

✔︎ Outline

  • YOLO Architecture & Output
  • Preparing Object Detection Data
  • Transfer Learning

This post is about using the YOLO model, so for a detailed explanation of YOLO, please refer to other articles.


YOLO Architecture

YOLO (You Only Look Once) is a Real-Time Object Detection model that can identify the types and positions of trained objects in real time, and it's composed of the following architecture.

YOLO v3 Architecture Source - https://www.cyberailab.com

YOLO v3 Architecture
Source - https://www.cyberailab.com


YOLO Output

The YOLO model's output is a tensor of the form N x N x (C + 5) x B), and from this information you can get the types and 2D coordinates of the objects in the image.

N x N x (C + 5) x B)

  • N x N : Grid
  • C : Number of trained Objects (Classes)
  • 5 : Bounding Box information of the detected Object (x, y, w, h, confidence)
  • B : Number of boxes per Grid cell
YOLO output Source - https://www.cyberailab.com

YOLO output
Source - https://www.cyberailab.com

Next, let's look at how to prepare data for training the YOLO model.


Preparing Training Data

To build an Object Detection model, you need images containing the objects and labels indicating the positions and types of the objects in the images. In this project, I prepared the data in the following order.

✔︎ Data preparation steps

  • Image Gathering
  • Image Labeling
  • Image Resizing
  • Image Generating

Image Gathering

In this project, I trained on three objects in total: lamps, bulbs, and fluorescent lights, and collected the following images for this. For lamps and bulbs, I split them into different classes so the ON/OFF state can be distinguished, so there are 5 classes in total.

Photos used to train the light recognition model: a lamp on and off, a bulb on and off, and a fluorescent lamp.
Images used to build the light recognition model

I filmed the objects as videos and converted each frame into an image, collecting a total of 5,000 images.

video to image using OpenCV

import cv2
for i in range(len(videoFiles)):
    cam = cv2.VideoCapture(videoFile)
    currentFrame = 0
    while(True):
        ret, frame = cam.read()
        if ret:
            cv2.imwrite(currentFrame + '.jpg', frame)
            currentFrame += 1
        else:
            break
    cam.release()

Image Labeling

To build an Object Detection model, you need images containing the objects you want to train on, along with labels recording each object's type and position. Labels have to be created by hand, and to make the work easier I used an open source tool called labelImg.

labelImg returns the positions and types of the objects in an image in xml format.

<annotation>
	<folder>lamp_on</folder>
	<filename>0.jpg</filename>
	<path>/lamp_on/0.jpg</path>
	<source>
		<database>Unknown</database>
	</source>
	<size>
		<width>1920</width>
		<height>1080</height>
		<depth>3</depth>
	</size>
	<segmented>0</segmented>
	<object>
		<name>lamp_on</name>
		<pose>Unspecified</pose>
		<truncated>0</truncated>
		<difficult>0</difficult>
		<bndbox>
			<xmin>704</xmin>
			<ymin>384</ymin>
			<xmax>970</xmax>
			<ymax>546</ymax>
		</bndbox>
	</object>
</annotation>

Image Resizing

The original collected images are 1920 x 1080, which takes a lot of training time, so I used the Pillow library to reduce the image size to one tenth, 192 x 108.

image resizing

from PIL import Image
for image_file in images:
  image = Image.open(image_file)
  resize_image = image.resize((192, 108))
  resize_image.save(new_path)

label resizing

def changeLabel(xmlPath, newXmlPath, imgPath, boxes):
    tree = elemTree.parse(xmlPath)

    # change path
    path = tree.find('./path')
    path.text = imgPath[0]

    # change bounding box
    objects = tree.findall('./object')
    for i, object_ in enumerate(objects):
        bndbox = object_.find('./bndbox')
        bndbox.find('./xmin').text = str(boxes[i][0])
        bndbox.find('./ymin').text = str(boxes[i][1])
        bndbox.find('./xmax').text = str(boxes[i][2])
        bndbox.find('./ymax').text = str(boxes[i][3])
    tree.write(newXmlPath, encoding='utf8')

Image Generating

The more high-quality data there is, the better the model performs, but labeling too much data by hand is hard, so I generated additional images from the 5,000 labeled images. There are various ways to generate images, but rotation introduces large errors due to the limits of Bounding Box notation, so I used horizontal flip to increase the images to 10,000.

horizontal flip

import random
import numpy as np
class RandomHorizontalFlip(object):
    def __init__(self, p=0.5):
        self.p = p

    def __call__(self, img, bboxes):
        img_center = np.array(img.shape[:2])[::-1]/2
        img_center = img_center.astype(int)
        img_center = np.hstack((img_center, img_center))
        if random.random() < self.p:
            img = img[:, ::-1, :]
            bboxes[:, [0, 2]] += 2*(img_center[[0, 2]] - bboxes[:, [0, 2]])
            box_w = abs(bboxes[:, 0] - bboxes[:, 2])
            bboxes[:, 0] -= box_w
            bboxes[:, 2] += box_w
        return img, bboxes

The labels are generated along with the images.

for imgFile in imgFiles:
    fileName = imgFile.split('.')[0]
    label = f'{labelPath}{fileName}.xml'
    w, h = getSizeFromXML(label)

    # opencv loads images in bgr. the [:,:,::-1] does bgr -> rgb
    image = cv2.imread(imgPath + imgFile)[:,:,::-1]
    bboxes = getRectFromXML(classes, label)

    # HorizontalFlip image
    image, bboxes = RandomHorizontalFlip(1)(image.copy(), bboxes.copy())

    # Save image
    image = Image.fromarray(image, 'RGB')
    newImgPath = f'./data/light/image/train/{className}/'
    if not os.path.exists(newImgPath):
        os.makedirs(newImgPath)
    image.save(newImgPath + imgFile)

    # Save label
    newXmlPath = f'./data/light/label/train/{className}/'
    if not os.path.exists(newXmlPath):
        os.makedirs(newXmlPath)
    newXmlPath = newXmlPath + fileName + '.xml'
    changeLabel(label, newXmlPath, newImgPath, bboxes)

That finishes preparing the labeled images. Next, I'll explain how to train the YOLO model with the data.


YOLO Training

I trained the YOLO model using the Keras-yolo3 library.

✔︎ Outline

  • Convert Darknet Model To Keras Model
  • Convert Annotation
  • Training

Convert Darknet Model To Keras Model

The YOLO v3 model is too heavy to put on a mobile device, so I used Tiny YOLO v3, the lightweight version, and trained with transfer learning, which lets you reuse the existing trained weights as they are.

Download tiny yolov3 pretrained weights

wget https://pjreddie.com/media/files/yolov3-tiny.weights

Running the command above downloads 35.4MB of weights called yolov3-tiny.weights. YOLO3 itself is implemented in DarkNet, a framework written in C/C++. You need to convert it to the .h5 format that can be used in Keras. For the conversion, use the convert.py file from Keras-yolo3.

Convert darknet model to keras model

python convert.py yolov3-tiny.cfg yolov3-tiny.weights model_data/yolo_tiny.h5

✔︎ Convert darknet model to keras model

  • convert.py : The file that performs the conversion command
  • yolov3.cfg : The file defining the model structure used in Darknet
  • yolov3.weight : The model file trained with Darknet

When it finishes, the weights file is converted to .h5. Next, to test whether the converted model works well, let's use the sample image below.

sample image : dog.jpg Source : darknet

sample image : dog.jpg
Source : darknet

tiny YOLO v3 converted model test

from IPython.display import display
from PIL import Image
from yolo import YOLO

def objectDetection(file, model_path, class_path):
    yolo = YOLO(model_path=model_path, classes_path=class_path, anchors_path="model_data/tiny_yolo_anchors.txt")
    image = Image.open(file)
    result_image = yolo.detect_image(image)
    display(result_image)

objectDetection('dog.jpg', 'model_data/yolo_tiny.h5', 'model_data/coco_classes.txt')

Since the YOLO model returns appropriate bounding boxes, confidence, and classes, the conversion seems to have succeeded.

YOLO model that detected a bicycle, a dog, and a car Source : darknet

YOLO model that detected a bicycle, a dog, and a car
Source : darknet


Convert Annotation

To train on data with Keras-yolo3, you need to convert the data labeled above into the format below. You can refer to the voc_annotation.py file to convert it into the following form.

✔︎ Annotation Format

  • Row format: image_file_path box1 box2 ... boxN
  • Box format: x_min,y_min,x_max,y_max,class_id (no space)

Annotation example

path/to/img1.jpg 50,100,150,200,0 30,50,200,120,3
path/to/img2.jpg 120,300,250,600,2

Convert annotation

import xml.etree.ElementTree as ET
from os import getcwd
import glob

def convert_annotation(annotation_voc, train_all_file):
    tree = ET.parse(annotation_voc)
    root = tree.getroot()

    for obj in root.iter('object'):
        difficult = obj.find('difficult').text
        cls = obj.find('name').text
        if cls not in classes or int(difficult)==1: continue
        cls_id = classes.index(cls)
        xmlbox = obj.find('bndbox')
        b = (int(xmlbox.find('xmin').text), int(xmlbox.find('ymin').text), int(xmlbox.find('xmax').text), int(xmlbox.find('ymax').text))
        train_all_file.write(" " + ",".join([str(a) for a in b]) + ',' + str(cls_id))

train_all_file = open('./data/light/train_all.txt', 'w')

# Get annotations_voc list
for className in classes:
    annotations_voc = glob.glob(f'./data/light/label/train/{className}/*.xml')
    for annotation_voc in annotations_voc:
        image_id = annotation_voc.split('/')[-1].split('.')[0]+'.JPG'
        train_all_file.write(f'./data/light/image/train/{className}/{image_id}')
        convert_annotation(annotation_voc, train_all_file)
        train_all_file.write('\n')
train_all_file.close()

My annotation conversion result

./data/light/image/train/bulb_on/162.JPG 70,0,124,52,0
./data/light/image/train/bulb_on/1390.JPG 70,61,117,100,0
./data/light/image/train/bulb_on/604.JPG 78,38,93,52,0
./data/light/image/train/bulb_on/88.JPG 72,28,139,93,0

Transfer Learning

Finally, for training, the _main() function in the train.py file has the following variables, and you modify them and run it.

_main() in train.py

def _main():
  annotation_path = 'data/light/train_all.txt' # Path to the result file from Convert Annotation above
  log_dir = 'logs/000/' # Path to save training logs
  classes_path = 'data/light/classes.txt' # List of classes to train
  anchors_path = 'model_data/yolo_tiny_anchors.txt' # Anchors of the tiny YOLO model
  transfer_learning_path = 'model_data/yolo_tiny.h5' # The h5 file resulting from Convert Darknet Model To Keras Model
  # ... omitted below

After modifying it as above and running it, it loads the existing pretrained tiny YOLO weights and starts Transfer Learning. It trains for a total of 100 epochs with a batch size of 32. Up to epoch 50, training runs with 42 of the 44 Layers frozen, and after that, all layers are unfrozen and training continues.

However, Keras's EarlyStop is applied with the following conditions, so training sometimes ends before going through the full 100 epochs.

EarlyStopping

EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1)

Also, to pick the best model, the ModelCheckpoint function monitors the validation error, and whenever the validation performance is better than in the previous epoch, it always saves those parameters along the way, so even if training stops midway, you can preserve the intermediate results.

With all the training done, let's test the model.

Trained Model Test

from IPython.display import display
from PIL import Image
from yolo import YOLO

def objectDetection(file, model_path, class_path):
    yolo = YOLO(model_path=model_path, classes_path=class_path, anchors_path='model_data/yolo_tiny_anchors.txt')
    image = Image.open(file)
    result_image = yolo.detect_image(image)
    display(result_image)

objectDetection('data/light/test/562.jpg', 'model_data/light_tiny_model.h5', 'data/light/classes.txt')
The transfer-learned tiny YOLO v3 finds each light in the photos and boxes it with a label and confidence such as lamp_on, bulb_off, bulb_on and fluorescent_lamp.
tiny YOLO v3 output after transfer learning

It accurately detects the exact Bounding Box, confidence, and type of the lights in the image. To save the tested model as a file, I added a function that returns the trained model to the yolo.py file of Keras-yolo3.

Adding a function that returns the trained model to the yolo.py file

def get_model(self):
    return self.yolo_model

Then I saved the trained model using the model's save function.

save keras h5 model

model = yolo.get_model()
model.save('model_data/light_tiny_model.h5')

Closing

In Part 4, I'll explain how to put the trained YOLO Model on an iOS application.

Also, since many people asked for the source code, I'm sharing the github link.

Part 1. Building a More Realistic AR App with Deep Learning
Part 2. Building an iOS AR App with ARKit
✔︎ Part 3. Creating a Custom YOLO v3 Model
Part 4. Deploying a YOLO v3 Model on iOS with CoreML

Comments