nareshmlx/opencv-pr huggingface dataset:
**File:** modules/dnn/src/dnn_common.hpp
**Change Type:** modified
**Context:** PR #21662: dnn: split dnn.cpp code - - extract `Net::Impl` interface into header (future PRs will add inheritance and plugin support) - `Net` methods ...
**Review Line:** 56

**Code Changes:**
```diff
+    // No guarantees that layer which support in-place computations
+    // will be computed in-place (input.data_ptr == output.data_ptr).
+    // If layer said that it could work in-place and layers after it
+    // no longer use input blob, we'll set output = input.
+    bool supportInPlace;
+    LayerShapes() {supportInPlace = false;}
+};
+
+
 #define CALL_MEMBER_FN(object, ptrToMemFn)  ((object).*(ptrToMemFn))
 
```

Review comment:
Initializer list?
**File:** modules/dnn/src/dnn_read.cpp
**Change Type:** added
**Context:** PR #21662: dnn: split dnn.cpp code - - extract `Net::Impl` interface into header (future PRs will add inheritance and plugin support) - `Net` methods ...
**Review Line:** 17

**Code Changes:**
```diff
+
+Net readNet(const String& _model, const String& _config, const String& _framework)
+{
+    String framework = toLowerCase(_framework);
+    String model = _model;
+    String config = _config;
+    const std::string modelExt = model.substr(model.rfind('.') + 1);
+    const std::string configExt = config.substr(config.rfind('.') + 1);
+    if (framework == "caffe" || modelExt == "caffemodel" || configExt == "caffemodel" || modelExt == "prototxt" || configExt == "prototxt")
+    {
+        if (modelExt == "prototxt" || configExt == "caffemodel")
```

Review comment:
If we make a copy of input parameters either way, it makes more sense to pass them by value instead(`const String& model` -> `String model`)
**File:** modules/dnn/src/dnn_read.cpp
**Change Type:** added
**Context:** PR #21662: dnn: split dnn.cpp code - - extract `Net::Impl` interface into header (future PRs will add inheritance and plugin support) - `Net` methods ...
**Review Line:** 68

**Code Changes:**
```diff
+    else if (framework == "darknet")
+        return readNetFromDarknet(bufferConfig, bufferModel);
+    else if (framework == "torch")
+        CV_Error(Error::StsNotImplemented, "Reading Torch models from buffers");
+    else if (framework == "dldt")
+        return readNetFromModelOptimizer(bufferConfig, bufferModel);
+    CV_Error(Error::StsError, "Cannot determine an origin framework with a name " + framework);
+}
+
+Net readNetFromModelOptimizer(const String& xml, const String& bin)
+{
```

Review comment:
We can also add onnx buffer support, which is useful for ONNXBackendAPI implementation. ```cpp else if (framework == "onnx") return readNetFromONNX(bufferModel); ```
**File:** modules/dnn/src/dnn_utils.cpp
**Change Type:** added
**Context:** PR #21662: dnn: split dnn.cpp code - - extract `Net::Impl` interface into header (future PRs will add inheritance and plugin support) - `Net` methods ...
**Review Line:** 64

**Code Changes:**
```diff
+            size = imgSize;
+        if (size != imgSize)
+        {
+            if (crop)
+            {
+                float resizeFactor = std::max(size.width / (float)imgSize.width,
+                        size.height / (float)imgSize.height);
+                resize(images[i], images[i], Size(), resizeFactor, resizeFactor, INTER_LINEAR);
+                Rect crop(Point(0.5 * (images[i].cols - size.width),
+                                  0.5 * (images[i].rows - size.height)),
+                        size);
```

Review comment:
I propose to use this opportunity to replace such instances of c-style casts witho static_casts everywhere. You can grep for (float), (int), etc.
**File:** modules/dnn/src/layer.cpp
**Change Type:** added
**Context:** PR #21662: dnn: split dnn.cpp code - - extract `Net::Impl` interface into header (future PRs will add inheritance and plugin support) - `Net` methods ...
**Review Line:** 12

**Code Changes:**
```diff
+namespace cv {
+namespace dnn {
+CV__DNN_INLINE_NS_BEGIN
+
+
+Layer::Layer() { preferableTarget = DNN_TARGET_CPU; }
+
+Layer::Layer(const LayerParams& params)
+    : blobs(params.blobs)
+    , name(params.name)
+    , type(params.type)
```

