Train a custom YOLOv4 detector using Google Colab

Train a custom YOLOv4 detector using Google Colab

(Tutorial for beginners)

Image for post

In this tutorial, we will be training our custom detector for mask detection using YOLOv4 and Darknet

Image for post
Original Video by cottonbro from Pexels

HOW TO BEGIN?

  • Open my Colab notebook on your browser.
  • Click on File in the menu bar and click on Save a copy in drive. This will open a copy of my Colab notebook on your browser which you can now use.
  • Next, once you have opened the copy of my notebook and are connected to the Google Colab VM, click on Runtime in the menu bar and click on Change runtime type. Select GPU and click on save.
Image for post

FOLLOW THESE 12 STEPS TO TRAIN AN OBJECT DETECTOR USING YOLOv4

(NOTE: For this YOLOv4 Tutorial, we will be cloning the Darknet git repository in a folder on our google drive)

  1. Create yolov4 and training folders in your google drive
  2. Mount drive, link your folder and navigate to the yolov4 folder
  3. Clone the Darknet git repository
  4. Create & upload the files we need for training ( i.e. “obj.zip” , “yolov4- custom.cfg”, “obj.data”, “obj.names” and “process.py” ) to your drive
  5. Make changes in the Makefile to enable OPENCV and GPU
  6. Run make command to build darknet
  7. Copy the files “obj.zip”, “yolov4-custom.cfg”, “obj.data”, “obj.names”, and “process.py” from the yolov4 folder to the darknet directory
  8. Run the process.py python script to create the train.txt & test.txt files
  9. Download the pre-trained YOLOv4 weights
  10. Train the detector
  11. Check performance
  12. Test your custom Object Detector

NOTE: If you get disconnected or lose your session for some reason, you have to run steps 2, 5, and 6 again to mount the drive, edit makefile and build darknet every single time, otherwise the darknet executable will not work.

LET’S BEGIN !!

Image for post
Original Video by cottonbro from Pexels

1) Create ‘yolov4’ and ‘training’ folders in your drive

Create a folder named yolov4 in your google drive. Next, create another folder named training inside the yolov4 folder. This is where we will save our trained weights (This path is mentioned in the obj.data file which we will upload later)

Image for post

2) Mount drive, link your folder, and navigate to the “yolov4” folder in your drive

Mount drive
%cd ..
from google.colab import drive
drive.mount('/content/gdrive')
Link your folder

Run the following command to create a symbolic link so that now the path /content/gdrive/My Drive/ is equal to /mydrive

!ln -s /content/gdrive/My Drive/ /mydrive
Navigate to /mydrive/yolov4 folder
%cd /mydrive/yolov4

3) Clone Darknet git repository

Clone the Darknet git repository in the yolov4 folder on your drive.

!git clone https://github.com/AlexeyAB/darknet
Image for post
Cloned Darknet repository in yolov4 folder

You can also view the folder from Colab since the drive has already been mounted. See pic below.

Image for post

4) Create & upload the following files which we need for training a custom detector

a. Labeled Custom Dataset
b. Custom cfg file
c. obj.data and obj.names files
d. process.py file (to create train.txt and test.txt files for training)
I have uploaded my custom files for mask detection on my GitHubI am working with 2 classes i.e. “with_mask” and “without_mask”.

Labeling your Dataset

Input image example (Image1.jpg)

Image for post
Original Photo by Ali Pazani from Pexels

You can use any software for labeling like the labelImg tool.

I use an open-source labeling tool called OpenLabeling with a very simple UI.

Image for post
OpenLabeling Tool GUI

Click on the link below to know more about the labeling process and other software for it:

Image Dataset Labeling article

NOTE: Garbage In = Garbage Out. Choosing and labeling images is the most important part. Try to find good-quality images. The quality of the data goes a long way toward determining the quality of the result.

The output YOLO format labeled file looks like as shown below.

Image for post
Image1.txt

4(a) Create and upload the labeled custom dataset “obj.zip” file to the “yolov4” folder on your drive

Put all the input image “.jpg” files and their corresponding YOLO format labeled “.txt” files in a folder named obj.

Create its zip file obj.zip and upload it to the yolov4 folder on your drive.

Image for post
obj folder containing both the input image files and the YOLO labeled text files

4(b) Create your custom config file and upload it to the ‘yolov4’ folder on your drive

Download the yolov4-custom.cfg file from darknet/cfgdirectorymake changes to it, and upload it to theyolov4/data folder on your drive.

You can also download the custom config files from the official AlexeyAB Github.

You need to make the following changes in your custom config file:

  • change line batch to batch=64
  • change line subdivisions to subdivisions=16
  • set network size width=416 height=416 or any value multiple of 32
  • change line max_batches to (classes*2000 but not less than the number of training images and not less than 6000), f.e. max_batches=6000 if you train for 3 classes
  • change line steps to 80% and 90% of max_batches, f.e. steps=4800,5400


Image for post
  • change [filters=255] to filters=(classes + 5)x3 in the 3 [convolutional] before each [yolo] layer, keep in mind that it only has to be the last [convolutional] before each of the [yolo] layers.
  • change line classes=80 to your number of objects in each of 3 [yolo]-layers.

So if classes=1 then it should be filters=18. If classes=2 then write filters=21.

You can tweak other parameter values too like the learning rate, angle, saturation, exposure, and hue once you’ve understood how the basics of the training process work. For beginners, the above changes should suffice.


4(c) Create your “obj.data” and “obj.names” files and upload them to your drive

obj.data

The obj.data file has :

  • The number of classes the path to.
  • The train.txt and test.txt files that we will create later.
  • The obj.names file which contains the names of the classes.
  • The training folder where the training weights will be saved.

obj.names

Has objects’ names — each in a new line. Make sure the classes are in the same order as in the class_list.txt file used while labeling the images so the index id of every class is the same as mentioned in the labeled YOLO text files.


4(d) Upload the <process.py> script file to your drive

(To divide all image files into 2 parts. 90% for train and 10% for test)

This process.py script creates the files train.txt & test.txt where the train.txtfile has paths to 90% of the images and test.txt has paths to 10% of the images.

You can download the process.py script from my GitHub.

Now that we have uploaded all the files, our yolov4folder on our drive should look like this:

Image for post

5) Make changes in the makefile to enable OPENCV and GPU.

(Also set CUDNN, CUDNN_HALF, and LIBSO to 1)

%cd darknet/
!sed -i 's/OPENCV=0/OPENCV=1/' Makefile
!sed -i 's/GPU=0/GPU=1/' Makefile
!sed -i 's/CUDNN=0/CUDNN=1/' Makefile
!sed -i 's/CUDNN_HALF=0/CUDNN_HALF=1/' Makefile
!sed -i 's/LIBSO=0/LIBSO=1/' Makefile

6) Run make command to build darknet

!make

7) Copy all the files from the ‘yolov4' folder to the ‘darknet’ directory

The current working directory is /mydrive/yolov4/darknet

Clean the data and cfg folders except for the labels folder inside the data folder which is required for writing label names on the detection boxes.

So just remove all other files from the data folder and completely clean the cfg folder as we already have our custom config file in the yolov4 folder on our drive.

This step is optional.

%cd data/
!find -maxdepth 1 -type f -exec rm -rf {} ;
%cd ..
%rm -rf cfg/
%mkdir cfg
7(a) Unzip the obj.zip dataset and its contents so that they are now in /darknet/data/ folder
!unzip /mydrive/yolov4/obj.zip -d data/
7(b) Copy your yolov4-custom.cfg file so that it is now in /darknet/cfg/ folder
!cp /mydrive/yolov4/yolov4-custom.cfg cfg
7(c) Copy the obj.names and obj.data files so that they are now in /darknet/data/ folder
!cp /mydrive/yolov4/obj.names data
!cp /mydrive/yolov4/obj.data  data
7(d) Copy the process.py file into the current darknet directory
!cp /mydrive/yolov4/process.py .

8) Run the process.py python script to create the train.txt & test.txt files inside the data folder

!python process.py

List the contents of the data folder to check if the train.txt & test.txt files have been created.

!ls data/

The above process.py script creates the two files train.txt and test.txt where train.txt has paths to 90% of the images and test.txt has paths to 10% of the images. These files look like as shown below.

Image for post
train.txt & test.txt files

9) Download the pre-trained YOLOv4 weights

Here we use transfer learning. Instead of training a model from scratch, we use pre-trained YOLOv4 weights which have been trained up to 137 convolutional layers. Run the following command to download the YOLOv4 pre-trained weights file.

!wget https://github.com/AlexeyAB/darknet/releases/download/darknet_yolo_v3_optimal/yolov4.conv.137

10) Training

Train your custom detector

For best results, you should stop the training when the average loss is less than 0.05 if possible or at least constantly below 0.3, else train the model until the average loss does not show any significant change for a while.

./darknet detector train data/obj.data cfg/yolov4-custom.cfg yolov4.conv.137 -dont_show -map
The map parameter here gives us the Mean Average Precision. The higher the mAP the better it is for object detection.

You can visit the official AlexeyAB Github page which gives a detailed explanation on when to stop training. Click on the link below to jump to that section.

AlexeyAB GitHub When to stop training

NOTE: If you get disconnected or lose your session for some reason, you have to run steps 2, 5, and 6 again to mount the drive, edit makefile and build darknet every single time, otherwise the darknet executable will not work.

To restart your training (In case the training does not finish and you get disconnected)

Image for post

If you get disconnected or lose your session, you don’t have to start training your model from scratch again. You can restart training from where you left off. Use the weights that were saved last. The weights are saved every 100 iterations as yolov4-custom_last.weights in the yolov4/training folder on your drive. (The path we gave as backup in “obj.data” file).

So to restart training run Steps 2, 5, 6, and then run the following command:

!./darknet detector train data/obj.data cfg/yolov4-custom.cfg /mydrive/yolov4/training/yolov4-custom_last.weights -dont_show -map

Use this simple hack for Auto-Click to avoid being kicked off Colab VM

Press (Ctrl + Shift + i) . Go to console. Paste the following code and press Enter.

