Learn OpenCV to understand the data types of OpenCV - 3

catalogue

Tool function

cv::alignPtr()

cv::alignSize()

cv::allocate()

cv::deallocate()

cv::fastAtan2()

cv::cubeRoot()

cv::CV_Assert() & cv::CV_DbgAsser()

cv::error()

cv::CV_Error() & cv::CV_Error_()

cv::fastFree()

cv::fastMalloc()

cv::format()

cv::getCPUTickCount()

cv::getNumThreads()

cv::getOptimalDFTSize()

cv::getThreadNum()

cv::getTickCount()

cv::getTickFrequency()

cv::setNumThreads()

cv::setUseOptimized()

cv::useOptimized()

cvIsInf()

cvIsNaN()

cvRound()

cvCeil()

cvFloor()

practice

Tool function

OpenCV provides some special functions that can be used to more effectively deal with mathematical and other problems common in computer vision applications. They are called tool functions. Tool functions include mathematical operations, testing, error production, memory and thread processing, optimization and other tools.

Tool and system functions:

Function namedescribe
cv::alignPtr()Align pointer to given number of bytes
cv::alignSize()Aligns the buffer size with the given number of bytes
cv::allocate()Assign a C-style array object
cv::cubeRoot()Calculate the cube root of a number
cv::CV_Assert()If the given condition is not true, an exception is thrown
cv::deallocate()Release a C-style array object
cv::error()Indicates an error and throws an exception
cv::fastAtan2()Calculation of two-dimensional angle of vector
cv::fastFree()Free a memory buffer
cv::fastMalloc()Allocate an aligned memory buffer
cv::format()Create an STL string in sprintf type format
cv::getCPUTickCount()Get tick count from internal CPU timer
cv::getNumThreads()Gets the number of threads currently used by OpenCV
cv::getOptimalDFTSize()Calculates the optimal size of the array to be passed to cv::DFT()
cv::getThreadNum()Gets the index of the current thread
cv::getTickCount()Get the tick count of the system
cv::getTickFrequency()Gets the number of tick s per second
cv::setNumThreads()Sets the number of threads used by OpenCV
cv::setUseOptimized()Turn optimization code on or off (SSE2, etc.)
cv::useOptimized()Indicates that code optimization is enabled
CV_Error()A macro that constructs CV: exception (from a fixed string) and throws an exception
CV_Error_()A macro that constructs CV: exception (from a formatted string) and throws an exception
cvIsInf()Determines whether a floating point number x is infinite
cvIsNaN()Determine whether a floating point number x is not a number
cvRound()Judge a floating point number x to the nearest integer
cvCeil()Approximate a floating-point number x to the nearest integer not less than x (rounded up)
cvFloor()Approximate a floating-point number x to the nearest integer not greater than x (round down)

cv::alignPtr()

template<typename _Tp >
static _Tp* cv::alignPtr(
    _Tp *ptr,
	int n = (int)sizeof(_Tp) 
)

Parameters:
	ptr Pointer to align
	n The alignment size must be a power of 2.
The return value of the function is the aligned pointer address

Aligns the pointer to the specified number of bytes. This function returns an aligned pointer of the same type as the input pointer:

(_Tp*)(((size_t)ptr + n-1) & -n)

In some architectures, only memory addresses that can be divided by a specified number (such as 4,16) can be accessed. Otherwise, the program will crash, or an error result will occur, or the data access will be slow.

opencv2. In versions above 0, many pointers are aligned, so that the pointer address can be divided by 16. The memory in opencv is generally allocated through malloc. It cannot be guaranteed that it can be divided by 16. At this time, it needs to be truncated. CV2 0 in malloc is the space to apply for one more pointer. This pointer points to the real memory address obtained by malloc. It is only used when free.

For a pointer to any address, OpenCV can use the cv::alignPtr() function to shift it to the nearest address that can divide n, where n must be a power of 2.

About & - N: n is a power of 2, and its binary has only one 1. For example, when n defaults to 16, it is 00010000, and taking a negative number gets 111110000. The effect is that for 2k, you get a number with low k of 0 and other bits of 1, If you combine this number (- n) with other numbers, you will cut off the lower k bits of other numbers. The number thus obtained must be a multiple of 2k (the number with the lower k bits of 0 must be a multiple of 2k). This effect only holds for n=2^k.

cv::alignSize()

static size_t cv::alignSize(
	size_t sz,
    int n = sizeof(T)
);
Parameters:
    sz:Buffer size to align.
    n:Alignment size must be a power of 2

Aligns the size of the buffer with the specified number of bytes.

This function returns the smallest fraction greater than or equal to sz and divisible by n: (calculate the size of this buffer so that it contains objects with a size of n integers)

(s + n - 1) & -n

cv::allocate()

template<class T>
T* cv::allocate(
	size_t sz;		//Array size, n * sizeof(T)
);

This function is similar to new in the form of array. It allocates a C-style array containing n T-type objects, calls the default constructor for each object, and returns a pointer to the first object in the array.