Review comment:
Initializer list?
**File:** modules/dnn/src/layer.cpp
**Change Type:** added
**Context:** PR #21662: dnn: split dnn.cpp code - - extract `Net::Impl` interface into header (future PRs will add inheritance and plugin support) - `Net` methods ...
**Review Line:** 19

**Code Changes:**
```diff
+Layer::Layer(const LayerParams& params)
+    : blobs(params.blobs)
+    , name(params.name)
+    , type(params.type)
+{
+    preferableTarget = DNN_TARGET_CPU;
+}
+
+void Layer::setParamsFrom(const LayerParams& params)
+{
+    blobs = params.blobs;
```

Review comment:
Initializer list?
**File:** modules/dnn/src/layer.cpp
**Change Type:** added
**Context:** PR #21662: dnn: split dnn.cpp code - - extract `Net::Impl` interface into header (future PRs will add inheritance and plugin support) - `Net` methods ...
**Review Line:** 107

**Code Changes:**
```diff
+static void vecToPVec(const std::vector<T>& v, std::vector<T*>& pv)
+{
+    pv.resize(v.size());
+    for (size_t i = 0; i < v.size(); i++)
+        pv[i] = const_cast<T*>(&v[i]);
+}
+
+void Layer::finalize(const std::vector<Mat>& inputs, std::vector<Mat>& outputs)
+{
+    CV_TRACE_FUNCTION();
+    this->finalize((InputArrayOfArrays)inputs, (OutputArrayOfArrays)outputs);
```

Review comment:
Why do we need a function with such strange signature? Maybe we can drop const from input vector or add const to pointers of output vector? (making it `std::vector<const T *>`)
**File:** modules/dnn/src/layer_factory.cpp
**Change Type:** added
**Context:** PR #21662: dnn: split dnn.cpp code - - extract `Net::Impl` interface into header (future PRs will add inheritance and plugin support) - `Net` methods ...
**Review Line:** 26

**Code Changes:**
```diff
+        cv::AutoLock lock(getInitializationMutex());
+        if (instance == NULL)
+            instance = new Mutex();
+    }
+    return *instance;
+}
+
+static LayerFactory_Impl& getLayerFactoryImpl_()
+{
+    static LayerFactory_Impl impl;
+    return impl;
```

Review comment:
We target 4.x, so we could also get rid of this in favor of ```cpp static Mutex instance; return instance; ```
**File:** modules/dnn/src/layer_factory.cpp
**Change Type:** added
**Context:** PR #21662: dnn: split dnn.cpp code - - extract `Net::Impl` interface into header (future PRs will add inheritance and plugin support) - `Net` methods ...
**Review Line:** 47

**Code Changes:**
```diff
+            instance = &getLayerFactoryImpl_();
+            initializeLayerFactory();
+        }
+    }
+    return *instance;
+}
+
+void LayerFactory::registerLayer(const String& type, Constructor constructor)
+{
+    CV_TRACE_FUNCTION();
+    CV_TRACE_ARG_VALUE(type, "type", type.c_str());
```

Review comment:
We should get rid of this as well for two reasons: 1) If two threads call this function, one of them can observe an empty factory. 2) There are no memory fences around instance pointer, so on the architectures with more relaxed memory model, it just shouldn't work. Proper refactoring will probably require changes of `CV_DNN_REGISTER_LAYER_CLASS` macro and a few signatures of public functions. We could do something like this: ```cpp LayerFactory_Impl& getLayerFactoryImpl() { static std::atomic<LayerFactory_Impl*> instance{nullptr}; static thread_local LayerFactory_Impl* init_ptr = nullptr; if (init_ptr != nullptr) { return *init_ptr; } if (instance == nullptr) { cv::AutoLock lock(getLayerFactoryMutex()); if (instance == nullptr) { init_ptr = &getLayerFactoryImpl_(); initializeLayerFactory(); instance = init_ptr; } } return *instance; } ``` But this workaround suffers from current design of public API and hence the code is too complex, imo.
**File:** modules/dnn/src/layer_internals.hpp
**Change Type:** added
**Context:** PR #21662: dnn: split dnn.cpp code - - extract `Net::Impl` interface into header (future PRs will add inheritance and plugin support) - `Net` methods ...
**Review Line:** 30

