onnx.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. // This file is part of OpenCV project.
  2. // It is subject to the license terms in the LICENSE file found in the top-level directory
  3. // of this distribution and at http://opencv.org/license.html.
  4. //
  5. // Copyright (C) 2020-2021 Intel Corporation
  6. #ifndef OPENCV_GAPI_INFER_ONNX_HPP
  7. #define OPENCV_GAPI_INFER_ONNX_HPP
  8. #include <unordered_map>
  9. #include <string>
  10. #include <array>
  11. #include <tuple> // tuple, tuple_size
  12. #include <opencv2/gapi/opencv_includes.hpp>
  13. #include <opencv2/gapi/util/any.hpp>
  14. #include <opencv2/core/cvdef.h> // GAPI_EXPORTS
  15. #include <opencv2/gapi/gkernel.hpp> // GKernelPackage
  16. namespace cv {
  17. namespace gapi {
  18. /**
  19. * @brief This namespace contains G-API ONNX Runtime backend functions, structures, and symbols.
  20. */
  21. namespace onnx {
  22. GAPI_EXPORTS cv::gapi::GBackend backend();
  23. enum class TraitAs: int {
  24. TENSOR, //!< G-API traits an associated cv::Mat as a raw tensor
  25. // and passes dimensions as-is
  26. IMAGE //!< G-API traits an associated cv::Mat as an image so
  27. // creates an "image" blob (NCHW/NHWC, etc)
  28. };
  29. using PostProc = std::function<void(const std::unordered_map<std::string, cv::Mat> &,
  30. std::unordered_map<std::string, cv::Mat> &)>;
  31. namespace detail {
  32. /**
  33. * @brief This structure contains description of inference parameters
  34. * which is specific to ONNX models.
  35. */
  36. struct ParamDesc {
  37. std::string model_path; //!< Path to model.
  38. // NB: nun_* may differ from topology's real input/output port numbers
  39. // (e.g. topology's partial execution)
  40. std::size_t num_in; //!< How many inputs are defined in the operation
  41. std::size_t num_out; //!< How many outputs are defined in the operation
  42. // NB: Here order follows the `Net` API
  43. std::vector<std::string> input_names; //!< Names of input network layers.
  44. std::vector<std::string> output_names; //!< Names of output network layers.
  45. using ConstInput = std::pair<cv::Mat, TraitAs>;
  46. std::unordered_map<std::string, ConstInput> const_inputs; //!< Map with pair of name of network layer and ConstInput which will be associated with this.
  47. std::vector<cv::Scalar> mean; //!< Mean values for preprocessing.
  48. std::vector<cv::Scalar> stdev; //!< Standard deviation values for preprocessing.
  49. std::vector<cv::GMatDesc> out_metas; //!< Out meta information about your output (type, dimension).
  50. PostProc custom_post_proc; //!< Post processing function.
  51. std::vector<bool> normalize; //!< Vector of bool values that enabled or disabled normalize of input data.
  52. std::vector<std::string> names_to_remap; //!< Names of output layers that will be processed in PostProc function.
  53. };
  54. } // namespace detail
  55. template<typename Net>
  56. struct PortCfg {
  57. using In = std::array
  58. < std::string
  59. , std::tuple_size<typename Net::InArgs>::value >;
  60. using Out = std::array
  61. < std::string
  62. , std::tuple_size<typename Net::OutArgs>::value >;
  63. using NormCoefs = std::array
  64. < cv::Scalar
  65. , std::tuple_size<typename Net::InArgs>::value >;
  66. using Normalize = std::array
  67. < bool
  68. , std::tuple_size<typename Net::InArgs>::value >;
  69. };
  70. /**
  71. * Contains description of inference parameters and kit of functions that
  72. * fill this parameters.
  73. */
  74. template<typename Net> class Params {
  75. public:
  76. /** @brief Class constructor.
  77. Constructs Params based on model information and sets default values for other
  78. inference description parameters.
  79. @param model Path to model (.onnx file).
  80. */
  81. Params(const std::string &model) {
  82. desc.model_path = model;
  83. desc.num_in = std::tuple_size<typename Net::InArgs>::value;
  84. desc.num_out = std::tuple_size<typename Net::OutArgs>::value;
  85. };
  86. /** @brief Specifies sequence of network input layers names for inference.
  87. The function is used to associate data of graph inputs with input layers of
  88. network topology. Number of names has to match the number of network inputs. If a network
  89. has only one input layer, there is no need to call it as the layer is
  90. associated with input automatically but this doesn't prevent you from
  91. doing it yourself. Count of names has to match to number of network inputs.
  92. @param layer_names std::array<std::string, N> where N is the number of inputs
  93. as defined in the @ref G_API_NET. Contains names of input layers.
  94. @return the reference on modified object.
  95. */
  96. Params<Net>& cfgInputLayers(const typename PortCfg<Net>::In &layer_names) {
  97. desc.input_names.assign(layer_names.begin(), layer_names.end());
  98. return *this;
  99. }
  100. /** @brief Specifies sequence of output layers names for inference.
  101. The function is used to associate data of graph outputs with output layers of
  102. network topology. If a network has only one output layer, there is no need to call it
  103. as the layer is associated with output automatically but this doesn't prevent
  104. you from doing it yourself. Count of names has to match to number of network
  105. outputs or you can set your own output but for this case you have to
  106. additionally use @ref cfgPostProc function.
  107. @param layer_names std::array<std::string, N> where N is the number of outputs
  108. as defined in the @ref G_API_NET. Contains names of output layers.
  109. @return the reference on modified object.
  110. */
  111. Params<Net>& cfgOutputLayers(const typename PortCfg<Net>::Out &layer_names) {
  112. desc.output_names.assign(layer_names.begin(), layer_names.end());
  113. return *this;
  114. }
  115. /** @brief Sets a constant input.
  116. The function is used to set constant input. This input has to be
  117. a prepared tensor since preprocessing is disabled for this case. You should
  118. provide name of network layer which will receive provided data.
  119. @param layer_name Name of network layer.
  120. @param data cv::Mat that contains data which will be associated with network layer.
  121. @param hint Type of input (TENSOR).
  122. @return the reference on modified object.
  123. */
  124. Params<Net>& constInput(const std::string &layer_name,
  125. const cv::Mat &data,
  126. TraitAs hint = TraitAs::TENSOR) {
  127. desc.const_inputs[layer_name] = {data, hint};
  128. return *this;
  129. }
  130. /** @brief Specifies mean value and standard deviation for preprocessing.
  131. The function is used to set mean value and standard deviation for preprocessing
  132. of input data.
  133. @param m std::array<cv::Scalar, N> where N is the number of inputs
  134. as defined in the @ref G_API_NET. Contains mean values.
  135. @param s std::array<cv::Scalar, N> where N is the number of inputs
  136. as defined in the @ref G_API_NET. Contains standard deviation values.
  137. @return the reference on modified object.
  138. */
  139. Params<Net>& cfgMeanStd(const typename PortCfg<Net>::NormCoefs &m,
  140. const typename PortCfg<Net>::NormCoefs &s) {
  141. desc.mean.assign(m.begin(), m.end());
  142. desc.stdev.assign(s.begin(), s.end());
  143. return *this;
  144. }
  145. /** @brief Configures graph output and provides the post processing function from user.
  146. The function is used when you work with networks with dynamic outputs.
  147. Since we can't know dimensions of inference result needs provide them for
  148. construction of graph output. This dimensions can differ from inference result.
  149. So you have to provide @ref PostProc function that gets information from inference
  150. result and fill output which is constructed by dimensions from out_metas.
  151. @param out_metas Out meta information about your output (type, dimension).
  152. @param remap_function Post processing function, which has two parameters. First is onnx
  153. result, second is graph output. Both parameters is std::map that contain pair of
  154. layer's name and cv::Mat.
  155. @return the reference on modified object.
  156. */
  157. Params<Net>& cfgPostProc(const std::vector<cv::GMatDesc> &out_metas,
  158. const PostProc &remap_function) {
  159. desc.out_metas = out_metas;
  160. desc.custom_post_proc = remap_function;
  161. return *this;
  162. }
  163. /** @overload
  164. Function with a rvalue parameters.
  165. @param out_metas rvalue out meta information about your output (type, dimension).
  166. @param remap_function rvalue post processing function, which has two parameters. First is onnx
  167. result, second is graph output. Both parameters is std::map that contain pair of
  168. layer's name and cv::Mat.
  169. @return the reference on modified object.
  170. */
  171. Params<Net>& cfgPostProc(std::vector<cv::GMatDesc> &&out_metas,
  172. PostProc &&remap_function) {
  173. desc.out_metas = std::move(out_metas);
  174. desc.custom_post_proc = std::move(remap_function);
  175. return *this;
  176. }
  177. /** @overload
  178. The function has additional parameter names_to_remap. This parameter provides
  179. information about output layers which will be used for inference and post
  180. processing function.
  181. @param out_metas Out meta information.
  182. @param remap_function Post processing function.
  183. @param names_to_remap Names of output layers. network's inference will
  184. be done on these layers. Inference's result will be processed in post processing
  185. function using these names.
  186. @return the reference on modified object.
  187. */
  188. Params<Net>& cfgPostProc(const std::vector<cv::GMatDesc> &out_metas,
  189. const PostProc &remap_function,
  190. const std::vector<std::string> &names_to_remap) {
  191. desc.out_metas = out_metas;
  192. desc.custom_post_proc = remap_function;
  193. desc.names_to_remap = names_to_remap;
  194. return *this;
  195. }
  196. /** @overload
  197. Function with a rvalue parameters and additional parameter names_to_remap.
  198. @param out_metas rvalue out meta information.
  199. @param remap_function rvalue post processing function.
  200. @param names_to_remap rvalue names of output layers. network's inference will
  201. be done on these layers. Inference's result will be processed in post processing
  202. function using these names.
  203. @return the reference on modified object.
  204. */
  205. Params<Net>& cfgPostProc(std::vector<cv::GMatDesc> &&out_metas,
  206. PostProc &&remap_function,
  207. std::vector<std::string> &&names_to_remap) {
  208. desc.out_metas = std::move(out_metas);
  209. desc.custom_post_proc = std::move(remap_function);
  210. desc.names_to_remap = std::move(names_to_remap);
  211. return *this;
  212. }
  213. /** @brief Specifies normalize parameter for preprocessing.
  214. The function is used to set normalize parameter for preprocessing of input data.
  215. @param normalizations std::array<cv::Scalar, N> where N is the number of inputs
  216. as defined in the @ref G_API_NET. Сontains bool values that enabled or disabled
  217. normalize of input data.
  218. @return the reference on modified object.
  219. */
  220. Params<Net>& cfgNormalize(const typename PortCfg<Net>::Normalize &normalizations) {
  221. desc.normalize.assign(normalizations.begin(), normalizations.end());
  222. return *this;
  223. }
  224. // BEGIN(G-API's network parametrization API)
  225. GBackend backend() const { return cv::gapi::onnx::backend(); }
  226. std::string tag() const { return Net::tag(); }
  227. cv::util::any params() const { return { desc }; }
  228. // END(G-API's network parametrization API)
  229. protected:
  230. detail::ParamDesc desc;
  231. };
  232. } // namespace onnx
  233. } // namespace gapi
  234. } // namespace cv
  235. #endif // OPENCV_GAPI_INFER_HPP