Example: void CV:: autobuffer<_ Tp, fixed_ size>::allocate(size_t size);

Allocate a new buffer of size. If the size is small enough, the stack allocated buffer is used.

template<typename _Tp, size_t fixed_size=4096/sizeof(_Tp)+8> 
class CV_EXPORTS AutoBuffer
{
public:
    typedef _Tp value_type;
    enum { buffer_padding = (int)((16 + sizeof(_Tp) - 1)/sizeof(_Tp)) };
 
    //! the default contructor
    AutoBuffer();
    //! constructor taking the real buffer size
    AutoBuffer(size_t _size);
    //! destructor. calls deallocate()
    ~AutoBuffer();
 
    //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used
    void allocate(size_t _size);
    //! deallocates the buffer if it was dynamically allocated
    void deallocate();
    //! returns pointer to the real buffer, stack-allocated or head-allocated
    operator _Tp* ();
    //! returns read-only pointer to the real buffer, stack-allocated or head-allocated
    operator const _Tp* () const;
 
protected:
    //! pointer to the real buffer, can point to buf if the buffer is small enough
    _Tp* ptr;
    //! size of the real buffer
    size_t size;
    //! pre-allocated buffer
    _Tp buf[fixed_size+buffer_padding];
};

cv::AutoBuffer<int> b;
b[0] = 1;
cout << b.size() << endl;

cv::deallocate()

template<T>
void cv::deallocate(
	T* ptr,			//buffer pointer to be released
    size_t sz		//buffer size, n * sizeof(T)
);

The cv::deallocate() function is similar to delete in the form of an array. It releases a C-style array containing n T-type objects and calls the destructor for each object.

cv::deallocate() is used to release the object allocated by cv::allocate(). The element n must be consistent with the allocated n.

cv::fastAtan2()

float cv::fastAtan2(
	float y,	//y coordinate of vector
    float x		//x coordinate of vector
);

The angle of the two-dimensional vector is calculated in degrees. The function fastAtan2 calculates the full range angle of the input 2D vector. The angle ranges from 0-360 ° and the accuracy is about 0.3 °.

cv::cubeRoot()

float cv::cubeRoot(
	float x
);
double cv::cubeRoot(
	double x
);

This function calculates the cube root of the variable x. the negative value of X can also be handled correctly and returns a negative value.

cv::CV_Assert() & cv::CV_DbgAsser()