**Code Changes:**
```diff
+    }
+
+    bool equal(const LayerPin& r) const
+    {
+        return (lid == r.lid && oid == r.oid);
+    }
+
+    bool operator<(const LayerPin& r) const
+    {
+        return lid < r.lid || (lid == r.lid && oid < r.oid);
+    }
```

Review comment:
We have an operator ==, std::tie?
**File:** modules/dnn/src/legacy_backend.hpp
**Change Type:** added
**Context:** PR #21662: dnn: split dnn.cpp code - - extract `Net::Impl` interface into header (future PRs will add inheritance and plugin support) - `Net` methods ...
**Review Line:** 44

**Code Changes:**
```diff
+        hostDirty = false;
+    }
+
+    static Ptr<BackendWrapper> create(Mat& m)
+    {
+        return Ptr<BackendWrapper>(new OpenCLBackendWrapper(m));
+    }
+
+    static Ptr<BackendWrapper> create(const Ptr<BackendWrapper>& baseBuffer, Mat& m)
+    {
+        return Ptr<BackendWrapper>(new OpenCLBackendWrapper(baseBuffer, m));
```

Review comment:
Should we grep for new and replace it with makePtr?
**File:** modules/dnn/src/net_impl_backend.cpp
**Change Type:** added
**Context:** PR #21662: dnn: split dnn.cpp code - - extract `Net::Impl` interface into header (future PRs will add inheritance and plugin support) - `Net` methods ...
**Review Line:** 94

**Code Changes:**
```diff
+void Net::Impl::initBackend(const std::vector<LayerPin>& blobsToKeep_)
+{
+    CV_TRACE_FUNCTION();
+    if (preferableBackend == DNN_BACKEND_OPENCV)
+    {
+        CV_Assert(preferableTarget == DNN_TARGET_CPU || IS_DNN_OPENCL_TARGET(preferableTarget));
+    }
+    else if (preferableBackend == DNN_BACKEND_HALIDE)
+    {
+#ifdef HAVE_HALIDE
+        initHalideBackend();
```

Review comment:
We could add initOpenCVBackend() as well. This would help get rid of copies in situations where blob preparation is destructive, so we have to keep a copy for some other backend to act on.
**File:** modules/dnn/src/net_quantization.cpp
**Change Type:** added
**Context:** PR #21662: dnn: split dnn.cpp code - - extract `Net::Impl` interface into header (future PRs will add inheritance and plugin support) - `Net` methods ...
**Review Line:** 19

**Code Changes:**
```diff
+// FIXIT drop from inference API
+static
+void getQuantizationParams(const Mat& src, std::vector<float>& scales, std::vector<int>& zeropoints)
+{
+    const int qmin = -128; // INT8_MIN
+    const int qmax = 127;  // INT8_MAX
+
+    double rmin, rmax, sc, zp;
+    cv::minMaxIdx(src, &rmin, &rmax);
+
+    // 0 must be present in the range [rmin, rmax]
```

Review comment:
we can replace this magic constants
**File:** modules/dnn/src/dnn_common.hpp
**Change Type:** modified
**Context:** PR #21662: dnn: split dnn.cpp code - - extract `Net::Impl` interface into header (future PRs will add inheritance and plugin support) - `Net` methods ...
**Review Line:** 56

**Code Changes:**
```diff
+    // No guarantees that layer which support in-place computations
+    // will be computed in-place (input.data_ptr == output.data_ptr).
+    // If layer said that it could work in-place and layers after it
+    // no longer use input blob, we'll set output = input.
+    bool supportInPlace;
+    LayerShapes() {supportInPlace = false;}
+};
+
+
 #define CALL_MEMBER_FN(object, ptrToMemFn)  ((object).*(ptrToMemFn))
 
```

Review comment:
Code is moved without changes. No plan to refactor it now.
**File:** modules/dnn/include/opencv2/dnn/dnn.hpp
**Change Type:** modified
**Context:** PR #21692: add apply softmax option to ClassificationModel

