1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5 // By downloading, copying, installing or using the software you agree to this license.
6 // If you do not agree to this license, do not download, install,
7 // copy or use the software.
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
19 // * Redistribution's of source code must retain the above copyright notice,
20 // this list of conditions and the following disclaimer.
22 // * Redistribution's in binary form must reproduce the above copyright notice,
23 // this list of conditions and the following disclaimer in the documentation
24 // and/or other materials provided with the distribution.
26 // * The name of the copyright holders may not be used to endorse or promote products
27 // derived from this software without specific prior written permission.
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // warranties of merchantability and fitness for a particular purpose are disclaimed.
32 // In no event shall the Intel Corporation or contributors be liable for any direct,
33 // indirect, incidental, special, exemplary, or consequential damages
34 // (including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort (including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
42 #ifndef OPENCV_DNN_DNN_HPP
43 #define OPENCV_DNN_DNN_HPP
46 #include <opencv2/core.hpp>
48 #if !defined CV_DOXYGEN && !defined CV_DNN_DONT_ADD_EXPERIMENTAL_NS
49 #define CV__DNN_EXPERIMENTAL_NS_BEGIN namespace experimental_dnn_v1 {
50 #define CV__DNN_EXPERIMENTAL_NS_END }
51 namespace cv { namespace dnn { namespace experimental_dnn_v1 { } using namespace experimental_dnn_v1; }}
53 #define CV__DNN_EXPERIMENTAL_NS_BEGIN
54 #define CV__DNN_EXPERIMENTAL_NS_END
57 #include <opencv2/dnn/dict.hpp>
61 CV__DNN_EXPERIMENTAL_NS_BEGIN
65 typedef std::vector<int> MatShape;
68 * @brief Enum of computation backends supported by layers.
77 * @brief Enum of target devices for computations.
85 /** @brief This class provides all data needed to initialize layer.
87 * It includes dictionary with scalar params (which can be readed by using Dict interface),
88 * blob params #blobs and optional meta information: #name and #type of layer instance.
90 class CV_EXPORTS LayerParams : public Dict
93 //TODO: Add ability to name blob params
94 std::vector<Mat> blobs; //!< List of learned parameters stored as blobs.
96 String name; //!< Name of the layer instance (optional, can be used internal purposes).
97 String type; //!< Type name which was used for creating layer by layer factory (optional).
101 * @brief Derivatives of this class encapsulates functions of certain backends.
106 BackendNode(int backendId);
108 virtual ~BackendNode(); //!< Virtual destructor to make polymorphism.
110 int backendId; //!< Backend identifier.
114 * @brief Derivatives of this class wraps cv::Mat for different backends and targets.
119 BackendWrapper(int backendId, int targetId);
122 * @brief Wrap cv::Mat for specific backend and target.
123 * @param[in] targetId Target identifier.
124 * @param[in] m cv::Mat for wrapping.
126 * Make CPU->GPU data transfer if it's require for the target.
128 BackendWrapper(int targetId, const cv::Mat& m);
131 * @brief Make wrapper for reused cv::Mat.
132 * @param[in] base Wrapper of cv::Mat that will be reused.
133 * @param[in] shape Specific shape.
135 * Initialize wrapper from another one. It'll wrap the same host CPU
136 * memory and mustn't allocate memory on device(i.e. GPU). It might
137 * has different shape. Use in case of CPU memory reusing for reuse
138 * associented memory on device too.
140 BackendWrapper(const Ptr<BackendWrapper>& base, const MatShape& shape);
142 virtual ~BackendWrapper(); //!< Virtual destructor to make polymorphism.
145 * @brief Transfer data to CPU host memory.
147 virtual void copyToHost() = 0;
150 * @brief Indicate that an actual data is on CPU.
152 virtual void setHostDirty() = 0;
154 int backendId; //!< Backend identifier.
155 int targetId; //!< Target identifier.
158 class CV_EXPORTS ActivationLayer;
159 class CV_EXPORTS BatchNormLayer;
160 class CV_EXPORTS ScaleLayer;
162 /** @brief This interface class allows to build new Layers - are building blocks of networks.
164 * Each class, derived from Layer, must implement allocate() methods to declare own outputs and forward() to compute outputs.
165 * Also before using the new layer into networks you must register your layer by using one of @ref dnnLayerFactory "LayerFactory" macros.
167 class CV_EXPORTS_W Layer : public Algorithm
171 //! List of learned parameters must be stored here to allow read them by using Net::getParam().
172 CV_PROP_RW std::vector<Mat> blobs;
174 /** @brief Computes and sets internal parameters according to inputs, outputs and blobs.
175 * @param[in] input vector of already allocated input blobs
176 * @param[out] output vector of already allocated output blobs
178 * If this method is called after network has allocated all memory for input and output blobs
179 * and before inferencing.
181 virtual void finalize(const std::vector<Mat*> &input, std::vector<Mat> &output);
183 /** @brief Given the @p input blobs, computes the output @p blobs.
184 * @param[in] input the input blobs.
185 * @param[out] output allocated output blobs, which will store results of the computation.
186 * @param[out] internals allocated internal blobs
188 virtual void forward(std::vector<Mat*> &input, std::vector<Mat> &output, std::vector<Mat> &internals) = 0;
190 /** @brief @overload */
191 CV_WRAP void finalize(const std::vector<Mat> &inputs, CV_OUT std::vector<Mat> &outputs);
193 /** @brief @overload */
194 CV_WRAP std::vector<Mat> finalize(const std::vector<Mat> &inputs);
196 /** @brief @overload */
197 CV_WRAP void forward(const std::vector<Mat> &inputs, CV_IN_OUT std::vector<Mat> &outputs,
198 CV_IN_OUT std::vector<Mat> &internals);
200 /** @brief Allocates layer and computes output. */
201 CV_WRAP void run(const std::vector<Mat> &inputs, CV_OUT std::vector<Mat> &outputs,
202 CV_IN_OUT std::vector<Mat> &internals);
204 /** @brief Returns index of input blob into the input array.
205 * @param inputName label of input blob
207 * Each layer input and output can be labeled to easily identify them using "%<layer_name%>[.output_name]" notation.
208 * This method maps label of input blob to its index into input vector.
210 virtual int inputNameToIndex(String inputName);
211 /** @brief Returns index of output blob in output array.
212 * @see inputNameToIndex()
214 virtual int outputNameToIndex(String outputName);
217 * @brief Ask layer if it support specific backend for doing computations.
218 * @param[in] backendId computation backend identifier.
221 virtual bool supportBackend(int backendId);
224 * @brief Returns Halide backend node.
225 * @param[in] inputs Input Halide buffers.
226 * @see BackendNode, BackendWrapper
228 * Input buffers should be exactly the same that will be used in forward invocations.
229 * Despite we can use Halide::ImageParam based on input shape only,
230 * it helps prevent some memory management issues (if something wrong,
231 * Halide tests will be failed).
233 virtual Ptr<BackendNode> initHalide(const std::vector<Ptr<BackendWrapper> > &inputs);
236 * @brief Automatic Halide scheduling based on layer hyper-parameters.
237 * @param[in] node Backend node with Halide functions.
238 * @param[in] inputs Blobs that will be used in forward invocations.
239 * @param[in] outputs Blobs that will be used in forward invocations.
240 * @param[in] targetId Target identifier
241 * @see BackendNode, Target
243 * Layer don't use own Halide::Func members because we can have applied
244 * layers fusing. In this way the fused function should be scheduled.
246 virtual void applyHalideScheduler(Ptr<BackendNode>& node,
247 const std::vector<Mat*> &inputs,
248 const std::vector<Mat> &outputs,
252 * @brief Implement layers fusing.
253 * @param[in] node Backend node of bottom layer.
256 * Actual for graph-based backends. If layer attached successfully,
257 * returns non-empty cv::Ptr to node of the same backend.
258 * Fuse only over the last function.
260 virtual Ptr<BackendNode> tryAttach(const Ptr<BackendNode>& node);
263 * @brief Tries to attach to the layer the subsequent activation layer, i.e. do the layer fusion in a partial case.
264 * @param[in] layer The subsequent activation layer.
266 * Returns true if the activation layer has been attached successfully.
268 virtual bool setActivation(const Ptr<ActivationLayer>& layer);
271 * @brief Tries to attach to the layer the subsequent batch normalization layer, i.e. do the layer fusion in a partial case.
272 * @param[in] layer The subsequent batch normalization layer.
274 * Returns true if the batch normalization layer has been attached successfully.
276 virtual bool setBatchNorm(const Ptr<BatchNormLayer>& layer);
279 * @brief Tries to attach to the layer the subsequent scaling layer, i.e. do the layer fusion in a partial case.
280 * @param[in] layer The subsequent scaling layer.
282 * Returns true if the scaling layer has been attached successfully.
284 virtual bool setScale(const Ptr<ScaleLayer>& layer);
287 * @brief "Deattaches" all the layers, attached to particular layer.
289 virtual void unsetAttached();
291 virtual bool getMemoryShapes(const std::vector<MatShape> &inputs,
292 const int requiredOutputs,
293 std::vector<MatShape> &outputs,
294 std::vector<MatShape> &internals) const;
295 virtual int64 getFLOPS(const std::vector<MatShape> &inputs,
296 const std::vector<MatShape> &outputs) const {(void)inputs; (void)outputs; return 0;}
298 CV_PROP String name; //!< Name of the layer instance, can be used for logging or other internal purposes.
299 CV_PROP String type; //!< Type name which was used for creating layer by layer factory.
302 explicit Layer(const LayerParams ¶ms); //!< Initializes only #name, #type and #blobs fields.
303 void setParamsFrom(const LayerParams ¶ms); //!< Initializes only #name, #type and #blobs fields.
307 /** @brief This class allows to create and manipulate comprehensive artificial neural networks.
309 * Neural network is presented as directed acyclic graph (DAG), where vertices are Layer instances,
310 * and edges specify relationships between layers inputs and outputs.
312 * Each network layer has unique integer id and unique string name inside its network.
313 * LayerId can store either layer name or layer id.
315 * This class supports reference counting of its instances, i. e. copies point to the same instance.
317 class CV_EXPORTS_W_SIMPLE Net
321 CV_WRAP Net(); //!< Default constructor.
322 CV_WRAP ~Net(); //!< Destructor frees the net only if there aren't references to the net anymore.
324 /** Returns true if there are no layers in the network. */
325 CV_WRAP bool empty() const;
327 /** @brief Adds new layer to the net.
328 * @param name unique name of the adding layer.
329 * @param type typename of the adding layer (type must be registered in LayerRegister).
330 * @param params parameters which will be used to initialize the creating layer.
331 * @returns unique identifier of created layer, or -1 if a failure will happen.
333 int addLayer(const String &name, const String &type, LayerParams ¶ms);
334 /** @brief Adds new layer and connects its first input to the first output of previously added layer.
337 int addLayerToPrev(const String &name, const String &type, LayerParams ¶ms);
339 /** @brief Converts string name of the layer to the integer identifier.
340 * @returns id of the layer, or -1 if the layer wasn't found.
342 CV_WRAP int getLayerId(const String &layer);
344 CV_WRAP std::vector<String> getLayerNames() const;
346 /** @brief Container for strings and integers. */
347 typedef DictValue LayerId;
349 /** @brief Returns pointer to layer with specified id or name which the network use. */
350 CV_WRAP Ptr<Layer> getLayer(LayerId layerId);
352 /** @brief Returns pointers to input layers of specific layer. */
353 std::vector<Ptr<Layer> > getLayerInputs(LayerId layerId); // FIXIT: CV_WRAP
355 /** @brief Delete layer for the network (not implemented yet) */
356 CV_WRAP void deleteLayer(LayerId layer);
358 /** @brief Connects output of the first layer to input of the second layer.
359 * @param outPin descriptor of the first layer output.
360 * @param inpPin descriptor of the second layer input.
362 * Descriptors have the following template <DFN><layer_name>[.input_number]</DFN>:
363 * - the first part of the template <DFN>layer_name</DFN> is sting name of the added layer.
364 * If this part is empty then the network input pseudo layer will be used;
365 * - the second optional part of the template <DFN>input_number</DFN>
366 * is either number of the layer input, either label one.
367 * If this part is omitted then the first layer input will be used.
369 * @see setNetInputs(), Layer::inputNameToIndex(), Layer::outputNameToIndex()
371 CV_WRAP void connect(String outPin, String inpPin);
373 /** @brief Connects #@p outNum output of the first layer to #@p inNum input of the second layer.
374 * @param outLayerId identifier of the first layer
375 * @param inpLayerId identifier of the second layer
376 * @param outNum number of the first layer output
377 * @param inpNum number of the second layer input
379 void connect(int outLayerId, int outNum, int inpLayerId, int inpNum);
381 /** @brief Sets outputs names of the network input pseudo layer.
383 * Each net always has special own the network input pseudo layer with id=0.
384 * This layer stores the user blobs only and don't make any computations.
385 * In fact, this layer provides the only way to pass user data into the network.
386 * As any other layer, this layer can label its outputs and this function provides an easy way to do this.
388 CV_WRAP void setInputsNames(const std::vector<String> &inputBlobNames);
390 /** @brief Runs forward pass to compute output of layer with name @p outputName.
391 * @param outputName name for layer which output is needed to get
392 * @return blob for first output of specified layer.
393 * @details By default runs forward pass for the whole network.
395 CV_WRAP Mat forward(const String& outputName = String());
397 /** @brief Runs forward pass to compute output of layer with name @p outputName.
398 * @param outputBlobs contains all output blobs for specified layer.
399 * @param outputName name for layer which output is needed to get
400 * @details If @p outputName is empty, runs forward pass for the whole network.
402 CV_WRAP void forward(std::vector<Mat>& outputBlobs, const String& outputName = String());
404 /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames.
405 * @param outputBlobs contains blobs for first outputs of specified layers.
406 * @param outBlobNames names for layers which outputs are needed to get
408 CV_WRAP void forward(std::vector<Mat>& outputBlobs,
409 const std::vector<String>& outBlobNames);
411 /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames.
412 * @param outputBlobs contains all output blobs for each layer specified in @p outBlobNames.
413 * @param outBlobNames names for layers which outputs are needed to get
415 CV_WRAP void forward(std::vector<std::vector<Mat> >& outputBlobs,
416 const std::vector<String>& outBlobNames);
419 /** @brief Optimized forward.
420 * @warning Not implemented yet.
421 * @details Makes forward only those layers which weren't changed after previous forward().
423 void forwardOpt(LayerId toLayer);
425 void forwardOpt(const std::vector<LayerId> &toLayers);
428 * @brief Compile Halide layers.
429 * @param[in] scheduler Path to YAML file with scheduling directives.
430 * @see setPreferableBackend
432 * Schedule layers that support Halide backend. Then compile them for
433 * specific target. For layers that not represented in scheduling file
434 * or if no manual scheduling used at all, automatic scheduling will be applied.
436 CV_WRAP void setHalideScheduler(const String& scheduler);
439 * @brief Ask network to use specific computation backend where it supported.
440 * @param[in] backendId backend identifier.
443 CV_WRAP void setPreferableBackend(int backendId);
446 * @brief Ask network to make computations on specific target device.
447 * @param[in] targetId target identifier.
450 CV_WRAP void setPreferableTarget(int targetId);
452 /** @brief Sets the new value for the layer output blob
453 * @param name descriptor of the updating layer output blob.
454 * @param blob new blob.
455 * @see connect(String, String) to know format of the descriptor.
456 * @note If updating blob is not empty then @p blob must have the same shape,
457 * because network reshaping is not implemented yet.
459 CV_WRAP void setInput(const Mat &blob, const String& name = "");
461 /** @brief Sets the new value for the learned param of the layer.
462 * @param layer name or id of the layer.
463 * @param numParam index of the layer parameter in the Layer::blobs array.
464 * @param blob the new value.
466 * @note If shape of the new blob differs from the previous shape,
467 * then the following forward pass may fail.
469 CV_WRAP void setParam(LayerId layer, int numParam, const Mat &blob);
471 /** @brief Returns parameter blob of the layer.
472 * @param layer name or id of the layer.
473 * @param numParam index of the layer parameter in the Layer::blobs array.
476 CV_WRAP Mat getParam(LayerId layer, int numParam = 0);
478 /** @brief Returns indexes of layers with unconnected outputs.
480 CV_WRAP std::vector<int> getUnconnectedOutLayers() const;
481 /** @brief Returns input and output shapes for all layers in loaded model;
482 * preliminary inferencing isn't necessary.
483 * @param netInputShapes shapes for all input blobs in net input layer.
484 * @param layersIds output parameter for layer IDs.
485 * @param inLayersShapes output parameter for input layers shapes;
486 * order is the same as in layersIds
487 * @param outLayersShapes output parameter for output layers shapes;
488 * order is the same as in layersIds
490 CV_WRAP void getLayersShapes(const std::vector<MatShape>& netInputShapes,
491 CV_OUT std::vector<int>& layersIds,
492 CV_OUT std::vector<std::vector<MatShape> >& inLayersShapes,
493 CV_OUT std::vector<std::vector<MatShape> >& outLayersShapes) const;
496 CV_WRAP void getLayersShapes(const MatShape& netInputShape,
497 CV_OUT std::vector<int>& layersIds,
498 CV_OUT std::vector<std::vector<MatShape> >& inLayersShapes,
499 CV_OUT std::vector<std::vector<MatShape> >& outLayersShapes) const;
501 /** @brief Returns input and output shapes for layer with specified
502 * id in loaded model; preliminary inferencing isn't necessary.
503 * @param netInputShape shape input blob in net input layer.
504 * @param layerId id for layer.
505 * @param inLayerShapes output parameter for input layers shapes;
506 * order is the same as in layersIds
507 * @param outLayerShapes output parameter for output layers shapes;
508 * order is the same as in layersIds
510 void getLayerShapes(const MatShape& netInputShape,
512 CV_OUT std::vector<MatShape>& inLayerShapes,
513 CV_OUT std::vector<MatShape>& outLayerShapes) const; // FIXIT: CV_WRAP
516 void getLayerShapes(const std::vector<MatShape>& netInputShapes,
518 CV_OUT std::vector<MatShape>& inLayerShapes,
519 CV_OUT std::vector<MatShape>& outLayerShapes) const; // FIXIT: CV_WRAP
521 /** @brief Computes FLOP for whole loaded model with specified input shapes.
522 * @param netInputShapes vector of shapes for all net inputs.
523 * @returns computed FLOP.
525 CV_WRAP int64 getFLOPS(const std::vector<MatShape>& netInputShapes) const;
527 CV_WRAP int64 getFLOPS(const MatShape& netInputShape) const;
529 CV_WRAP int64 getFLOPS(const int layerId,
530 const std::vector<MatShape>& netInputShapes) const;
532 CV_WRAP int64 getFLOPS(const int layerId,
533 const MatShape& netInputShape) const;
535 /** @brief Returns list of types for layer used in model.
536 * @param layersTypes output parameter for returning types.
538 CV_WRAP void getLayerTypes(CV_OUT std::vector<String>& layersTypes) const;
540 /** @brief Returns count of layers of specified type.
541 * @param layerType type.
542 * @returns count of layers
544 CV_WRAP int getLayersCount(const String& layerType) const;
546 /** @brief Computes bytes number which are requered to store
547 * all weights and intermediate blobs for model.
548 * @param netInputShapes vector of shapes for all net inputs.
549 * @param weights output parameter to store resulting bytes for weights.
550 * @param blobs output parameter to store resulting bytes for intermediate blobs.
552 void getMemoryConsumption(const std::vector<MatShape>& netInputShapes,
553 CV_OUT size_t& weights, CV_OUT size_t& blobs) const; // FIXIT: CV_WRAP
555 CV_WRAP void getMemoryConsumption(const MatShape& netInputShape,
556 CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
558 CV_WRAP void getMemoryConsumption(const int layerId,
559 const std::vector<MatShape>& netInputShapes,
560 CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
562 CV_WRAP void getMemoryConsumption(const int layerId,
563 const MatShape& netInputShape,
564 CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
566 /** @brief Computes bytes number which are requered to store
567 * all weights and intermediate blobs for each layer.
568 * @param netInputShapes vector of shapes for all net inputs.
569 * @param layerIds output vector to save layer IDs.
570 * @param weights output parameter to store resulting bytes for weights.
571 * @param blobs output parameter to store resulting bytes for intermediate blobs.
573 void getMemoryConsumption(const std::vector<MatShape>& netInputShapes,
574 CV_OUT std::vector<int>& layerIds,
575 CV_OUT std::vector<size_t>& weights,
576 CV_OUT std::vector<size_t>& blobs) const; // FIXIT: CV_WRAP
578 void getMemoryConsumption(const MatShape& netInputShape,
579 CV_OUT std::vector<int>& layerIds,
580 CV_OUT std::vector<size_t>& weights,
581 CV_OUT std::vector<size_t>& blobs) const; // FIXIT: CV_WRAP
583 /** @brief Enables or disables layer fusion in the network.
584 * @param fusion true to enable the fusion, false to disable. The fusion is enabled by default.
586 CV_WRAP void enableFusion(bool fusion);
588 /** @brief Returns overall time for inference and timings (in ticks) for layers.
589 * Indexes in returned vector correspond to layers ids. Some layers can be fused with others,
590 * in this case zero ticks count will be return for that skipped layers.
591 * @param timings vector for tick timings for all layers.
592 * @return overall ticks for model inference.
594 CV_WRAP int64 getPerfProfile(CV_OUT std::vector<double>& timings);
602 * @deprecated Deprecated as external interface. Will be for internal needs only.
603 * @brief Small interface class for loading trained serialized models of different dnn-frameworks. */
604 class CV_EXPORTS_W Importer : public Algorithm
608 /** @brief Adds loaded layers into the @p net and sets connections between them. */
609 CV_DEPRECATED CV_WRAP virtual void populateNet(Net net) = 0;
615 * @deprecated Use @ref readNetFromCaffe instead.
616 * @brief Creates the importer of <a href="http://caffe.berkeleyvision.org">Caffe</a> framework network.
617 * @param prototxt path to the .prototxt file with text description of the network architecture.
618 * @param caffeModel path to the .caffemodel file with learned network.
619 * @returns Pointer to the created importer, NULL in failure cases.
621 CV_DEPRECATED CV_EXPORTS_W Ptr<Importer> createCaffeImporter(const String &prototxt, const String &caffeModel = String());
623 /** @brief Reads a network model stored in Caffe model files.
624 * @details This is shortcut consisting from createCaffeImporter and Net::populateNet calls.
626 CV_EXPORTS_W Net readNetFromCaffe(const String &prototxt, const String &caffeModel = String());
628 /** @brief Reads a network model stored in Tensorflow model file.
629 * @details This is shortcut consisting from createTensorflowImporter and Net::populateNet calls.
631 CV_EXPORTS_W Net readNetFromTensorflow(const String &model);
633 /** @brief Reads a network model stored in Torch model file.
634 * @details This is shortcut consisting from createTorchImporter and Net::populateNet calls.
636 CV_EXPORTS_W Net readNetFromTorch(const String &model, bool isBinary = true);
639 * @deprecated Use @ref readNetFromTensorflow instead.
640 * @brief Creates the importer of <a href="http://www.tensorflow.org">TensorFlow</a> framework network.
641 * @param model path to the .pb file with binary protobuf description of the network architecture.
642 * @returns Pointer to the created importer, NULL in failure cases.
644 CV_DEPRECATED CV_EXPORTS_W Ptr<Importer> createTensorflowImporter(const String &model);
647 * @deprecated Use @ref readNetFromTorch instead.
648 * @brief Creates the importer of <a href="http://torch.ch">Torch7</a> framework network.
649 * @param filename path to the file, dumped from Torch by using torch.save() function.
650 * @param isBinary specifies whether the network was serialized in ascii mode or binary.
651 * @returns Pointer to the created importer, NULL in failure cases.
653 * @warning Torch7 importer is experimental now, you need explicitly set CMake `opencv_dnn_BUILD_TORCH_IMPORTER` flag to compile its.
655 * @note Ascii mode of Torch serializer is more preferable, because binary mode extensively use `long` type of C language,
656 * which has various bit-length on different systems.
658 * The loading file must contain serialized <a href="https://github.com/torch/nn/blob/master/doc/module.md">nn.Module</a> object
659 * with importing network. Try to eliminate a custom objects from serialazing data to avoid importing errors.
661 * List of supported layers (i.e. object instances derived from Torch nn.Module class):
666 * - nn.SpatialConvolution
667 * - nn.SpatialMaxPooling, nn.SpatialAveragePooling
668 * - nn.ReLU, nn.TanH, nn.Sigmoid
670 * - nn.SoftMax, nn.LogSoftMax
672 * Also some equivalents of these classes from cunn, cudnn, and fbcunn may be successfully imported.
674 CV_DEPRECATED CV_EXPORTS_W Ptr<Importer> createTorchImporter(const String &filename, bool isBinary = true);
676 /** @brief Loads blob which was serialized as torch.Tensor object of Torch7 framework.
677 * @warning This function has the same limitations as createTorchImporter().
679 CV_EXPORTS_W Mat readTorchBlob(const String &filename, bool isBinary = true);
680 /** @brief Creates 4-dimensional blob from image. Optionally resizes and crops @p image from center,
681 * subtract @p mean values, scales values by @p scalefactor, swap Blue and Red channels.
682 * @param image input image (with 1- or 3-channels).
683 * @param size spatial size for output image
684 * @param mean scalar with mean values which are subtracted from channels. Values are intended
685 * to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true.
686 * @param scalefactor multiplier for @p image values.
687 * @param swapRB flag which indicates that swap first and last channels
688 * in 3-channel image is necessary.
689 * @details input image is resized so one side after resize is equal to corresponing
690 * dimension in @p size and another one is equal or larger. Then, crop from the center is performed.
691 * @returns 4-dimansional Mat with NCHW dimensions order.
693 CV_EXPORTS_W Mat blobFromImage(const Mat& image, double scalefactor=1.0, const Size& size = Size(),
694 const Scalar& mean = Scalar(), bool swapRB=true);
695 /** @brief Creates 4-dimensional blob from series of images. Optionally resizes and
696 * crops @p images from center, subtract @p mean values, scales values by @p scalefactor,
697 * swap Blue and Red channels.
698 * @param images input images (all with 1- or 3-channels).
699 * @param size spatial size for output image
700 * @param mean scalar with mean values which are subtracted from channels. Values are intended
701 * to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true.
702 * @param scalefactor multiplier for @p images values.
703 * @param swapRB flag which indicates that swap first and last channels
704 * in 3-channel image is necessary.
705 * @details input image is resized so one side after resize is equal to corresponing
706 * dimension in @p size and another one is equal or larger. Then, crop from the center is performed.
707 * @returns 4-dimansional Mat with NCHW dimensions order.
709 CV_EXPORTS_W Mat blobFromImages(const std::vector<Mat>& images, double scalefactor=1.0,
710 Size size = Size(), const Scalar& mean = Scalar(), bool swapRB=true);
712 /** @brief Convert all weights of Caffe network to half precision floating point.
713 * @param src Path to origin model from Caffe framework contains single
714 * precision floating point weights (usually has `.caffemodel` extension).
715 * @param dst Path to destination model with updated weights.
717 * @note Shrinked model has no origin float32 weights so it can't be used
718 * in origin Caffe framework anymore. However the structure of data
719 * is taken from NVidia's Caffe fork: https://github.com/NVIDIA/caffe.
720 * So the resulting model may be used there.
722 CV_EXPORTS_W void shrinkCaffeModel(const String& src, const String& dst);
726 CV__DNN_EXPERIMENTAL_NS_END
730 #include <opencv2/dnn/layer.hpp>
731 #include <opencv2/dnn/dnn.inl.hpp>
733 #endif /* OPENCV_DNN_DNN_HPP */