JeVois  1.23
JeVois Smart Embedded Machine Vision Toolkit
Share this page:
Loading...
Searching...
No Matches
Utils.H
Go to the documentation of this file.
1// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2//
3// JeVois Smart Embedded Machine Vision Toolkit - Copyright (C) 2020 by Laurent Itti, the University of Southern
4// California (USC), and iLab at USC. See http://iLab.usc.edu and http://jevois.org for information about this project.
5//
6// This file is part of the JeVois Smart Embedded Machine Vision Toolkit. This program is free software; you can
7// redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software
8// Foundation, version 2. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
10// License for more details. You should have received a copy of the GNU General Public License along with this program;
11// if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
12//
13// Contact information: Laurent Itti - 3641 Watt Way, HNB-07A - Los Angeles, CA 90089-2520 - USA.
14// Tel: +1 213 740 3527 - itti@pollux.usc.edu - http://iLab.usc.edu - http://jevois.org
15// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
16/*! \file */
17
18#pragma once
19
20#include <map>
21#include <string>
22#include <opencv2/core/core.hpp>
23#include <tensorflow/lite/c/common.h> // for TfLiteType
24#include <ovxlib/vsi_nn_pub.h> // for data types and quantization types
25
26#ifdef JEVOIS_PRO
27#include <hailo/hailort.h>
28#include <onnxruntime_cxx_api.h>
29#endif
30
31namespace jevois
32{
33 //! Deep neural networks
34 namespace dnn
35 {
36 /*! \defgroup dnn Tensor/Neural Processing networks
37
38 Classes and utilities to provide abstraction to deep neural networks. Provides interfacing to OpenCV backends
39 (CPU, OpenCL), tensor processing units (TPU) such as Coral Edge TPU and neural processing units (NPU) such as
40 Amlogic A311D NPU. */
41
42 /*! @{ */ // **********************************************************************
43
44 //! Get class labels from either a list or a file
45 /*! If arg corresponds to a file that exists (either absolute path or relative to JEVOIS_SHARE_PATH), then load the
46 classes from that file. Otherwise, set them from arg, which should then be a comma-separated list of values. */
47 std::map<int, std::string> getClassLabels(std::string const & arg);
48
49 //! Read a label file
50 /*! Two formats are allowed: one class name per line, or one class number followed by one class name per file.*/
51 std::map<int, std::string> readLabelsFile(std::string const & fname);
52
53 //! Get a label from an id
54 /*! If no entry is found in the map, return the id as a string (if namedonly is false) or an empty string (if
55 namedonly is true). */
56 std::string getLabel(std::map<int, std::string> const & labels, int id, bool namedonly = false);
57
58 //! Compute a color from a label name
59 int stringToRGBA(std::string const & label, unsigned char alpha = 128);
60
61 //! Get top-k entries and their indices
62 void topK(float const * pfProb, float * pfMaxProb, uint32_t * pMaxClass, uint32_t outputCount, uint32_t topNum);
63
64 //! Get a string of the form: "nD AxBxC... TYPE" from an n-dimensional cv::Mat with data type TYPE
65 std::string shapestr(cv::Mat const & m);
66
67 //! Get a string of the form: "nD AxBxC... TYPE" from an n-dimensional size vector and OpenCV data type TYPE
68 std::string shapestr(std::vector<size_t> dims, int typ);
69
70 //! Get a string of the form: "nD AxBxC... TYPE" from an n-dimensional size vector and OpenCV data type TYPE
71 std::string shapestr(std::vector<int> dims, int typ);
72
73 //! Get a string of the form: "nD AxBxC... TYPE" from an n-dimensional TfLiteTensor with data type TYPE
74 std::string shapestr(TfLiteTensor const * t);
75
76 //! Get a string of the form: "nD AxBxC... TYPE" from an n-dimensional NPU tensor with data type TYPE
77 std::string shapestr(vsi_nn_tensor_attr_t const & attr);
78
79 //! Get a vector of size_t from a string containing AxBxC...
80 std::vector<size_t> strshape(std::string const & str);
81
82 //! Convert from TensorFlow data type to OpenCV
83 int tf2cv(TfLiteType t);
84
85 //! Convert from TensorFlow data type to vsi_nn
86 vsi_nn_type_e tf2vsi(TfLiteType t);
87
88 //! Convert from NPU data type to OpenCV
89 int vsi2cv(vsi_nn_type_e t);
90
91 //! Clamp a rectangle to within given image width and height
92 void clamp(cv::Rect & r, int width, int height);
93
94 //! Clamp a rectangle to within given image width and height
95 void clamp(cv::Rect2f & r, float width, float height);
96
97 //! Parse tensor specification
98 /*! If the specification is empty, an empty vector is returned. Throws std::range_error on any parsing error. */
99 std::vector<vsi_nn_tensor_attr_t> parseTensorSpecs(std::string const & specs);
100
101 //! Construct a cv::Mat from attr and possibly data pointer
102 /*! If dataptr is nullptr, new memory will be allocated for the cv::Mat. Caller must ensure data outlives the
103 cv::Mat, and is responsible for eventually de-allocating the data. Usually, with non-null dataptr, this is only
104 to be used as a temporary re-casting, e.g., to recast a received tensor into a Mat before dequantizing it, then
105 forgetting about that Mat. */
106 cv::Mat attrmat(vsi_nn_tensor_attr_t const & attr, void * dataptr = nullptr);
107
108 //! Get a tensor dims as a vector of int, useful to construct a matching cv::Mat
109 std::vector<int> attrdims(vsi_nn_tensor_attr_t const & attr);
110
111 //! Get a tensor's (width, height) size in cv::Size format, skipping over other dimensions
112 cv::Size attrsize(vsi_nn_tensor_attr_t const & attr);
113
114 //! Get a string describing the specs of a tensor, including quantification specs (not provided by shapestr())
115 std::string attrstr(vsi_nn_tensor_attr_t const & attr);
116
117 //! Check that a cv::Mat blob matches exactly the spec of an attr
118 bool attrmatch(vsi_nn_tensor_attr_t const & attr, cv::Mat const & blob);
119
120 //! Get tensor shape and type attributes for a TensorFlow Lite tensor
121 vsi_nn_tensor_attr_t tensorattr(TfLiteTensor const * t);
122
123 //! Compute fast exponential using approximation formula
124 /*! From https://github.com/Qengineering/YoloV8-ncnn-Raspberry-Pi-4/blob/main/yoloV8.cpp */
125 float fastexp(float x);
126
127 //! Compute sigmoid using fastexp
128 float sigmoid(float x);
129
130 //! Compute sigmoid using fastexp on every pixel of a Mat of type CV_32F, in-place
131 void sigmoid(cv::Mat & m);
132
133 //! Apply softmax to a float vector
134 /*! n is the number of elements to process, stride is the increment in the arrays from one element to the next. So
135 the arrays should have size n * stride. Returns the index in [0..n*stride[ of the highest scoring element. If
136 maxonly is true, only output[returned index] is valid. */
137 size_t softmax(float const * input, size_t const n, size_t const stride, float const fac, float * output,
138 bool maxonly);
139
140 //! Compute softmax and return DFL distance
141 /*! src should have size n * stride. Note: even if stride > 1, dst should always have size n */
142 float softmax_dfl(float const * src, float * dst, size_t const n, size_t const stride = 1);
143
144 //! Quantize from float32 to fixed-point according to the quantization spec in attr
145 /*! m should be float32, typically normalized to [0..1[ or [-1..1[ already. attr is the desired quantized type and
146 method (DFP, AA, etc) */
147 cv::Mat quantize(cv::Mat const & m, vsi_nn_tensor_attr_t const & attr);
148
149 //! Dequantize an output to float32 according to the quantization spec in attr
150 /*! attr should have the type and quantization details of m, returned tensor is float32 */
151 cv::Mat dequantize(cv::Mat const & m, vsi_nn_tensor_attr_t const & attr);
152
153 //! Returns the number of non-unit dims in a cv::Mat
154 /*! For example, returns 2 for a 4D Mat with size 1x1x224x224, since it effectively is a 224x224 2D array */
155 size_t effectiveDims(cv::Mat const & m);
156
157 //! Concatenate several tensors into one
158 /*! Axis may be positive starting at 0 for the first dimension (when reading dims from left to right), or negative
159 starting at -1 for the last dimension. For example, for a 10x20x30 tensor, axis 0 has size 10 and is also axis
160 -3, axis 1 has size 20 and is also axis -2, and axis 2 has size 30 and is also axis -1. The input tensors must
161 all have the same number of dimensions, same pixel type, and sizes must match for all dimensions except the one
162 that is being concatenated. */
163 cv::Mat concatenate(std::vector<cv::Mat> const & tensors, int axis);
164
165 //! Split a tensor into several, along a given axis
166 /*! The sum of all given sizes must equal the original size along the selected axis. */
167 std::vector<cv::Mat> split(cv::Mat const & tensor, int axis, std::vector<int> const & sizes);
168
169#ifdef JEVOIS_PRO
170 //! Get a string of the form: "nD AxBxC... TYPE" from an n-dimensional Hailo tensor with data type TYPE
171 std::string shapestr(hailo_vstream_info_t const & vi);
172
173 //! Get tensor shape and type attributes for a Hailo tensor
174 vsi_nn_tensor_attr_t tensorattr(hailo_vstream_info_t const & vi);
175
176 //! Convert from Hailo data type to vsi_nn
177 vsi_nn_type_e hailo2vsi(hailo_format_type_t t);
178
179 //! Convert from ONNX-Runtime data type to vsi_nn
180 vsi_nn_type_e onnx2vsi(ONNXTensorElementDataType t);
181
182 //! Get a string of the form: "nD AxBxC... TYPE" from an n-dimensional ONNX tensor with data type TYPE
183 std::string shapestr(Ort::ConstTensorTypeAndShapeInfo const & ti);
184
185 //! Get tensor shape and type attributes for an ONNX-runtime tensor
186 vsi_nn_tensor_attr_t tensorattr(Ort::ConstTensorTypeAndShapeInfo const & ti);
187#endif
188
189 /*! @} */ // **********************************************************************
190
191
192 /*! \defgroup pydnn DNN-related processors written in python
193
194 In addition to writing DNN pre/net/post processors in C++, JeVois supports writing them in Python.
195
196 \ingroup dnn */
197
198
199 } // namespace dnn
200} // namespace jevois
201
202// Inlcude inlined functions implementation
203#include <jevois/DNN/details/UtilsImpl.H>
float fastexp(float x)
Compute fast exponential using approximation formula.
int tf2cv(TfLiteType t)
Convert from TensorFlow data type to OpenCV.
Definition Utils.C:327
std::map< int, std::string > getClassLabels(std::string const &arg)
Get class labels from either a list or a file.
Definition Utils.C:25
int vsi2cv(vsi_nn_type_e t)
Convert from NPU data type to OpenCV.
Definition Utils.C:349
size_t softmax(float const *input, size_t const n, size_t const stride, float const fac, float *output, bool maxonly)
Apply softmax to a float vector.
Definition Utils.C:733
vsi_nn_tensor_attr_t tensorattr(TfLiteTensor const *t)
Get tensor shape and type attributes for a TensorFlow Lite tensor.
Definition Utils.C:605
std::string getLabel(std::map< int, std::string > const &labels, int id, bool namedonly=false)
Get a label from an id.
Definition Utils.C:85
cv::Mat quantize(cv::Mat const &m, vsi_nn_tensor_attr_t const &attr)
Quantize from float32 to fixed-point according to the quantization spec in attr.
Definition Utils.C:816
std::map< int, std::string > readLabelsFile(std::string const &fname)
Read a label file.
Definition Utils.C:42
float sigmoid(float x)
Compute sigmoid using fastexp.
vsi_nn_type_e onnx2vsi(ONNXTensorElementDataType t)
Convert from ONNX-Runtime data type to vsi_nn.
Definition Utils.C:249
std::vector< cv::Mat > split(cv::Mat const &tensor, int axis, std::vector< int > const &sizes)
Split a tensor into several, along a given axis.
Definition Utils.C:997
std::vector< vsi_nn_tensor_attr_t > parseTensorSpecs(std::string const &specs)
Parse tensor specification.
Definition Utils.C:428
void clamp(cv::Rect &r, int width, int height)
Clamp a rectangle to within given image width and height.
Definition Utils.C:408
std::string attrstr(vsi_nn_tensor_attr_t const &attr)
Get a string describing the specs of a tensor, including quantification specs (not provided by shapes...
Definition Utils.C:553
float softmax_dfl(float const *src, float *dst, size_t const n, size_t const stride=1)
Compute softmax and return DFL distance.
Definition Utils.C:769
cv::Mat attrmat(vsi_nn_tensor_attr_t const &attr, void *dataptr=nullptr)
Construct a cv::Mat from attr and possibly data pointer.
Definition Utils.C:512
size_t effectiveDims(cv::Mat const &m)
Returns the number of non-unit dims in a cv::Mat.
Definition Utils.C:927
vsi_nn_type_e hailo2vsi(hailo_format_type_t t)
Convert from Hailo data type to vsi_nn.
Definition Utils.C:394
cv::Mat concatenate(std::vector< cv::Mat > const &tensors, int axis)
Concatenate several tensors into one.
Definition Utils.C:937
int stringToRGBA(std::string const &label, unsigned char alpha=128)
Compute a color from a label name.
Definition Utils.C:97
cv::Size attrsize(vsi_nn_tensor_attr_t const &attr)
Get a tensor's (width, height) size in cv::Size format, skipping over other dimensions.
Definition Utils.C:528
cv::Mat dequantize(cv::Mat const &m, vsi_nn_tensor_attr_t const &attr)
Dequantize an output to float32 according to the quantization spec in attr.
Definition Utils.C:888
vsi_nn_type_e tf2vsi(TfLiteType t)
Convert from TensorFlow data type to vsi_nn.
Definition Utils.C:371
void topK(float const *pfProb, float *pfMaxProb, uint32_t *pMaxClass, uint32_t outputCount, uint32_t topNum)
Get top-k entries and their indices.
Definition Utils.C:106
std::string shapestr(cv::Mat const &m)
Get a string of the form: "nD AxBxC... TYPE" from an n-dimensional cv::Mat with data type TYPE.
Definition Utils.C:126
std::vector< int > attrdims(vsi_nn_tensor_attr_t const &attr)
Get a tensor dims as a vector of int, useful to construct a matching cv::Mat.
Definition Utils.C:519
std::vector< size_t > strshape(std::string const &str)
Get a vector of size_t from a string containing AxBxC...
Definition Utils.C:318
bool attrmatch(vsi_nn_tensor_attr_t const &attr, cv::Mat const &blob)
Check that a cv::Mat blob matches exactly the spec of an attr.
Definition Utils.C:802
Main namespace for all JeVois classes and functions.
Definition Concepts.dox:2