**Code Changes:**
```diff
@@ -1310,6 +1310,9 @@ CV__DNN_INLINE_NS_BEGIN
      class CV_EXPORTS_W_SIMPLE ClassificationModel : public Model
      {
      public:
+         CV_DEPRECATED_EXTERNAL  // avoid using in C++ code, will be moved to "protected" (need to fix bindings first)
+         ClassificationModel();
+
          /**
           * @brief Create classification model from network represented in one of the supported formats.
           * An order of @p model and @p config arguments does not matter.
```

Review comment:
Usually it is written as `Softmax`/`softmax` (`max` is started from lowercase): What is about these names? - `enableSoftmaxPostProcessing` / `isEnabledSoftmaxPostProcessing` - `applySoftmaxPostProcessing` (? without getter)
**File:** modules/dnn/include/opencv2/dnn/dnn.hpp
**Change Type:** modified
**Context:** PR #21692: add apply softmax option to ClassificationModel

**Code Changes:**
```diff
@@ -1310,6 +1310,9 @@ CV__DNN_INLINE_NS_BEGIN
      class CV_EXPORTS_W_SIMPLE ClassificationModel : public Model
      {
      public:
+         CV_DEPRECATED_EXTERNAL  // avoid using in C++ code, will be moved to "protected" (need to fix bindings first)
+         ClassificationModel();
+
          /**
           * @brief Create classification model from network represented in one of the supported formats.
           * An order of @p model and @p config arguments does not matter.
```

Review comment:
We should not have internal fields in public headers. They should be moved into "Impl". See `DetectionModel_Impl` as example.
**File:** modules/dnn/src/model.cpp
**Change Type:** modified
**Context:** PR #21692: add apply softmax option to ClassificationModel

**Code Changes:**
```diff
@@ -197,28 +197,95 @@ void Model::predict(InputArray frame, OutputArrayOfArrays outs) const
 }
 
 
+class ClassificationModel_Impl : public Model::Impl
+{
+public:
+    virtual ~ClassificationModel_Impl() {}
+    ClassificationModel_Impl() : Impl() {}
+    ClassificationModel_Impl(const ClassificationModel_Impl&) = delete;
```

Review comment:
No need to use `cv::` in OpenCV sources - they are usually are part of cv namespace already.
**File:** modules/dnn/include/opencv2/dnn/dnn.hpp
**Change Type:** modified
**Context:** PR #21692: add apply softmax option to ClassificationModel

**Code Changes:**
```diff
@@ -1310,6 +1310,9 @@ CV__DNN_INLINE_NS_BEGIN
      class CV_EXPORTS_W_SIMPLE ClassificationModel : public Model
      {
      public:
+         CV_DEPRECATED_EXTERNAL  // avoid using in C++ code, will be moved to "protected" (need to fix bindings first)
+         ClassificationModel();
+
          /**
           * @brief Create classification model from network represented in one of the supported formats.
           * An order of @p model and @p config arguments does not matter.
```

Review comment:
It may be a bit redundant, I habe renamed set/get functions. `setEnableSoftmaxPostProcessing` / `getEnableSoftmaxPostProcessing`
**File:** modules/dnn/include/opencv2/dnn/dnn.hpp
**Change Type:** modified
**Context:** PR #21692: add apply softmax option to ClassificationModel

**Code Changes:**
```diff
@@ -1310,6 +1310,9 @@ CV__DNN_INLINE_NS_BEGIN
      class CV_EXPORTS_W_SIMPLE ClassificationModel : public Model
      {
      public:
+         CV_DEPRECATED_EXTERNAL  // avoid using in C++ code, will be moved to "protected" (need to fix bindings first)
+         ClassificationModel();
+
          /**
           * @brief Create classification model from network represented in one of the supported formats.
           * An order of @p model and @p config arguments does not matter.
```

Review comment:
I have implemented `ClassificationModel_Impl` and moved this variable..
**File:** modules/dnn/src/model.cpp
**Change Type:** modified
**Context:** PR #21692: add apply softmax option to ClassificationModel

**Code Changes:**
```diff
@@ -197,28 +197,95 @@ void Model::predict(InputArray frame, OutputArrayOfArrays outs) const
 }
 
 
+class ClassificationModel_Impl : public Model::Impl
+{
+public:
+    virtual ~ClassificationModel_Impl() {}
+    ClassificationModel_Impl() : Impl() {}
+    ClassificationModel_Impl(const ClassificationModel_Impl&) = delete;
```

