JeVois  1.22
JeVois Smart Embedded Machine Vision Toolkit
Share this page:
Loading...
Searching...
No Matches
Misc utilities

Miscellaneous utility and helper functions.

Collaboration diagram for Misc utilities:

Classes

class  jevois::ThreadPool
 A thread pool with CPU affinity. More...
 
class  jevois::ParallelForAPIjevois
 A parallel API to make OpenCV use our thread pool. More...
 

Modules

 Miscellaneous preprocessor utilities related to controlling compilation
 
 Console access utilities
 
 Helper functions to convert coordinates from camera resolution to standardized
 
 Name demangling functions
 

Macros

#define XIOCTL(dev, req, mem)
 Helper macro to execute an ioctl, ignore interruptions, and, if error, issue a fatal message and throw.
 
#define XIOCTL_QUIET(dev, req, mem)
 Helper macro to execute an ioctl, ignore interruptions, and, if error throw quietly.
 
#define XIOCTL_QUIET_ONCE(dev, req, mem)
 Helper macro to execute an ioctl, ignore interruptions, and, if error throw quietly.
 

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

Macro Definition Documentation

◆ XIOCTL

#define XIOCTL (   dev,
  req,
  mem 
)

Helper macro to execute an ioctl, ignore interruptions, and, if error, issue a fatal message and throw.

This macro assumes that req is an identifier (#define) for the corresponding ioctl number.

Definition at line 211 of file Utils.H.

◆ XIOCTL_QUIET

#define XIOCTL_QUIET (   dev,
  req,
  mem 
)

Helper macro to execute an ioctl, ignore interruptions, and, if error throw quietly.

This is useful, e.g., for V4L2 camera enumeration of formats, where one is supposed to call an ioctl with increasing format number until it fails. When that happens we don't want to display any fatal error message as XIOCTL() does. This macro assumes that req is an identifier for the corresponding ioctl number.

Definition at line 222 of file Utils.H.

◆ XIOCTL_QUIET_ONCE

#define XIOCTL_QUIET_ONCE (   dev,
  req,
  mem 
)

Helper macro to execute an ioctl, ignore interruptions, and, if error throw quietly.

This is useful, e.g., for V4L2 camera enumeration of formats, where one is supposed to call an ioctl with increasing format number until it fails. When that happens we don't want to display any fatal error message as XIOCTL() does. This macro assumes that req is an identifier for the corresponding ioctl number. Note that in this version we throw on any error.

Definition at line 234 of file Utils.H.

Function Documentation

◆ absolutePath()

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

◆ 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::dnn::NetworkNPU::doprocess(), jevois::MovieOutput::MovieOutput(), jevois::dnn::Pipeline::process(), jevois::dnn::Network::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::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 Raw zero-copy / memory-mapped video images and support functions 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::concatenate(), jevois::dnn::NetworkONNX::doprocess(), jevois::dnn::NetworkTPU::doprocess(), and jevois::dnn::split().

◆ 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 317 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 450 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 542 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()

template<typename T >
std::string jevois::join ( std::vector< T > const &  tokens,
std::string const &  delimiter 
)

Concatenate a vector of tokens into a string.

Internally, we use std::to_string to convert each token to string, which may throw

Referenced by jevois::GUIhelper::drawInfo(), jevois::dnn::Pipeline::process(), jevois::dnn::Network::process(), and jevois::dnn::split().

◆ join< std::string >()

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

Concatenate a vector of string tokens into a string.

◆ 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(), jevois::dnn::NetworkNPU::doprocess(), jevois::ParallelForAPIjevois::parallel_for(), jevois::dnn::Network::process(), 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 512 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 527 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 362 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 345 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 332 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 479 of file Utils.C.

References jevois::sformat().

Referenced by jevois::dnn::Pipeline::process(), jevois::Profiler::stop(), jevois::Timer::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 503 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 488 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);
std::string sformat(char const *fmt,...) __attribute__((format(__printf__
Create a string using printf style arguments.
Definition Utils.C:440

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 440 of file Utils.C.

Referenced by jevois::DMPdata::activity(), jevois::dnn::NetworkHailo::doprocess(), jevois::dnn::NetworkTPU::doprocess(), jevois::GUIhelper::drawNewModuleForm(), jevois::GUIhelper::iinfo(), jevois::num2str(), jevois::Camera::readRegister(), jevois::dnn::PostProcessorClassify::report(), jevois::dnn::PostProcessorDetect::report(), jevois::dnn::PostProcessorDetectOBB::report(), jevois::dnn::PostProcessorPose::report(), jevois::dnn::PostProcessorYuNet::report(), jevois::secs2str(), jevois::secs2str(), jevois::StdModule::sendSerialObjDetImg2D(), 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 295 of file Utils.C.

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

◆ 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 309 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 462 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::dnn::NetworkHailo::load(), jevois::Engine::parseCommand(), and jevois::Watchdog::run().

◆ to_string()

template<typename T >
std::string jevois::to_string ( T const &  val)

Convert from type to string.

This internally uses operator>> for that type, so it works with any type that supports it.

Referenced by jevois::CameraCalibration::save(), and jevois::Engine::saveCameraCalibration().

◆ tolower()

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

Convert string to lowercase.

Definition at line 378 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::VideoMapping::c2size(), jevois::VideoMapping::csize(), jevois::VideoMapping::osize(), 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 Raw zero-copy / memory-mapped video images and support functions.

Definition at line 197 of file Utils.C.

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

Referenced by jevois::drawErrorImage().