In this tutorial you will learn how to use the 'dnn_superres' interface to upscale an image via a multi-output pre-trained neural network. OpenCVs dnn module supports accessing multiple nodes in one inference, if the names of the nodes are given. Currently there is one model included that is capable of giving more output in one inference run, that is the LapSRN model. LapSRN supports multiple outputs with one forward pass. It can now support 2x, 4x, 8x, and (2x, 4x) and (2x, 4x, 8x) super-resolution. The uploaded trained model files have the following output node names:
- 2x model: NCHW_output
- 4x model: NCHW_output_2x, NCHW_output_4x
- 8x model: NCHW_output_2x, NCHW_output_4x, NCHW_output_8x
Building
When building OpenCV, run the following command to build all the contrib module:
Or only build the dnn_superres module:
Or make sure you check the dnn_superres module in the GUI version of CMake: cmake-gui.
Source Code of the sample
Run the sample code with the following command
Explanation
- Set header and namespaces #include <opencv2/dnn_superres.hpp>using namespace std;using namespace cv;using namespace dnn_superres;
Create the Dnn Superres object
DnnSuperResImpl sr;Instantiate a dnn super-resolution object.
Read the model
path = "models/LapSRN_x8.pb"sr.readModel(path);Read the model from the given path.
Set the model
sr.setModel("lapsrn", 8);Sets the algorithm and scaling factor. The last (largest) scaling factor should be given here.
Give the node names and scaling factors
std::vector<int> scales{2, 4, 8}std::vector<int> node_names{'NCHW_output_2x','NCHW_output_4x','NCHW_output_8x'}Set the scaling factors, and the output node names in the model.
Upscale an image
Mat img = cv::imread(img_path);std::vector<Mat> outputs;sr.upsampleMultioutput(img, outputs, scales, node_names);Run the inference. The output images will be stored in a Mat vector.