function ClickConnect(){
console.log("Working"); 
document
  .querySelector('#top-toolbar > colab-connect-button')
  .shadowRoot.querySelector('#connect')
  .click() 
}
setInterval(ClickConnect,60000)

11) Check performance

Define helper function imShow

def imShow(path):import cv2
import matplotlib.pyplot as plt
%matplotlib inline
image = cv2.imread(path)
height, width = image.shape[:2]
resized_image = cv2.resize(image,(3*width, 3*height), interpolation = cv2.INTER_CUBIC)
fig = plt.gcf()
fig.set_size_inches(18, 10)
plt.axis(“off”)
plt.imshow(cv2.cvtColor(resized_image, cv2.COLOR_BGR2RGB))
plt.show()

Check the training chart

You can check the performance of all the trained weights by looking at the chart.png file. However, the chart.png file only shows results if the training does not get interrupted i.e. if you do not get disconnected or lose your session. If you restart training from a saved point, this will not work.

imShow('chart.png')

If this does not work, there are other methods to check your performance. One of them is by checking the mAP of the trained weights.

Check mAP (mean average precision)

You can check mAP for all the weights saved every 1000 iterations for eg:- yolov4-custom_4000.weights, yolov4-custom_5000.weights, yolov4-custom_6000.weights, and so on. This way you can find out which weights file gives you the best result. The higher the mAP the better it is.

Run the following command to check the mAP for a particular saved weights file where xxxx is the iteration number for it.(eg:- 4000,5000,6000,…)

!./darknet detector map data/obj.data cfg/yolov4-custom.cfg /mydrive/yolov4/training/yolov4-custom_xxxx.weights -points 0

12) Test your custom Object Detector

Make changes to your custom config file to set it to test mode

  • change line batch to batch=1
  • change line subdivisions to subdivisions=1

You can do it either manually or by simply running the code below

%cd cfg
!sed -i 's/batch=64/batch=1/' yolov4-custom.cfg
!sed -i 's/subdivisions=16/subdivisions=1/' yolov4-custom.cfg
%cd ..

Run detector on an image

Upload an image to your google drive to test.

Run your custom detector on an image with this command. (The thresh flag sets the minimum accuracy required for object detection)

!./darknet detector test data/obj.data cfg/yolov4-custom.cfg /mydrive/yolov4/training/yolov4-custom_best.weights /mydrive/mask_test_images/image1.jpg -thresh 0.3imShow('predictions.jpg')
Image for post
Original Photo by Norma Mortenson from Pexels

Run detector on webcam images

For running detector on images captured by a webcam run the following code. This is the code snippet provided by Google Colab for camera capture except for the last two lines which run the detector on the saved image as we did in the previous command above.

Image for post
Detection on a webcam image

Run detector on a video

Upload a video to your google drive to test.

Run your custom detector on a video with this command. (The thresh flag sets the minimum accuracy required for object detection)

!./darknet detector demo data/obj.data cfg/yolov4-custom.cfg /mydrive/yolov4/training/yolov4-custom_best.weights -dont_show /mydrive/mask_test_videos/test1.mp4 -thresh 0.5 -i 0 -out_filename /mydrive/mask_test_videos/results1.avi
Image for post
Original Video by Max Fischer from Pexels

Run detector on a live webcam

First Import dependencies, define helper functions and load your custom YOLOv4 files, and then run the detector on a webcam.

Run the code below. (NOTE: Adjust the custom files in line 22 to your files)

Detection on a webcam

NOTE:

The dataset I have collected for mask detection contains mostly close-up images. For more long-shot images you can search online. There are many sites where you can download labeled and unlabeled datasets. I have given a few links at the bottom under Dataset Sources. I have also given a few links for mask datasets. Some of them have more than 10,000 images.

Though there are certain tweaks and changes we can make to our training config file or add more images to the dataset for every type of object class through augmentation, we have to be careful so that it does not cause overfitting which affects the accuracy of the model.

For beginners, you can start simply by using the config file I have uploaded on myGitHubI have also uploaded mymask images dataset along with the YOLO format labeled text files, which although might not be the best but will give you a good start on how to train your own custom detector model using YOLO. You can find a labeled dataset of better quality or an unlabeled dataset and label it yourself later.

Image for post
Original Video by Max Fischer from Pexels

GitHub link

I have uploaded my custom mask dataset and all the other files needed for training a custom YOLOv4 detector on my GitHub link below.

https://github.com/techzizou/yolov4-custom_Training


Labeled Dataset (obj.zip)

Labeled Mask Dataset


Colab notebook for this

YOLOv4 custom training Tutorial


YouTube video on this!


CREDITS

References

Dataset Sources

You can download datasets for many objects from the sites mentioned below. These sites also contain images of many classes of objects along with their annotations/labels in multiple formats such as the YOLO_DARKNET text files and the PASCAL_VOC XML files.

Mask Dataset Sources

I have used these 3 datasets for my labeled dataset:

More Mask Datasets

Video Sources


Image for post
Original Video by Nothing Ahead from Pexels

Leave a Reply