OpenCV DNN module only support inference model but not training model. If you want to use your own trained convolutional neural networks (CNN), you need to use deep learning frame works such as Tensorflow, Caffe, Torch, and to export it to OpenCV.
Here are sample codes to train CNN model with PyTorch and to use it with OpenCV, following the steps below:
- Train CNN model with PyTorch and save it. (train_LeNet.py)
- Create CNN model for inference and load trained parameters. (save_LeNet_ONNX.py)
- Save Inference model as ONNX format file. (save_LeNet_ONNX.py)
- Load ONNX file from OpenCV. (opencv_LeNet.cpp)
These sample codes train LeNET5 with MNIST dataset. I confirmed this code in following environment:
- Ubuntu 18.04
- Python 3.6
- OpenCV 4.3 (C++)
- PyTorch 1.4.0 + torchvision 0.5.0
If you want to train Keras+Tensorflow model and export it to OpenCV, see below: