JeVois  1.20
JeVois Smart Embedded Machine Vision Toolkit
Share this page:
Misc utilities

Miscellaneous utility and helper functions.

Collaboration diagram for Misc utilities:

Classes

class  jevois::ThreadPool
 A thread pool with CPU affinity. More...
 

Modules

 Miscellaneous preprocessor utilities related to controlling compilation
 
 Console access utilities
 Console-related utility and helper functions.
 
 Helper functions to convert coordinates from camera resolution to standardized
 Different machine vision algorithms in JeVois may be able to operate with different camera resolutions, such as 1280x1024, 320x240, or 176x144. When some item of interest is detected in the camera frame, one may often want to send the coordinates of that thing to the serial port. This poses a problem if one were to directly send the image coordinates of the item out, which is that now the receiver (e.g., an Arduino) needs to know which camera image resolution was used, so that it can properly interpret these coordinates. For example, if the visual attention (saliency) algorithm is running with 640x480 camera input, then a salient object at the center of the camera's field of view would have coordinates 320,240. But if the same saliency algorithm is configured to process 320x240 input video (so that it can run at a higher framerate), now an object at the center of the field of view would have coordinates 160,120. If one connects an Arduino that controls, for example, a pan/tilt head to JeVois, we need a way to communicate coordinates of target objects in the world independently of the video resolution used by the camera.
 
 Name demangling functions
 Name demangling functions return the original name of a type as written in the source code, as opposed to the name used internally by the compiler, which is mangled to avoid name conflicts and confusions across different namespaces, overloads, and such.
 

Functions

template<class Function , class... Args>
std::future< std::invoke_result_t< std::decay_t< Function >, std::decay_t< Args >... > > jevois::async (Function &&f, Args &&... args)
 Async execution using a thread pool. More...
 
template<class Function , class... Args>
std::future< std::invoke_result_t< std::decay_t< Function >, std::decay_t< Args >... > > jevois::async_little (Function &&f, Args &&... args)
 Async execution using a thread pool. More...
 
template<typename T >
std::vector< T > jevois::joinall (std::vector< std::future< T >> &fvec, bool multiline=true)
 Collect results from several async threads that are all returning a T result. More...
 
void jevois::joinall (std::vector< std::future< void >> &fvec, bool multiline=true)
 Collect results from several async threads that are all returning a T result. More...
 
std::string jevois::fccstr (unsigned int fcc)
 Convert a V4L2 four-cc code (V4L2_PIX_FMT_...) to a 4-char string. More...
 
std::string jevois::cvtypestr (unsigned int cvtype)
 Convert cv::Mat::type() code to to a string (e.g., CV_8UC1, CV_32SC3, etc) More...
 
unsigned int jevois::cvBytesPerPix (unsigned int cvtype)
 Return the number of bytes per pixel for a given OpenCV pixel type. More...
 
unsigned int jevois::strfcc (std::string const &str)
 Convert a JeVois video format string to V4L2 four-cc code (V4L2_PIX_FMT_...) More...
 
unsigned int jevois::v4l2BytesPerPix (unsigned int fcc)
 Return the number of bytes per pixel for a given V4L2_PIX_FMT_... More...
 
unsigned int jevois::v4l2ImageSize (unsigned int fcc, unsigned int width, unsigned int height)
 Return the image size in bytes for a given V4L2_PIX_FMT_..., width, height. More...
 
unsigned int jevois::blackColor (unsigned int fcc)
 Return a value that corresponds to black for the given video format. More...
 
unsigned int jevois::whiteColor (unsigned int fcc)
 Return a value that corresponds to white for the given video format. More...
 
void jevois::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. More...
 
std::vector< std::string > jevois::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 whitespace. More...
 
std::string jevois::join (std::vector< std::string > const &strings, std::string const &delimiter)
 Concatenate a vector of tokens into a string. More...
 
bool jevois::stringStartsWith (std::string const &str, std::string const &prefix)
 Return true if str starts with prefix (including if both strings are equal) More...
 
std::string jevois::replaceWhitespace (std::string const &str, char rep='_')
 Replace white space characters in a string with underscore (default) or another character. More...
 
std::string jevois::strip (std::string const &str)
 Strip white space (including CR, LF, tabs, etc) from the end of a string. More...
 
