'How to convert YOLOv5 PyTorch model to OpenCV DNN compatible format

Could anybody please help me to convert YOLOv5 PyTorch model to ONNX or TensorFlow format to be able to use it with OpenCV C++ inference?

I used this tutorial to train the model with colab: https://blog.roboflow.com/how-to-train-yolov5-on-a-custom-dataset/

Maybe there is a way of conversion in colab or I should use any other tools?



Solution 1:[1]

pt model to onnx that is able to be read by OpenCV 4.5.4 is as follows:

python3 export.py --weights best.pt --include onnx --simplify

Solution 2:[2]

Below is the recent reply from ultralytics developers(YoloV5 creators) regarding OpenCV & YoloV5 compatibility. In fact I'm also looking for correct implementation tutorial.

? Original Thread

Good news ?! Your original issue may now be fixed ? in PR #4833 by @SamFC10. This PR implements architecture updates to allow for ONNX-exported YOLOv5 models to be used with OpenCV DNN.

To receive this update:

  • Gitgit pull from within your yolov5/ directory or git clone https://github.com/ultralytics/yolov5
  • PyTorch Hub – Force-reload with model = torch.hub.load('ultralytics/yolov5', 'yolov5s', force_reload=True)
  • Notebooks – View updated notebooks Open In Colab Open In Kaggle. Colab
  • Dockersudo docker pull ultralytics/yolov5:latest to update your image.

Thank you for spotting this issue and informing us of the problem. Please let us know if this update resolves the issue for you, and feel free to inform us of any other issues you discover or feature requests that come to mind. Happy trainings with YOLOv5 ?!

Solution 3:[3]

The best way is to use Google Colab where you don't have to worry about downloading huge chunks of data and fixing dependencies. You can use this notebook for converting models.

You can also check out this LearnOpenCV blog post for more details.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PauloM
Solution 2 Henry Ecker
Solution 3 Kukil Kashyap Borgohain