[OpenCV DNN] How to hard code my network layers and weights into CPP files?

Hi, I am looking for a way to hard code my network layers and weights into CPP files, so that my program can be distributed in a unified format, instead of having separated files for network definition and weights.

I have already transfered network weights from PyTorch .pth format to variables in CPP files, such as float conv1_1_w[out_channels * in_channels * ks * ks]. And I also find some APIs that may help: cv::dnn::Net and cv::dnn::Net.addLayers for building the network and initializing network parameters.

However, I could not find any examples from either OpenCV’s tutorial or Googling. Everybody is talking loading networks from the packed model files. Could you kindly provide some quick and easy examples for me to do this?


I am not familiar with the dnn module. I think you’ll want to take a look at LayerParams. there might be convenience functions that let you build up a network and its weights from data in memory…

I hope that someone who is familiar with the dnn module will answer you yet.

Thanks for your reply. I also found this API, but struggled for setting up its parameters, for example I don’t know how to construct the blob, I don’t know its storage format in memory, which is not covered in the documentation. Hope someone (maybe the dev team) can explain this or give a simple and quick example for me to verify that.

they won’t look here. they’re exclusively on github, developing and working on issues.

your best bet would be to investigate the source code. if there isn’t an API to do what you want, you could propose it as a feature (on github). maybe someone will pick it up and implement it.

Thanks very much for your information. I think I am going to file an issue on Github while looking into the source code.