std::string jevois::extractString (std::string const &str, std::string const &startsep, std::string const &endsep)
 Extract a portion of a string between two delimiters. More...
 
size_t jevois::replaceStringFirst (std::string &str, std::string const &from, std::string const &to)
 Replace first instance of 'from' with 'to'. More...
 
size_t jevois::replaceStringAll (std::string &str, std::string const &from, std::string const &to)
 Replace all instances of 'from' with 'to'. More...
 
std::string jevois::replaceAll (std::string const &str, std::string const &from, std::string const &to)
 Replace all instances of 'from' with 'to'. More...
 
std::string jevois::tolower (std::string const &str)
 Convert string to lowercase. More...
 
std::filesystem::path jevois::absolutePath (std::filesystem::path const &root, std::filesystem::path const &path)
 Compute an absolute path from two paths. More...
 
std::string jevois::sformat (char const *fmt,...) __attribute__((format(__printf__
 Create a string using printf style arguments. More...
 
template<typename T >
std::string T jevois::from_string (std::string const &str)
 Convert from string to a type. More...
 
template<typename T >
std::string jevois::to_string (T const &val)
 Convert from type to string. More...
 
template<typename dest_type , typename source_type >
dest_type jevois::clamped_convert (source_type source)
 Clamped numerical conversion. More...
 
void jevois::flushcache ()
 Flush the caches, may sometimes be useful when running the camera in turbo mode. More...
 
std::string jevois::system (std::string const &cmd, bool errtoo=true)
 Execute a command and grab stdout output to a string. More...
 
std::string jevois::secs2str (double secs)
 Report a duration given in seconds with variable units (ns, us, ms, or s), with precision of 2 decimal points. More...
 
std::string jevois::secs2str (std::vector< double > secs)
 Report avg+/-std duration given in seconds with variable units (ns, us, ms, or s), with 1 decimal point. More...
 
void jevois::secs2str (std::ostringstream &ss, double secs)
 Report a duration given in seconds with variable units (ns, us, ms, or s) More...
 
std::string jevois::num2str (double n)
 Report a number with variable multipliers (K, M, G, T, P, E, Z, Y), with precision of 2 decimal points. More...
 
void jevois::num2str (std::ostringstream &ss, double n)
 Report a number with variable multipliers (K, M, G, T, P, E, Z, Y) More...
 
std::string jevois::getFileString (char const *fname, int skip=0)
 Read one line from a file and return it as a string. More...
 

Function Documentation

◆ absolutePath()

std::filesystem::path jevois::absolutePath ( std::filesystem::path const &  root,
std::filesystem::path const &  path 
)

Compute an absolute path from two paths.

Parameter path contains a path that could be either absolute or relative; parameter root should contain a root path. If path is absolute, it is returned; otherwise, root is prepended to it and the result is returned.

Definition at line 385 of file Utils.C.

Referenced by jevois::Component::absolutePath(), jevois::dnn::NetworkOpenCV::load(), jevois::dnn::NetworkTPU::load(), jevois::dnn::NetworkONNX::load(), jevois::dnn::NetworkNPU::load(), jevois::dnn::NetworkHailo::load(), jevois::dnn::PostProcessorClassify::onParamChange(), jevois::dnn::Pipeline::process(), and jevois::Component::setParamsFromFile().

◆ applyLetterBox()

void jevois::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.

Modify given image dims (imw,imh) so that the image fits inside window dims (winw,winh) while being as large as possible but without modifying the image's aspect ratio. If noalias is specified, the scaling factor will be rounded down to the nearest integer to prevent aliasing in the display. This may reduce the displayed image size. For example, with a 1920x1080 window, a 640x480 image would be letterboxed to 1440x1080 when noalias is false. But that is a scaling factor of 2.25 which may create rendering aliasing. When noalias is true, the letterboxed image size will be 1280x960 (scale factor of 2.0).

Definition at line 222 of file Utils.C.

References LFATAL.

Referenced by jevois::GPUimage::draw(), and jevois::dnn::PreProcessorBlob::process().

◆ async()

template<class Function , class... Args>
std::future<std::invoke_result_t<std::decay_t<Function>, std::decay_t<Args>...> > jevois::async ( Function &&  f,
Args &&...  args 
)

Async execution using a thread pool.

Same function signature and usage as std::async(). Always launches the task in a parallel thread, using a thread pool. Runs the task on big (ARM A73) cores when using big.little CPU architecture of JeVois Pro Platform. Use this function to launch parallel threads of high priority, e.g., machine vision algorithms.

Referenced by jevois::rawimage::byteSwap(), jevois::GUIhelper::compileCommand(), jevois::dnn::NetworkHailo::doprocess(), jevois::MovieOutput::MovieOutput(), TutorialEdgeDetectionX4::process(), jevois::dnn::Pipeline::process(), jevois::dnn::Network::ready(), jevois::rawimage::unpackCvRGBAtoGrayRawImage(), and jevois::dnn::PostProcessorDetectYOLO::yolo().

◆ async_little()

template<class Function , class... Args>
std::future<std::invoke_result_t<std::decay_t<Function>, std::decay_t<Args>...> > jevois::async_little ( Function &&  f,
Args &&...  args 
)

Async execution using a thread pool.

Same function signature and usage as std::async(). Always launches the task in a parallel thread, using a thread pool. Runs the task on little (ARM A53) cores when using big.little CPU architecture of JeVois Pro Platform, or on the same thread pool as jevois::async() on other architectures. Use this function to run threads that are not very compute intensive, e.g., threads that may sleep most of the time until some condition has become satisfied.

Referenced by jevois::CameraDevice::CameraDevice(), jevois::GUIhelper::drawSystem(), jevois::Engine::Engine(), jevois::Gadget::Gadget(), and jevois::Watchdog::Watchdog().

◆ blackColor()

unsigned int jevois::blackColor ( unsigned int  fcc)

Return a value that corresponds to black for the given video format.

The returned value is appropriate to use as the color value for the image drawing functions in Minimalistic support for images in the core JeVois library and may not always be zero.

Definition at line 172 of file Utils.C.

References jevois::fccstr(), JEVOISPRO_FMT_GUI, and LFATAL.

◆ clamped_convert()

template<typename dest_type , typename source_type >
dest_type jevois::clamped_convert ( source_type  source)

Clamped numerical conversion.

◆ cvBytesPerPix()

unsigned int jevois::cvBytesPerPix ( unsigned int  cvtype)

Return the number of bytes per pixel for a given OpenCV pixel type.

Definition at line 89 of file Utils.C.

References LFATAL.

Referenced by jevois::dnn::NetworkTPU::doprocess(), and jevois::dnn::NetworkONNX::doprocess().

◆ cvtypestr()

◆ extractString()

std::string jevois::extractString ( std::string const &  str,
std::string const &  startsep,
std::string const &  endsep 
)

Extract a portion of a string between two delimiters.

Returns an empty string if the delimiters were not found.

Definition at line 316 of file Utils.C.

Referenced by jevois::GUIhelper::drawInfo().

◆ fccstr()

◆ flushcache()

void jevois::flushcache ( )

Flush the caches, may sometimes be useful when running the camera in turbo mode.

Definition at line 449 of file Utils.C.

References LERROR.

◆ from_string()

template<typename T >
std::string T jevois::from_string ( std::string const &  str)

Convert from string to a type.

For integral types, internally uses std::stoll() for that type, which supports prefixes like 0 (for octal) and 0x (hex). Beware of that octal convention and do not pass leading zeros unless you mean it. For non-integral types, internally uses operator>> for that type, so it works with any type that supports it.

◆ getFileString()

std::string jevois::getFileString ( char const *  fname,
int  skip = 0 
)

Read one line from a file and return it as a string.

Useful to get info from virtual kernel filesystems, such as CPU temperature, etc. Parameter skip optionally specifies a number of lines to skip before returning the one of interest.

Definition at line 541 of file Utils.C.

Referenced by jevois::dnn::NetworkTPU::doprocess(), jevois::GUIhelper::drawSystem(), jevois::getFanSpeed(), jevois::getNumInstalledSPUs(), jevois::getNumInstalledTPUs(), jevois::getSysInfoCPU(), jevois::getSysInfoMem(), jevois::getSysInfoVersion(), jevois::GUIhelper::GUIhelper(), and jevois::Engine::postInit().

◆ join()

std::string jevois::join ( std::vector< std::string > const &  strings,
std::string const &  delimiter 
)

Concatenate a vector of tokens into a string.

Definition at line 280 of file Utils.C.

Referenced by jevois::GUIhelper::drawInfo(), jevois::dnn::PostProcessorClassify::onParamChange(), and jevois::dnn::Pipeline::process().

◆ joinall() [1/2]

template<typename T >
std::vector<T> jevois::joinall ( std::vector< std::future< T >> &  fvec,
bool  multiline = true 
)

Collect results from several async threads that are all returning a T result.

Guarantees that get() will run on all futures. If any throws, collect all the error messages (if possible, e.g., an std::exception was thrown) and assemble them into a single string of the form "[error 1][error 2] ..." or "error 1\nerror 2\n...", then throw that as an std::runtime_error

Referenced by jevois::dnn::NetworkHailo::doprocess(), and jevois::dnn::PostProcessorDetectYOLO::yolo().

◆ joinall() [2/2]

void jevois::joinall ( std::vector< std::future< void >> &  fvec,
bool  multiline = true 
)

Collect results from several async threads that are all returning a T result.

Guarantees that get() will run on all futures. If any throws, collect all the error messages (if possible, e.g., an std::exception was thrown) and assemble them into a single string of the form "[error 1][error 2] ..." or "error 1\nerror 2\n...", then throw that as an std::runtime_error

◆ num2str() [1/2]

std::string jevois::num2str ( double  n)

Report a number with variable multipliers (K, M, G, T, P, E, Z, Y), with precision of 2 decimal points.

Definition at line 511 of file Utils.C.

References jevois::sformat().

Referenced by jevois::dnn::NetworkOpenCV::doprocess().

◆ num2str() [2/2]

void jevois::num2str ( std::ostringstream &  ss,
double  n 
)

Report a number with variable multipliers (K, M, G, T, P, E, Z, Y)

You should decide on precision using std::setprecision(n) in your stream before calling this function.

Definition at line 526 of file Utils.C.

◆ replaceAll()

std::string jevois::replaceAll ( std::string const &  str,
std::string const &  from,
std::string const &  to 
)

Replace all instances of 'from' with 'to'.

Returns the number of replacements made.

Definition at line 361 of file Utils.C.

Referenced by jevois::dnn::Pipeline::process().

◆ replaceStringAll()

size_t jevois::replaceStringAll ( std::string &  str,
std::string const &  from,
std::string const &  to 
)

Replace all instances of 'from' with 'to'.

Returns the number of replacements made.

Definition at line 344 of file Utils.C.

Referenced by jevois::dnn::readLabelsFile().

◆ replaceStringFirst()

size_t jevois::replaceStringFirst ( std::string &  str,
std::string const &  from,
std::string const &  to 
)

Replace first instance of 'from' with 'to'.

Returns the number of replacements made (0 or 1).

Definition at line 331 of file Utils.C.

◆ replaceWhitespace()

std::string jevois::replaceWhitespace ( std::string const &  str,
char  rep = '_' 
)

◆ secs2str() [1/3]

std::string jevois::secs2str ( double  secs)

Report a duration given in seconds with variable units (ns, us, ms, or s), with precision of 2 decimal points.

Definition at line 478 of file Utils.C.

References jevois::sformat().

Referenced by jevois::dnn::Pipeline::process(), jevois::Timer::stop(), jevois::Profiler::stop(), and jevois::TimerOne::stop().

◆ secs2str() [2/3]

void jevois::secs2str ( std::ostringstream &  ss,
double  secs 
)

Report a duration given in seconds with variable units (ns, us, ms, or s)

You should decide on precision using std::setprecision(n) in your stream before calling this function.

Definition at line 502 of file Utils.C.

◆ secs2str() [3/3]

std::string jevois::secs2str ( std::vector< double >  secs)

Report avg+/-std duration given in seconds with variable units (ns, us, ms, or s), with 1 decimal point.

Definition at line 487 of file Utils.C.

References jevois::sformat().

◆ sformat()

std::string jevois::sformat ( char const *  fmt,
  ... 
)

Create a string using printf style arguments.

Example:

std::string s = jevois::sformat("MyString_%f_%d", 1.0, 2);

One should normally refrain from using sformat(), and instead use streaming operators of C++, one exception is when issuing serial messages that have float numbers in them, the printf-like sytnax of sformat is useful to quickly and easily specify a numerical precision.

Definition at line 439 of file Utils.C.

Referenced by jevois::DMPdata::activity(), jevois::dnn::NetworkTPU::doprocess(), jevois::dnn::NetworkHailo::doprocess(), jevois::GUIhelper::drawNewModuleForm(), jevois::GUIhelper::iinfo(), jevois::num2str(), jevois::Camera::readRegister(), jevois::dnn::PostProcessorClassify::report(), jevois::dnn::PostProcessorDetect::report(), jevois::dnn::PostProcessorYuNet::report(), jevois::secs2str(), jevois::StdModule::sendSerialObjDetImg2D(), jevois::Camera::writeRegister(), and jevois::dnn::PostProcessorDetectYOLO::yolo().

◆ split()

◆ strfcc()

unsigned int jevois::strfcc ( std::string const &  str)

Convert a JeVois video format string to V4L2 four-cc code (V4L2_PIX_FMT_...)

Throws a runtime_error if str is not one of: BAYER, YUYV, GREY, GRAY, MJPG, RGB565, BGR24 or NONE.

Definition at line 111 of file Utils.C.

References ISP_V4L2_PIX_FMT_META, and JEVOISPRO_FMT_GUI.

◆ stringStartsWith()

bool jevois::stringStartsWith ( std::string const &  str,
std::string const &  prefix 
)

Return true if str starts with prefix (including if both strings are equal)

Note that if str is shorter than prefix, return is false (like in strncmp()).

Definition at line 294 of file Utils.C.

Referenced by jevois::GUIconsole::draw(), jevois::GUIhelper::drawInfo(), jevois::GUIhelper::drawParameters(), jevois::GUIhelper::drawSystem(), jevois::Serial::filePut(), jevois::Engine::mainLoop(), and jevois::Engine::postInit().

◆ strip()

std::string jevois::strip ( std::string const &  str)

Strip white space (including CR, LF, tabs, etc) from the end of a string.

Definition at line 308 of file Utils.C.

Referenced by jevois::Engine::runScriptFromFile().

◆ system()

std::string jevois::system ( std::string const &  cmd,
bool  errtoo = true 
)

Execute a command and grab stdout output to a string.

If errtoo is true, we also grab errors by appending a 2>&1 to the command. Throws std::runtime_error if the command cannot be run somehow, or if it exits with a non-zero exit code.

Definition at line 461 of file Utils.C.

References LFATAL.

Referenced by jevois::GUIhelper::compileCommand(), jevois::GUIhelper::drawInfo(), jevois::GUIhelper::drawNewModuleForm(), jevois::GUIhelper::drawSystem(), jevois::getNumInstalledTPUs(), jevois::getNumInstalledVPUs(), jevois::Engine::parseCommand(), jevois::Engine::reboot(), jevois::Watchdog::run(), jevois::MovieOutput::streamOff(), and jevois::MovieOutput::~MovieOutput().

◆ to_string()

◆ tolower()

std::string jevois::tolower ( std::string const &  str)

Convert string to lowercase.

Definition at line 377 of file Utils.C.

◆ v4l2BytesPerPix()

unsigned int jevois::v4l2BytesPerPix ( unsigned int  fcc)

◆ v4l2ImageSize()

unsigned int jevois::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 at line 168 of file Utils.C.

References jevois::v4l2BytesPerPix().

Referenced by jevois::CameraDevice::streamOn(), and jevois::Gadget::streamOn().

◆ whiteColor()

unsigned int jevois::whiteColor ( unsigned int  fcc)

Return a value that corresponds to white for the given video format.

The returned value is appropriate to use as the color value for the image drawing functions in Minimalistic support for images in the core JeVois library.

Definition at line 197 of file Utils.C.

References jevois::fccstr(), JEVOISPRO_FMT_GUI, and LFATAL.

Referenced by jevois::drawErrorImage().

jevois::sformat
std::string sformat(char const *fmt,...) __attribute__((format(__printf__
Create a string using printf style arguments.
Definition: Utils.C:439