Review comment:
I removed the explicit specification of namespace `cv::`.
**File:** modules/dnn/include/opencv2/dnn/dnn.hpp
**Change Type:** modified
**Context:** PR #21692: add apply softmax option to ClassificationModel

**Code Changes:**
```diff
@@ -1310,6 +1310,9 @@ CV__DNN_INLINE_NS_BEGIN
      class CV_EXPORTS_W_SIMPLE ClassificationModel : public Model
      {
      public:
+         CV_DEPRECATED_EXTERNAL  // avoid using in C++ code, will be moved to "protected" (need to fix bindings first)
+         ClassificationModel();
+
          /**
           * @brief Create classification model from network represented in one of the supported formats.
           * An order of @p model and @p config arguments does not matter.
```

Review comment:
Please exclude adding of new public API from this PR - this requires extra discussion.
**File:** modules/dnn/src/model.cpp
**Change Type:** modified
**Context:** PR #21692: add apply softmax option to ClassificationModel

**Code Changes:**
```diff
@@ -197,28 +197,95 @@ void Model::predict(InputArray frame, OutputArrayOfArrays outs) const
 }
 
 
+class ClassificationModel_Impl : public Model::Impl
+{
+public:
+    virtual ~ClassificationModel_Impl() {}
+    ClassificationModel_Impl() : Impl() {}
+    ClassificationModel_Impl(const ClassificationModel_Impl&) = delete;
```

Review comment:
Implementation details should be moved into `ClassificationModel_Impl::classify()`. `ClassificationModel::classify()` should perform as a thin wrapper.
**File:** modules/dnn/src/model.cpp
**Change Type:** modified
**Context:** PR #21692: add apply softmax option to ClassificationModel

**Code Changes:**
```diff
@@ -197,28 +197,95 @@ void Model::predict(InputArray frame, OutputArrayOfArrays outs) const
 }
 
 
+class ClassificationModel_Impl : public Model::Impl
+{
+public:
+    virtual ~ClassificationModel_Impl() {}
+    ClassificationModel_Impl() : Impl() {}
+    ClassificationModel_Impl(const ClassificationModel_Impl&) = delete;
```

Review comment:
BTW, `protected:` should be OK too
**File:** modules/dnn/src/model.cpp
**Change Type:** modified
**Context:** PR #21692: add apply softmax option to ClassificationModel

**Code Changes:**
```diff
@@ -197,28 +197,95 @@ void Model::predict(InputArray frame, OutputArrayOfArrays outs) const
 }
 
 
+class ClassificationModel_Impl : public Model::Impl
+{
+public:
+    virtual ~ClassificationModel_Impl() {}
+    ClassificationModel_Impl() : Impl() {}
+    ClassificationModel_Impl(const ClassificationModel_Impl&) = delete;
```

Review comment:
```.diff -Model(network) +Model() ``` as model is initialized below again.
**File:** modules/dnn/include/opencv2/dnn/dnn.hpp
**Change Type:** modified
**Context:** PR #21692: add apply softmax option to ClassificationModel

**Code Changes:**
```diff
@@ -1310,6 +1310,9 @@ CV__DNN_INLINE_NS_BEGIN
      class CV_EXPORTS_W_SIMPLE ClassificationModel : public Model
      {
      public:
+         CV_DEPRECATED_EXTERNAL  // avoid using in C++ code, will be moved to "protected" (need to fix bindings first)
+         ClassificationModel();
+
          /**
           * @brief Create classification model from network represented in one of the supported formats.
           * An order of @p model and @p config arguments does not matter.
```

Review comment:
I got it. Revert the last commit.
**File:** modules/dnn/src/model.cpp
**Change Type:** modified
**Context:** PR #21692: add apply softmax option to ClassificationModel

**Code Changes:**
```diff
@@ -197,28 +197,95 @@ void Model::predict(InputArray frame, OutputArrayOfArrays outs) const
 }
 
 
+class ClassificationModel_Impl : public Model::Impl
+{
+public:
+    virtual ~ClassificationModel_Impl() {}
+    ClassificationModel_Impl() : Impl() {}
+    ClassificationModel_Impl(const ClassificationModel_Impl&) = delete;
```

Review comment:
I got it. Change to protected from private.
**File:** modules/dnn/src/model.cpp
**Change Type:** modified
**Context:** PR #21692: add apply softmax option to ClassificationModel

