JeVois  1.18
JeVois Smart Embedded Machine Vision Toolkit
Share this page:
Utils.H
Go to the documentation of this file.
1 // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 //
3 // JeVois Smart Embedded Machine Vision Toolkit - Copyright (C) 2016 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 <string>
21 #include <vector>
22 #include <type_traits> // for std::is_integral
23 #include <sstream>
24 #include <filesystem>
25 
26 //! Metadata V4L2 format used by Amlogic A311D camera ISP
27 #define ISP_V4L2_PIX_FMT_META v4l2_fourcc( 'M', 'E', 'T', 'A' )
28 
29 //! JeVois-Pro zero-copy display of camera input frame (to be used as output mode in VideoMapping)
30 /*! Note that the underlying mode is RGBA as used by MALI OpenGL */
31 #define JEVOISPRO_FMT_GUI v4l2_fourcc( 'J', 'V', 'U', 'I' )
32 
33 namespace jevois
34 {
35  /*! \defgroup utils Misc utilities
36 
37  Miscellaneous utility and helper functions. */
38 
39  /*! @{ */ // **********************************************************************
40 
41  //! Convert a V4L2 four-cc code (V4L2_PIX_FMT_...) to a 4-char string
42  std::string fccstr(unsigned int fcc);
43 
44  //! Convert cv::Mat::type() code to to a string (e.g., CV_8UC1, CV_32SC3, etc)
45  std::string cvtypestr(unsigned int cvtype);
46 
47  //! Return the number of bytes per pixel for a given OpenCV pixel type
48  unsigned int cvBytesPerPix(unsigned int cvtype);
49 
50  //! Convert a JeVois video format string to V4L2 four-cc code (V4L2_PIX_FMT_...)
51  /*! Throws a runtime_error if str is not one of: BAYER, YUYV, GREY, GRAY, MJPG, RGB565, BGR24 or NONE. */
52  unsigned int strfcc(std::string const & str);
53 
54  //! Return the number of bytes per pixel for a given V4L2_PIX_FMT_...
55  unsigned int v4l2BytesPerPix(unsigned int fcc);
56 
57  //! Return the image size in bytes for a given V4L2_PIX_FMT_..., width, height
58  unsigned int v4l2ImageSize(unsigned int fcc, unsigned int width, unsigned int height);
59 
60  //! Return a value that corresponds to black for the given video format
61  /*! The returned value is appropriate to use as the color value for the image drawing functions in \ref image and may
62  not always be zero. */
63  unsigned int blackColor(unsigned int fcc);
64 
65  //! Return a value that corresponds to white for the given video format
66  /*! The returned value is appropriate to use as the color value for the image drawing functions in \ref image. */
67  unsigned int whiteColor(unsigned int fcc);
68 
69  //! Apply a letterbox resizing to fit an image into a window
70  /*! Modify given image dims (imw,imh) so that the image fits inside window dims (winw,winh) while being as large as
71  possible but without modifying the image's aspect ratio. If noalias is specified, the scaling factor will be
72  rounded down to the nearest integer to prevent aliasing in the display. This may reduce the displayed image
73  size. For example, with a 1920x1080 window, a 640x480 image would be letterboxed to 1440x1080 when noalias is
74  false. But that is a scaling factor of 2.25 which may create rendering aliasing. When noalias is true, the
75  letterboxed image size will be 1280x960 (scale factor of 2.0). */
76  void applyLetterBox(unsigned int & imw, unsigned int & imh, unsigned int const winw, unsigned int const winh,
77  bool noalias);
78 
79  //! Split string into vector of tokens using a regex to specify what to split on; default regex splits by whitespace
80  std::vector<std::string> split(std::string const & input, std::string const & regex = "\\s+");
81 
82  //! Concatenate a vector of tokens into a string
83  std::string join(std::vector<std::string> const & strings, std::string const & delimiter);
84 
85  //! Return true if str starts with prefix (including if both strings are equal)
86  /*! Note that if str is shorter than prefix, return is false (like in strncmp()). */
87  bool stringStartsWith(std::string const & str, std::string const & prefix);
88 
89  //! Replace white space characters in a string with underscore (default) or another character
90  std::string replaceWhitespace(std::string const & str, char rep = '_');
91 
92  //! Strip white space (including CR, LF, tabs, etc) from the end of a string
93  std::string strip(std::string const & str);
94 
95  //! Extract a portion of a string between two delimiters
96  /*! Returns an empty string if the delimiters were not found. */
97  std::string extractString(std::string const & str, std::string const & startsep, std::string const & endsep);
98 
99  //! Replace first instance of 'from' with 'to'
100  /*! Returns the number of replacements made (0 or 1). */
101  size_t replaceStringFirst(std::string & str, std::string const & from, std::string const & to);
102 
103  //! Replace all instances of 'from' with 'to'
104  /*! Returns the number of replacements made. */
105  size_t replaceStringAll(std::string & str, std::string const & from, std::string const & to);
106 
107  //! Replace all instances of 'from' with 'to'
108  /*! Returns the number of replacements made. */
109  std::string replaceAll(std::string const & str, std::string const & from, std::string const & to);
110 
111  //! Compute an absolute path from two paths
112  /*! Parameter \p path contains a path that could be either absolute or relative; parameter \p root should contain a
113  root path. If path is absolute, it is returned; otherwise, root is prepended to it and the result is returned. */
114  std::filesystem::path absolutePath(std::filesystem::path const & root, std::filesystem::path const & path);
115 
116  //! Create a string using printf style arguments
117  /*! Example:
118  @code
119  std::string s = jevois::sformat("MyString_%f_%d", 1.0, 2);
120  @endcode
121 
122  One should normally refrain from using sformat(), and instead use streaming operators of C++, one exception is
123  when issuing serial messages that have float numbers in them, the printf-like sytnax of sformat is useful to
124  quickly and easily specify a numerical precision. */
125  std::string sformat(char const * fmt, ...)
126  // NOTE: this __attribute__ tells gcc that it should issue printf-style warnings when compiling calls to sformat(),
127  // treating the 1st argument (fmt) as the format string, and the 2nd and subsequent arguments as the printf-style
128  // parameters
129  __attribute__((format(__printf__, 1, 2)));
130 
131  // Doxygen is not too good with enable_if, it only documents one version of the function. Here is a workaround:
132 #ifdef JEVOIS_DOXYGEN
133  //! Convert from string to a type
134  /*! For integral types, internally uses std::stoll() for that type, which supports prefixes like 0 (for octal) and 0x
135  (hex). Beware of that octal convention and do not pass leading zeros unless you mean it. For non-integral types,
136  internally uses operator>> for that type, so it works with any type that supports it. */
137  template <typename T> T from_string(std::string const & str);
138 #else
139  //! Convert from string to a type, version for non-integral types
140  /*! This internally uses operator>> for that type, so it works with any type that supports it. */
141  template <typename T>
142  typename std::enable_if< ! std::is_integral<T>::value, T>::type from_string(std::string const & str);
143 
144  //! Convert from string to a type, version for integral types
145  /*! This internally uses std::stoll() for that type, which supports prefixes like 0 (for octal) and 0x (hex). */
146  template <typename T>
147  typename std::enable_if<std::is_integral<T>::value, T>::type from_string(std::string const & str);
148 #endif
149 
150  //! Convert from type to string
151  /*! This internally uses operator>> for that type, so it works with any type that supports it. */
152  template <typename T>
153  std::string to_string(T const & val);
154 
155  //! Clamped numerical conversion
156  template <typename dest_type, typename source_type>
157  dest_type clamped_convert(source_type source);
158 
159  //! Flush the caches, may sometimes be useful when running the camera in turbo mode
160  void flushcache();
161 
162  //! Execute a command and grab stdout output to a string
163  /*! If errtoo is true, we also grab errors by appending a 2>&1 to the command. */
164  std::string system(std::string const & cmd, bool errtoo = true);
165 
166  //! Report a duration given in seconds with variable units (ns, us, ms, or s), with precision of 2 decimal points
167  std::string secs2str(double secs);
168 
169  //! Report avg+/-std duration given in seconds with variable units (ns, us, ms, or s), with 1 decimal point
170  std::string secs2str(std::vector<double> secs);
171 
172  //! Report a duration given in seconds with variable units (ns, us, ms, or s)
173  /*! You should decide on precision using std::setprecision(n) in your stream before calling this function. */
174  void secs2str(std::ostringstream & ss, double secs);
175 
176  //! Report a number with variable multipliers (K, M, G, T, P, E, Z, Y), with precision of 2 decimal points
177  std::string num2str(double n);
178 
179  //! Report a number with variable multipliers (K, M, G, T, P, E, Z, Y)
180  /*! You should decide on precision using std::setprecision(n) in your stream before calling this function. */
181  void num2str(std::ostringstream & ss, double n);
182 
183  //! Read one line from a file and return it as a string
184  /*! Useful to get info from virtual kernel filesystems, such as CPU temperature, etc. Parameter \p skip optionally
185  specifies a number of lines to skip before returning the one of interest. */
186  std::string getFileString(char const * fname, int skip = 0);
187 
188  /*! @} */ // **********************************************************************
189 
190 } // namespace jevois
191 
192 
193 // ####################################################################################################
194 //! Helper macro to execute an ioctl, ignore interruptions, and, if error, issue a fatal message and throw
195 /*! \def XIOCTL(dev, req, mem)
196  \hideinitializer
197 
198  This macro assumes that req is an identifier (\#define) for the corresponding ioctl number.
199  \ingroup utils */
200 
201 // ####################################################################################################
202 //! Helper macro to execute an ioctl, ignore interruptions, and, if error throw quietly
203 /*! \def XIOCTL_QUIET(dev, req, mem)
204  \hideinitializer
205 
206  This is useful, e.g., for V4L2 camera enumeration of formats, where one is supposed to call an ioctl
207  with increasing format number until it fails. When that happens we don't want to display any fatal error
208  message as XIOCTL() does. This macro assumes that req is an identifier for the corresponding ioctl number.
209  \ingroup utils */
210 
211 // ####################################################################################################
212 //! Helper macro to execute an ioctl, ignore interruptions, and, if error throw quietly
213 /*! \def XIOCTL_QUIET_ONCE(dev, req, mem)
214  \hideinitializer
215 
216  This is useful, e.g., for V4L2 camera enumeration of formats, where one is supposed to call an ioctl
217  with increasing format number until it fails. When that happens we don't want to display any fatal error
218  message as XIOCTL() does. This macro assumes that req is an identifier for the corresponding ioctl number.
219  Note that in this version we throw on any error.
220  \ingroup utils */
221 
222 // Include implementation details
223 #include <jevois/Util/details/UtilsImpl.H>
jevois::whiteColor
unsigned int whiteColor(unsigned int fcc)
Return a value that corresponds to white for the given video format.
Definition: Utils.C:188
jevois::sformat
std::string sformat(char const *fmt,...) __attribute__((format(__printf__
Create a string using printf style arguments.
Definition: Utils.C:419
jevois::split
std::vector< std::string > split(std::string const &input, std::string const &regex="\\s+")
Split string into vector of tokens using a regex to specify what to split on; default regex splits by...
Definition: Utils.C:258
jevois::cvBytesPerPix
unsigned int cvBytesPerPix(unsigned int cvtype)
Return the number of bytes per pixel for a given OpenCV pixel type.
Definition: Utils.C:89
jevois::flushcache
void flushcache()
Flush the caches, may sometimes be useful when running the camera in turbo mode.
Definition: Utils.C:429
jevois::cvtypestr
std::string cvtypestr(unsigned int cvtype)
Convert cv::Mat::type() code to to a string (e.g., CV_8UC1, CV_32SC3, etc)
Definition: Utils.C:58
jevois::clamped_convert
dest_type clamped_convert(source_type source)
Clamped numerical conversion.
jevois::replaceStringFirst
size_t replaceStringFirst(std::string &str, std::string const &from, std::string const &to)
Replace first instance of 'from' with 'to'.
Definition: Utils.C:319
jevois::blackColor
unsigned int blackColor(unsigned int fcc)
Return a value that corresponds to black for the given video format.
Definition: Utils.C:166
jevois::getFileString
std::string getFileString(char const *fname, int skip=0)
Read one line from a file and return it as a string.
Definition: Utils.C:516
jevois::replaceWhitespace
std::string replaceWhitespace(std::string const &str, char rep='_')
Replace white space characters in a string with underscore (default) or another character.
Definition: Utils.C:288
jevois::replaceAll
std::string replaceAll(std::string const &str, std::string const &from, std::string const &to)
Replace all instances of 'from' with 'to'.
Definition: Utils.C:349
jevois::absolutePath
std::filesystem::path absolutePath(std::filesystem::path const &root, std::filesystem::path const &path)
Compute an absolute path from two paths.
Definition: Utils.C:365
jevois
Definition: Concepts.dox:1
jevois::system
std::string system(std::string const &cmd, bool errtoo=true)
Execute a command and grab stdout output to a string.
Definition: Utils.C:441
jevois::v4l2BytesPerPix
unsigned int v4l2BytesPerPix(unsigned int fcc)
Return the number of bytes per pixel for a given V4L2_PIX_FMT_...
Definition: Utils.C:138
jevois::replaceStringAll
size_t replaceStringAll(std::string &str, std::string const &from, std::string const &to)
Replace all instances of 'from' with 'to'.
Definition: Utils.C:332
jevois::join
std::string join(std::vector< std::string > const &strings, std::string const &delimiter)
Concatenate a vector of tokens into a string.
Definition: Utils.C:268
jevois::extractString
std::string extractString(std::string const &str, std::string const &startsep, std::string const &endsep)
Extract a portion of a string between two delimiters.
Definition: Utils.C:304
jevois::fccstr
std::string fccstr(unsigned int fcc)
Convert a V4L2 four-cc code (V4L2_PIX_FMT_...) to a 4-char string.
Definition: Utils.C:45
jevois::applyLetterBox
void applyLetterBox(unsigned int &imw, unsigned int &imh, unsigned int const winw, unsigned int const winh, bool noalias)
Apply a letterbox resizing to fit an image into a window.
Definition: Utils.C:210
jevois::stringStartsWith
bool stringStartsWith(std::string const &str, std::string const &prefix)
Return true if str starts with prefix (including if both strings are equal)
Definition: Utils.C:282
jevois::secs2str
std::string secs2str(double secs)
Report a duration given in seconds with variable units (ns, us, ms, or s), with precision of 2 decima...
Definition: Utils.C:453
jevois::to_string
std::string to_string(T const &val)
Convert from type to string.
jevois::num2str
std::string num2str(double n)
Report a number with variable multipliers (K, M, G, T, P, E, Z, Y), with precision of 2 decimal point...
Definition: Utils.C:486
jevois::v4l2ImageSize
unsigned int v4l2ImageSize(unsigned int fcc, unsigned int width, unsigned int height)
Return the image size in bytes for a given V4L2_PIX_FMT_..., width, height.
Definition: Utils.C:162
jevois::from_string
std::string T from_string(std::string const &str)
Convert from string to a type.
jevois::strfcc
unsigned int strfcc(std::string const &str)
Convert a JeVois video format string to V4L2 four-cc code (V4L2_PIX_FMT_...)
Definition: Utils.C:111
jevois::strip
std::string strip(std::string const &str)
Strip white space (including CR, LF, tabs, etc) from the end of a string.
Definition: Utils.C:296