Finished training that sweet Pytorch model? Let’s learn how to load it on OpenCV!




Let’s start!

    Following the article I wrote previously: “How to load Tensorflow models with OpenCV” now it’s time to approach another widely used ML Library. But first  I’d like to make something clear here before we start: Pytorch is not Torch and for now, OpenCV does not support a direct load and use of Pytorch Models.

    But, there’s a way: a conversion to the ONNX format (which OpenCV supports). Have you ever heard of it?

    ONNX is an open format built to represent machine learning models. ONNX defines a common set of operators and a common file format to enable AI developers to use models with a variety of frameworks, tools, runtimes, and compilers.

    Basically, you can convert any model of any library that obeys the ONNX file standards.

 

Code time!

    I’ll separate the code in two (the complete implementation is at the end). The first part is related to model conversion. For simplification purposes, I’ll use a pre-trained one (Densenet 121). Please make sure to set the

onnx_model_path
variable.

 

 

    Now we have our model converted and saved as set on the onnx_model_path

variable. Time to test our converted model by loading it with OpenCV:

 

 

I’ll use Figure 1 to test the output:

 

Dalmation dog image for testing purposes

Figure 1 – Input image

 

The following output is generated:

 

Output of the script

Figure 2 – Output of the script

    Working, and predicting precisely our Dalmatian dog! As promised, the complete code with some small additions is available below, (and at my Github).

 

 

Sidenote: The latest OpenCV’s and Pytorch versions are 4.4 and 1.6 respectively, and there are some operations that the ONNX module still does not support, but that could change in the future. Learn more here. 

 

 

 

 

Have fun with your projects! 
If this post helped you, please consider buying me a coffee 🙂