**Code Changes:**
```diff
@@ -197,28 +197,95 @@ void Model::predict(InputArray frame, OutputArrayOfArrays outs) const
 }
 
 
+class ClassificationModel_Impl : public Model::Impl
+{
+public:
+    virtual ~ClassificationModel_Impl() {}
+    ClassificationModel_Impl() : Impl() {}
+    ClassificationModel_Impl(const ClassificationModel_Impl&) = delete;
```

Review comment:
I will fix it.
**File:** modules/dnn/src/model.cpp
**Change Type:** modified
**Context:** PR #21692: add apply softmax option to ClassificationModel

**Code Changes:**
```diff
@@ -197,28 +197,95 @@ void Model::predict(InputArray frame, OutputArrayOfArrays outs) const
 }
 
 
+class ClassificationModel_Impl : public Model::Impl
+{
+public:
+    virtual ~ClassificationModel_Impl() {}
+    ClassificationModel_Impl() : Impl() {}
+    ClassificationModel_Impl(const ClassificationModel_Impl&) = delete;
```

Review comment:
We don't need `softmax()` method in public `ClassificationModel`. Lets keep public APIs clear. We will discuss how to provide dedicated `softmax()` processing a bit later. There is no such issue with internal `ClassificationModel_Impl` as we don't have compatibility obligations there.
**File:** modules/dnn/src/model.cpp
**Change Type:** modified
**Context:** PR #21692: add apply softmax option to ClassificationModel

**Code Changes:**
```diff
@@ -197,28 +197,95 @@ void Model::predict(InputArray frame, OutputArrayOfArrays outs) const
 }
 
 
+class ClassificationModel_Impl : public Model::Impl
+{
+public:
+    virtual ~ClassificationModel_Impl() {}
+    ClassificationModel_Impl() : Impl() {}
+    ClassificationModel_Impl(const ClassificationModel_Impl&) = delete;
```

Review comment:
I understand. Remove softmax() function from Classification class.
**File:** modules/dnn/src/model.cpp
**Change Type:** modified
**Context:** PR #21692: add apply softmax option to ClassificationModel
**Review Line:** 246

**Code Changes:**
```diff
+        outblob.create(inblob.size(), inblob.type());
+
+        Mat exp;
+        const float max = *std::max_element(input.begin<float>(), input.end<float>());
+        cv::exp((input - max), exp);
+        outblob.getMat() = exp / cv::sum(exp)[0];
+    }
+
+protected:
+    bool applySoftmax = false;
+};
```

Review comment:
suspicious place
**File:** modules/dnn/src/dnn.cpp
**Change Type:** modified
**Context:** PR #21429: (3.4) dnn: fix API - explicit ctors, const methods - Validate: - [x] samples/dnn/dasiamrpn_tracker.py - [x] Halide build configuration - [x...
**Review Line:** 1410

**Code Changes:**
```diff
         if (it == layers.end())
             CV_Error(Error::StsObjectNotFound, format("Layer with requested id=%d not found", id));
 
-        return it->second;
+        return const_cast<LayerData&>(it->second);
     }
 
-    LayerData& getLayerData(const String &layerName)
+    LayerData& getLayerData(const String &layerName) const
     {
         int id = getLayerId(layerName);
```

Review comment:
We are returning non-const reference from const method. Why do we need that?
**File:** modules/dnn/src/dnn.cpp
**Change Type:** modified
**Context:** PR #21429: (3.4) dnn: fix API - explicit ctors, const methods - Validate: - [x] samples/dnn/dasiamrpn_tracker.py - [x] Halide build configuration - [x...

**Code Changes:**
```diff
@@ -846,11 +846,11 @@ struct BlobManager
     // layer blob.
     int numReferences(const LayerPin& lp)
     {
-        std::map<LayerPin, LayerPin>::iterator mapIt = reuseMap.find(lp);
+        std::map<LayerPin, LayerPin>::const_iterator mapIt = reuseMap.find(lp);
         CV_Assert(mapIt != reuseMap.end());
         LayerPin memHost = mapIt->second;
 
-        std::map<LayerPin, int>::iterator refIt = refCounter.find(memHost);
```

Review comment:
I think, we either should check that lid exists in layers, or mark layers as mutable, or don't mark this method as const. I think, the use of const_cast is unjustified here.