#define CV_Assert(expr)
do { 
    if(!!(expr)) ; 
    else 
        cv::error( cv::Error::StsAssert, #expr, CV_Func, __FILE__, __LINE__ ); 
} while(0)

CV_Assert() is a macro that tests the expression passed to it and throws an exception if the expression is false.

CV_DbgAsser() can only be used in Debug mode.

cv::error()

void cv::error(
	const cv::Exception &ex
);

This function is mostly composed of CVS_ Error() and CV_ERROR_ () calls. These macros are packaged for you with the information displayed in the exception, and then pass the final exception result to cv::error();

cv::CV_Error() & cv::CV_Error_()

//example
CV_Error(ecode, estring);
CV_Error_(ecode, fmt, ...);

cv::CV_ The error () macro allows you to pass an error code ecode and a fixed C-style string estring, then package them into cv::Exception, and then pass them to cv::error() for processing.

If you need to build messages during runtime, use the macro CV_Error_, It is allowed to pass an error code ecode and a sprintf () style string followed by various variable parameters, which is required by sprintf ().

cv::fastFree()

void cv::fastFree(
	void *ptr
);

Free the memory allocated by cv::fastMalloc().

cv::fastMalloc()

void* cv::fastMalloc(
	size_t size 		//buffer size to be allocated
);

cv::fastMalloc() works similar to malloc(), but it does memory alignment. This means that if the passed buffer size exceeds 16 bits, the returned buffer will be aligned to the 16 bit boundary.

cv::format()

string cv::format(
	const char* fmt,	//format string 
    ...					//vargs, similar to sprintf()
);

This function is essentially the same as sprintf () in the standard library. It does not need to get a character cache from the visitor, but builds an STL character and returns it. It is useful for the Exception () constructor to format error messages.

cv::getCPUTickCount()

int64 cv::getCPUTickCount(void);

This function returns the number of CPU ticks, including but not limited to x86 architecture.

This function is useful for tasks such as initializing a random number generator.

cv::getNumThreads()

int cv::getNumThreads(void);

Returns the number of threads currently available for OpenCV.

cv::getOptimalDFTSize()

int cv::getOptimalDFTSize(int n);  

The general input of cv::getOptimalDFTSize() is the actual size of the picture and returns the array size that should be passed to cv::dft().

cv::getThreadNum()

int cv::getThreadNum(void);

If OpenMP support is added when the OpenCV library is compiled, the index of the currently executing thread is returned (starting from zero).

cv::getTickCount()

long int cv::getTickCount(void); 

This function returns a tick count of time related to some architecture.

Each tick time can be calculated with cv::getTickFrequency().

This function is more widely used than cv::getCPUTickCount(). It will not be affected by underlying problems such as which core the thread runs in or CPU frequency reduction.

cv::getTickFrequency()

double cv::getTickFrequency(void);		//Returns the number of ticks per second.

This function returns the number of ticks per second.

In order to calculate the time of some events, you only need to call cv::getTickCount() before and after the function call, and the two time subtraction is divided by the return value of cv::getTickFrequency().

double t = (double)getTickCount();
// do something ...
t = ((double)getTickCount() - t)/getTickFrequency();

cv::setNumThreads()

void cv::setNumThreads(int nthreads);	//Set the number of threads OpenCV can use

When OpenMP support is added during OpenCV compilation, this function can set the number of threads used in OpenMP area.

If nthreads is 0, the number of threads is reset to the default value.

cv::setUseOptimized()

void cv::setUseOptimized(bool on_off);

By default, the optimization routine is enabled unless you disable it during installation. These optimizations can be turned on and off at any time using cv::setUseOptimized().

The test of the global flag of the optimized usage is completed at a relatively high level in the opencv library function. This means that cv::setUseOptimized() should not be called when any other routine (or function) is running.

cv::useOptimized()

bool cv::useOptimized(void);
Return value:
    true: Optimization is currently on
    false:Optimization is off

At any time, you can use cv::useOptimized() to check the status of optimized global tags.

cvIsInf()

int cvIsInf(double x);

If x is positive and negative infinity, cvIsInf() returns 1, otherwise it returns 0

cvIsNaN()

int cvIsNaN(double x);

If x is not a number, cvIsNaN() returns 1, otherwise it returns 0

cvRound()

int cvRound(double x);

Given a floating-point number x, cvRound() computes the nearest integer to X. If the input value is outside the range of the 32-bit integer representation, the result is undefined

cvCeil()

int cvCeil(
	float x
);

Given a floating-point number x, cvCeil() computes the smallest integer (rounded up) not less than x. if the input exceeds the representation range of a 32-bit integer, the result returns undefined.

cvFloor()

int cvFloor(
	float x
);

Given a floating-point number x, cvCeil() computes the smallest integer (rounded down) not greater than x. if the input exceeds the representation range of a 32-bit integer, the result returns undefined.

practice

  1. Locate and open cxtyes h. Read through and find many conversion help functions.

a. Select a negative floating point number

b. Calculate its absolute value, approximate, round up, round down

c. Generate some random numbers

d. Generate a cv::Point2f of a floating-point number, convert it to an integer cv::Point, and convert cv::Point to cv::Point2f

int main()
{
	srand(time(NULL));

	float a = -3.14;
	cout << "Absolute value:" << cv::abs(a) << ". approximate:" << cvRound(a) << ". Round up:" << cvCeil(a) << ". Round down:"
		<< cvFloor(a) << endl;

	//cv::RNG rng(rand());
	//int x1 = (int)rng % 1000;

	//cout << x1 << endl;

	//cv::Point2f p1(rng.uniform(0.0, 1000.0), rng.uniform(0.0, 1000.0));
	//cout << p1 << endl;

	//cv::Point p2 = (cv::Point)p1;
	//cout << p2 << endl;


	CvPoint point1 = cvPoint(50, 50);
    cout << "(" << point.x << ", " << point.y << ")" <<endl;
	CvPoint2D32f pointf1 = cvPointTo32f(point1);
	cout << "(" << pointf1.x << ", " << pointf1.y << ")" <<endl;

	CvPoint2D32f pointf2 = cvPoint2D32f(50.9876, 50.3565);
	cout << "(" << pointf2.x << ", " << pointf2.y << ")" <<endl;
	CvPoint point2 = cvPointFrom32f(pointf2);
	cout << "(" << point2.x << ", " << point2.y << ")" <<endl;

	return EXIT_SUCCESS;
}

2. Compact matrix and vector class

a. Use cv::Mat33f and cv::Vec3f objects to generate a 3 * 3 matrix and a 3-row vector

b. Can you multiply them directly? If not, why?

int main()
{
	cv::RNG rng(0);
	cv::Matx33f m33(rng.uniform(0.0, 100.0), rng.uniform(0.0, 100.0), rng.uniform(0.0, 100.0), 
					rng.uniform(0.0, 100.0), rng.uniform(0.0, 100.0), rng.uniform(0.0, 100.0), 
					rng.uniform(0.0, 100.0), rng.uniform(0.0, 100.0), rng.uniform(0.0, 100.0));

	cv::Vec3f v3(rng.uniform(0.0, 100.0), rng.uniform(0.0, 100.0), rng.uniform(0.0, 100.0));

	cout << m33 << endl;
	cout << v3 << endl;

	cout << m33 * v3 << endl;

	return EXIT_SUCCESS;
}

Keywords: OpenCV AI Computer Vision

Added by zoooj on Thu, 23 Dec 2021 09:30:52 +0200