1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-31 00:03:03 +04:00

Merge pull request #28963 from abhishek-gola:custom_layers

Added custom layer support in new DNN engine #28963

Closes: https://github.com/opencv/opencv/issues/26200
Merge with: https://github.com/opencv/opencv_extra/pull/1358

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [x] The feature is well documented and sample code can be built with the project CMake
This commit is contained in:
Abhishek Gola
2026-05-13 13:01:25 +05:30
committed by GitHub
parent 72e0bc2bf3
commit 914c0b2bc8
3 changed files with 168 additions and 3 deletions
@@ -202,6 +202,36 @@ Next we register a layer and try to import the model.
@snippet dnn/custom_layers.hpp Register ResizeBilinearLayer
## Example: custom layer from ONNX
ONNX groups operators into **domains**. The standard operators live in the
default domain `ai.onnx`; vendors and exporters often place their own ops in a
named domain such as `my.namespace`. When OpenCV imports an ONNX node, it looks
the op up in cv::dnn::LayerFactory by:
- the op_type alone, for nodes in the default `ai.onnx` domain (or no domain), and
- `"<domain>.<op_type>"`, for nodes in any non-default domain.
Node attributes are passed through to the layer constructor as
cv::dnn::LayerParams entries with the same names. Consider an op `MyCustomOp`
with attributes `scale` and `bias` that computes `y = scale * x + bias`. The
implementation can look like:
@snippet dnn/custom_layer_onnx.cpp CustomScaleBiasLayer
To import a model that uses this op, register the layer **before** calling
cv::dnn::readNetFromONNX. Use cv::dnn::LayerFactory::registerLayer for runtime
registration (and cv::dnn::LayerFactory::unregisterLayer when done) — pick the
right key for the domain of the op as described above:
@snippet dnn/custom_layer_onnx.cpp Register CustomScaleBiasLayer
A complete runnable example is available at
[samples/dnn/custom_layer_onnx.cpp](https://github.com/opencv/opencv/tree/5.x/samples/dnn/custom_layer_onnx.cpp).
Tiny ONNX models exercising both the default-domain and custom-domain registration
paths can be generated with
[generate_custom_layer_models.py](https://github.com/opencv/opencv_extra/tree/5.x/testdata/dnn/onnx/generate_custom_layer_models.py)
in the opencv_extra repository.
## Define a custom layer in Python
The following example shows how to customize OpenCV's layers in Python.