JeVois  1.22
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 //! Read a label file
45 /*! Two formats are allowed: one class name per line, or one class number followed by one class name per file.*/
46 std::map<int, std::string> readLabelsFile(std::string const & fname);
47
48 //! Get a label from an id
49 /*! If no entry is found in the map, return the id as a string (if namedonly is false) or an empty string (if
50 namedonly is true). */
51 std::string getLabel(std::map<int, std::string> const & labels, int id, bool namedonly = false);
52
53 //! Compute a color from a label name
54 int stringToRGBA(std::string const & label, unsigned char alpha = 128);
55
56 //! Get top-k entries and their indices
57 void topK(float const * pfProb, float * pfMaxProb, uint32_t * pMaxClass, uint32_t outputCount, uint32_t topNum);
58
59 //! Get a string of the form: "nD AxBxC... TYPE" from an n-dimensional cv::Mat with data type TYPE
60 std::string shapestr(cv::Mat const & m);
61
62 //! Get a string of the form: "nD AxBxC... TYPE" from an n-dimensional size vector and OpenCV data type TYPE
63 std::string shapestr(std::vector<size_t> dims, int typ);
64
65 //! Get a string of the form: "nD AxBxC... TYPE" from an n-dimensional size vector and OpenCV data type TYPE
66 std::string shapestr(std::vector<int> dims, int typ);
67
68 //! Get a string of the form: "nD AxBxC... TYPE" from an n-dimensional TfLiteTensor with data type TYPE
69 std::string shapestr(TfLiteTensor const * t);
70
71 //! Get a string of the form: "nD AxBxC... TYPE" from an n-dimensional NPU tensor with data type TYPE
72 std::string shapestr(vsi_nn_tensor_attr_t const & attr);
73
74 //! Get a vector of size_t from a string containing AxBxC...
75 std::vector<size_t> strshape(std::string const & str);
76
77 //! Convert from TensorFlow data type to OpenCV
78 int tf2cv(TfLiteType t);
79
80 //! Convert from TensorFlow data type to vsi_nn
81 vsi_nn_type_e tf2vsi(TfLiteType t);
82
83 //! Convert from NPU data type to OpenCV
84 int vsi2cv(vsi_nn_type_e t);
85
86 //! Clamp a rectangle to within given image width and height
87 void clamp(cv::Rect & r, int width, int height);
88
89 //! Clamp a rectangle to within given image width and height
90 void clamp(cv::Rect2f & r, float width, float height);
91
92 //! Parse tensor specification
93 /*! If the specification is empty, an empty vector is returned. Throws std::range_error on any parsing error. */
94 std::vector<vsi_nn_tensor_attr_t> parseTensorSpecs(std::string const & specs);
95
96 //! Construct a cv::Mat from attr and possibly data pointer
97 /*! If dataptr is nullptr, new memory will be allocated for the cv::Mat. Caller must ensure data outlives the
98 cv::Mat, and is responsible for eventually de-allocating the data. Usually, with non-null dataptr, this is only
99 to be used as a temporary re-casting, e.g., to recast a received tensor into a Mat before dequantizing it, then
100 forgetting about that Mat. */
101 cv::Mat attrmat(vsi_nn_tensor_attr_t const & attr, void * dataptr = nullptr);
102
103 //! Get a tensor dims as a vector of int, useful to construct a matching cv::Mat
104 std::vector<int> attrdims(vsi_nn_tensor_attr_t const & attr);
105
106 //! Get a tensor's (width, height) size in cv::Size format, skipping over other dimensions
107 cv::Size attrsize(vsi_nn_tensor_attr_t const & attr);
108
109 //! Get a string describing the specs of a tensor, including quantification specs (not provided by shapestr())
110 std::string attrstr(vsi_nn_tensor_attr_t const & attr);
111
112 //! Check that a cv::Mat blob matches exactly the spec of an attr
113 bool attrmatch(vsi_nn_tensor_attr_t const & attr, cv::Mat const & blob);
114
115 //! Get tensor shape and type attributes for a TensorFlow Lite tensor
116 vsi_nn_tensor_attr_t tensorattr(TfLiteTensor const * t);
117
118 //! Compute fast exponential using approximation formula
119 /*! From https://github.com/Qengineering/YoloV8-ncnn-Raspberry-Pi-4/blob/main/yoloV8.cpp */
120 float fastexp(float x);
121
122 //! Compute sigmoid using fastexp
123 float sigmoid(float x);
124
125 //! Compute sigmoid using fastexp on every pixel of a Mat of type CV_32F, in-place
126 void sigmoid(cv::Mat & m);
127
128 //! Apply softmax to a float vector
129 /*! n is the number of elements to process, stride is the increment in the arrays from one element to the next. So
130 the arrays should have size n * stride. Returns the index in [0..n*stride[ of the highest scoring element. If
131 maxonly is true, only output[returned index] is valid. */
132 size_t softmax(float const * input, size_t const n, size_t const stride, float const fac, float * output,
133 bool maxonly);
134
135 //! Compute softmax and return DFL distance
136 /*! src should have size n * stride. Note: even if stride > 1, dst should always have size n */
137 float softmax_dfl(float const * src, float * dst, size_t const n, size_t const stride = 1);
138
139 //! Quantize from float32 to fixed-point according to the quantization spec in attr
140 /*! m should be float32, typically normalized to [0..1[ or [-1..1[ already. attr is the desired quantized type and
141 method (DFP, AA, etc) */
142 cv::Mat quantize(cv::Mat const & m, vsi_nn_tensor_attr_t const & attr);
143
144 //! Dequantize an output to float32 according to the quantization spec in attr
145 /*! attr should have the type and quantization details of m, returned tensor is float32 */
146 cv::Mat dequantize(cv::Mat const & m, vsi_nn_tensor_attr_t const & attr);
147
148 //! Returns the number of non-unit dims in a cv::Mat
149 /*! For example, returns 2 for a 4D Mat with size 1x1x224x224, since it effectively is a 224x224 2D array */
150 size_t effectiveDims(cv::Mat const & m);
151
152 //! Concatenate several tensors into one
153 /*! Axis may be positive starting at 0 for the first dimension (when reading dims from left to right), or negative
154 starting at -1 for the last dimension. For example, for a 10x20x30 tensor, axis 0 has size 10 and is also axis
155 -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
156 all have the same number of dimensions, same pixel type, and sizes must match for all dimensions except the one
157 that is being concatenated. */
158 cv::Mat concatenate(std::vector<cv::Mat> const & tensors, int axis);
159
160 //! Split a tensor into several, along a given axis
161 /*! The sum of all given sizes must equal the original size along the selected axis. */
162 std::vector<cv::Mat> split(cv::Mat const & tensor, int axis, std::vector<int> const & sizes);
163
164#ifdef JEVOIS_PRO
165 //! Get a string of the form: "nD AxBxC... TYPE" from an n-dimensional Hailo tensor with data type TYPE
166 std::string shapestr(hailo_vstream_info_t const & vi);
167
168 //! Get tensor shape and type attributes for a Hailo tensor
169 vsi_nn_tensor_attr_t tensorattr(hailo_vstream_info_t const & vi);
170
171 //! Convert from Hailo data type to vsi_nn
172 vsi_nn_type_e hailo2vsi(hailo_format_type_t t);
173
174 //! Convert from ONNX-Runtime data type to vsi_nn
175 vsi_nn_type_e onnx2vsi(ONNXTensorElementDataType t);
176
177 //! Get a string of the form: "nD AxBxC... TYPE" from an n-dimensional ONNX tensor with data type TYPE
178 std::string shapestr(Ort::ConstTensorTypeAndShapeInfo const & ti);
179
180 //! Get tensor shape and type attributes for an ONNX-runtime tensor
181 vsi_nn_tensor_attr_t tensorattr(Ort::ConstTensorTypeAndShapeInfo const & ti);
182#endif
183
184 /*! @} */ // **********************************************************************
185
186
187 /*! \defgroup pydnn DNN-related processors written in python
188
189 In addition to writing DNN pre/net/post processors in C++, JeVois supports writing them in Python.
190
191 \ingroup dnn */
192
193
194 } // namespace dnn
195} // namespace jevois
196
197// Inlcude inlined functions implementation
198#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:310
int vsi2cv(vsi_nn_type_e t)
Convert from NPU data type to OpenCV.
Definition Utils.C:332
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:716
vsi_nn_tensor_attr_t tensorattr(TfLiteTensor const *t)
Get tensor shape and type attributes for a TensorFlow Lite tensor.
Definition Utils.C:588
std::string getLabel(std::map< int, std::string > const &labels, int id, bool namedonly=false)
Get a label from an id.
Definition Utils.C:68
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:799
std::map< int, std::string > readLabelsFile(std::string const &fname)
Read a label file.
Definition Utils.C:25
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:232
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:980
std::vector< vsi_nn_tensor_attr_t > parseTensorSpecs(std::string const &specs)
Parse tensor specification.
Definition Utils.C:411
void clamp(cv::Rect &r, int width, int height)
Clamp a rectangle to within given image width and height.
Definition Utils.C:391
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:536
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:752
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:495
size_t effectiveDims(cv::Mat const &m)
Returns the number of non-unit dims in a cv::Mat.
Definition Utils.C:910
vsi_nn_type_e hailo2vsi(hailo_format_type_t t)
Convert from Hailo data type to vsi_nn.
Definition Utils.C:377
cv::Mat concatenate(std::vector< cv::Mat > const &tensors, int axis)
Concatenate several tensors into one.
Definition Utils.C:920
int stringToRGBA(std::string const &label, unsigned char alpha=128)
Compute a color from a label name.
Definition Utils.C:80
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:511
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:871
vsi_nn_type_e tf2vsi(TfLiteType t)
Convert from TensorFlow data type to vsi_nn.
Definition Utils.C:354
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:89
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:109
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:502
std::vector< size_t > strshape(std::string const &str)
Get a vector of size_t from a string containing AxBxC...
Definition Utils.C:301
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:785
Main namespace for all JeVois classes and functions.
Definition Concepts.dox:2