Converting YOLOv4 trained model weights to TensorFlow Lite model

Raunak Singh Inventor
2 min readJun 23, 2022

--

Clone the repository

>> git clone https://github.com/hunglc007/tensorflow-yolov4-tflite>> cd tensorflow-yolov4-tflite/

Make sure you have conda installed on your system

>> conda create -n tf2.3-cpu python=3.6>> conda activate tf2.3-cpu

Install TensorFlow 2.3

>> pip install tensorflow==2.3

Convert DarkNet Weights to TensorFlow Model

If you followed my previous tutorial, https://medium.com/@raunak.singh.inventor/pop-os-ubuntu-install-darknet-for-yolov4-object-detection-with-gpu-and-opencv-support-4a7f6700c5e8, you can just copy the YOLOv4 weights from there to the data/ folder.

The weights are also available here: https://github.com/AlexeyAB/darknet/releases/download/darknet_yolo_v3_optimal/yolov4.weights

>> pip install opencv-python>> pip install easydict>> python save_model.py --weights ./data/yolov4.weights --output ./checkpoints/yolov4-416 --input_size 416 --model yolov4

Now the DarkNet Weights have been converted to a Tensorflow Model available in the checkpoints folder. Let’s check if it works by predicting on a demo image.

>> pip install pillow>> python detect.py --weights ./checkpoints/yolov4-416 --size 416 --model yolov4 --image ./data/kite.jpg

if you get this error:

cv2.error: OpenCV(4.6.0) :-1: error: (-5:Bad argument) in function 'rectangle'
> Overload resolution failed:
> - Can't parse 'pt1'. Sequence item with index 0 has a wrong type
> - Can't parse 'pt1'. Sequence item with index 0 has a wrong type
> - Can't parse 'rec'. Expected sequence length 4, got 2
> - Can't parse 'rec'. Expected sequence length 4, got 2

Then edit core/utils.py as per the instructions here: https://github.com/hunglc007/tensorflow-yolov4-tflite/issues/368

and then run:

>> autopep8 -i core/utils.py>> python detect.py --weights ./checkpoints/yolov4-416 --size 416 --model yolov4 --image ./data/kite.jpg

This should give you the image below:

Convert TensorFlow Model to TFLite Model

Convert the DarkNet weights to TensorFlow Model again, but this time add the --framework tflite parameter

>> python save_model.py --weights ./data/yolov4.weights --output ./checkpoints/yolov4-416 --input_size 416 --model yolov4 --framework tflite

Convert TensorFlow Model to TensorFlow Lite Model

>> python convert_tflite.py --weights ./checkpoints/yolov4-416 --output ./checkpoints/yolov4-416.tflite

Test TFLite Model on video

>> python detectvideo.py --weights ./checkpoints/yolov4-416.tflite --size 416 --model yolov4 --video ./data/road.mp4 --framework tflite

And there you go. You have converted a YOLOv4 DarkNet model to a TFLite model.

The TFLite model is available at checkpoints/yolov4-416.tflite

Explore the github repository more here: https://github.com/hunglc007/tensorflow-yolov4-tflite

--

--

Raunak Singh Inventor

I have a passion for tinkering, coding, and hardware. OPEN-SOURCE Rules!!!