Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform deep copy with cv::dnn::Net?

I want to deep copy instance of cv::dnn::Net:

cv::dnn::Net n1 = cv::dnn::readNetFromONNX("");
cv::dnn::Net n2 = n1;

But this class uses implicit sharing, as I understand it. And I did not find any way to do this in documentation. Is there any possibility (some method copy(), for example) that allows to completely copy the instance?

like image 878
Ivanko Avatar asked Oct 17 '19 14:10

Ivanko


1 Answers

To find an answer to your question I have referred to OpenCV docs (for dnn module) and source.

There are no explicitly defined copy or move constructors (and copy operators) for cv::dnn::Net. This class is just the interface, the only data member is : pointer to implementation in its private part.

class CV_EXPORTS_W_SIMPLE Net
{
public:
    CV_WRAP Net();  //!< Default constructor.
    CV_WRAP ~Net(); //!< Destructor frees the net only if there aren't references to the net anymore.

...

private:
    struct Impl;
    Ptr<Impl> impl;
};

So you were right to point that there was no sense in creating copy of it in way cv::dnn::Net n2 = n1; since it simply creates another pointer to same implementation. And without any interface to this private pointer to implementation you can hardly access it without modifying sources.

You neither can use cv::dnn::Model (which inherits from cv::dnn::Net and allows to set input params) since it also just a pointer to implementation.

I can't imagine use case which requires usage of two different instances of the same network. Looks like OpenCV developers did the same.

To forward pass the network in multi-threaded environment you can call cv::dnn::Net::forwardAsync() but it only possible for intel inference engine backend. Attempt to call cv::dnn::Net::forward() from concurring threads will cause a run time error.

And you are free to create two nets from same config and model files, but again I can't imagine a use case for that (and forwardAsync() may give better performance due to inner design optimizations).

like image 94
f4f Avatar answered Sep 20 '22 15:09

f4f