Opencv C++ image processing: matrix Mat + random number RNG + calculation time-consuming + mouse events

Article directory

  • 1. C++ data type + number of bytes + value range
  • 2. Mat object: n-dimensional single/multi-channel dense matrix
    • 2.1. Create Mat matrix
    • 2.2. Get pixel 1: img.at(y,x)
    • 2.3. Get pixel 2 (to prevent color overflow): saturate_cast(y,x)
    • 2.4 Common properties of Mat matrix
  • 3. Basic data types
    • 3.1, Point class: cv::Point()
    • 3.2, Scalar class: cv::Scalar()
    • 3.3, Size class: cv::Size()
    • 3.4, Rect class: cv::Rect()
    • 3.5, Matx class: cv::Matx()
    • 3.6, Vec class: cv::Vec()
    • 3.7, Range class: cv::Range()
  • 4. Random number: cv::RNG
    • 4.1. Generate a random number: cv::RNG::uniform() + cv::RNG::gaussian()
    • 4.2. Get the next random number: next + operator
    • 4.3. Fill the matrix with random numbers: cv::RNG::fill()
  • 5. Calculate consumption time function
    • 5.1. Time-consuming: cv::getTickCount()
    • 5.2. Frequency: cv::getTickFrequency()
    • 5.3. Practical cases
  • 6. Mouse and track bar operation
    • 6.1. The callback function of the mouse event: cv::MouseCallback
    • 6.2. Set the callback function of the mouse event: cv::setMouseCallback()
    • 6.3. Create a trackbar and attach it to the specified window: cv::createTrackbar()
    • 6.4. Get the current position of the specified trackbar: cv::getTrackbarPos()
    • 6.5. Set the position of the specified trackbar in the specified window: cv::setTrackbarPos()

1. C++ data type + byte count + value range

Data Type Bytes Value Range
bool type (Boolean type) 1 [0 or 1]
BOOL type (int type) 4 [TRUE or FALSE]
sbyte type (signed 8-bit integer) 1 [128 ~ 127]
bytet type (unsigned 8-bit integer) 8U 2 [0 ~ 255]
short type (signed 16-bit integer) 16S 2 [-32,768 ~ 32,767]
ushort type (unsigned 16-bit integer) 16U 2 [0 ~ 65,535]
int type (signed 32-bit integer) 32S 4 [-2,147,483 ~ 2,147,483,647]
uint type (unsigned 32-bit integer) 4 [0 ~ 4,294,967,295]
long type (64-bit signed integer) 8 [9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807]
ulong type (64-bit unsigned integer) 8 [0 ~ 18,446,744,073,709,551,615]
float type (32-bit single-precision real number) 32F 4 [3.4E + 10 to the negative 38th power ~ 3.4E + 10 to the 38th power]
double type (64-bit double-precision real number) 64F 8 [1.7E + 10 minus 308 times Square ~ 1.7E + 10 to the positive 308th power]
pointer 4

Note: The number of bytes occupied by int, float, and double is determined by the compiler, and different compilers have different regulations. The ANSI standard defines int as occupying 2 bytes.

2. Mat object: n-dimensional single/multi-channel dense matrix

Mat (n-dimensional dense array class): used to store values, vectors, matrices, grayscale or color images, voxel volumes, vector fields, point clouds, tensor, histogram.
Mat class: Create and access two-dimensional, three-dimensional, four-dimensional, and five-dimensional matrices
Mat class: Matrix multiplication – detailed explanation of point multiplication, dot, mul operations

OpenCV C++ uses Mat to store image data, and Mat is composed of multiple pixels. The storage format of conventional images is 8 bits (8bit), that is, one pixel occupies 8 bytes of space.

The data format of an image consists of two parts: storage format + number of channels. Contains: CV_{<!-- -->8U, 16S, 16U, 32S, 32F, 64F}C{<!-- -->1, 2, 3, 4}.
(1) Storage formats include: 8U(unsigned char), 16S(short int), 16U(unsigned short int),
32S(signed int), 32F(float), 64F(double)
(2) The number of channels includes: C{<!-- -->1, 2, 3, 4}.
Among them, the number of channels represents how many pixel values each pixel can store. For example: In an RGB color map, each pixel has three pixel values.
C1 (single-channel image). Such as: grayscale image. The general image is an 8-bit (8bit) storage format, namely CV_8UC1.
C3 (3-channel image). Such as: RGB color map
C4 (4-channel image). Such as: RGB image with transparency channel
\t\t\t\t\t\t\t
For example: CV_8UC3 represents an 8-bit unsigned integer three-channel matrix
00. Assume 3-channel matrix Mat=(100, 100, 3)
11. The RGB image has 100 x 100 x 3=30000 pixels
22. The space occupied by each pixel in the memory space is 8 bits (8bit), that is, CV_8;.
33. Each pixel stores 3 values.
  • Ask:
    When processing the pixels of the image, why do we need to convert the CV_8UC3 (Vec3b) when reading the image into CV_32F (Vec3F), and after processing, we need to convert back to CV_8UC3 (Vec3b) unsigned integer?
  • answer:
    8U value range=[0, 255], 16U=[0, 65535], 32f=[3.4E + 10 to the negative 38th power ~ 3.4E + 10 to the 38th power].
    (1) When performing image processing on pixels, it can be processed directly without conversion.
    (2) When performing mathematical calculations on pixels, it is necessary to maintain high precision to avoid information loss.

2.1, create Mat matrix

Function description: cv::Mat M_temp(row, column, data_type, cv::Scalar(0, 0, 255))
Input parameters:\t\t
row The row of the matrix.
column The column of the matrix.
data_type The data format of the image.
Scalar(0, 0, 255) Initializes RGB pixel values. It means that R/G is all 0, and B is all 255.
\t\t\t\t
//
cv::Mat img1(480, 640, CV_8UC3); //New matrix
cv::Mat img2(img1); //copy matrix

cv::Mat img7 = cv::Mat::zeros(rows, cols, CV_8UC3); //Matrix with all 0 values.
cv::Mat img8 = cv::Mat::ones(rows, cols, CV_64FC1); //A matrix with all 1 values.
cv::Mat img9 = cv::Mat::eye(rows, cols, CV_16SC2); //identity matrix.

2.2. Get pixel 1: img.at(y,x)

(0) CV_8UC1(uchar): 8-bit unsigned integer single-channel matrix.
(1) CV_8UC3(Vec3b): 8-bit unsigned integer three-channel matrix.
(2) CV_32FC3 (Vec3F): 32-bit floating-point three-channel matrix.

cv::Mat img = cv::Mat::ones(240, 320, CV_8UC1); //Create a single-channel Mat matrix
cv::Mat img1 = cv::Mat::ones(480, 640, CV_8UC3); //Create a multi-channel Mat matrix

float elem = img.at<uchar>(10, 10); //Get the pixel value of a (single channel) pixel: img.at<uchar>(y,x)
cv::Vec3b elem = img1.at<cv::Vec3b>(10, 10); //Get the pixel value of (multi-channel) pixel: img.at<cv::Vec3b>(y,x)
elem_B = elem[0]; // blue channel value (all 255)
elem_G = elem[1]; //Green channel value (all 255)
elem_R = elem[2]; // red channel value (all 0)

2.3, get pixel 2 (to prevent color overflow): saturate_cast(y,x)

Boundary overflow can be solved: if the pixel value is greater than 255, assign 255; if the pixel value is less than 0, assign 0.

//The principle is as follows
if (data_value < 0)
data_value = 0;
else if (data_value > 255)
data_value = 255;
#include <opencv2/opencv.hpp>
//using namespace cv;
//using namespace std;

int main(int argc, const char* argv[])
{<!-- -->
    //(1) Read the image
    std::string img_path = "test.jpg";
    cv::Mat src = cv::imread(img_path, 1);

    //(2) Determine whether the image is read successfully
    if (!src.data)
    {<!-- -->
        std::cout << "can't read image!" << std::endl;
        return -1;
    }
    
    //(3) Get the element
    cv::Mat dst1, dst2;
dst1 = cv::Mat::zeros(src. size(), src. type());
dst2 = cv::Mat::zeros(src. size(), src. type());

//Three for loops: dst(i,j) =a * src(i,j) + b
for (int y = 0; y < src.rows; y++ )
{<!-- -->
for (int x = 0; x < src. cols; x ++ )
{<!-- -->
for (int c = 0; c < 3; c ++ ) //three channels
{<!-- -->
dst1.at<cv::Vec3b>(y, x)[c] = src.at<cv::Vec3b>(y, x)[c] * 2; //unsaturated filtering
dst2.at<cv::Vec3b>(y, x)[c] = cv::saturate_cast<uchar>(src.at<cv::Vec3b>(y, x)[c] * 2); //saturated filter out
}
}
}
\t
//(4) display image
cv::imshow("src", src);
cv::imshow("dst1", dst1);
cv::imshow("dst2", dst2);

cv::waitKey(0);
return 0;
}

2.4, common attributes of Mat matrix

cv::Mat img(320, 320, CV_8UC3, cv::Scalar(255, 255, 0)); //Create a 320×320 3-channel color image.

Mat.rows Get the number of matrix rows
Mat.cols Get the number of matrix columns
Mat.dims Get matrix dimension (single channel is two-dimensional, multi-channel is three-dimensional)
Mat.channels() Get the number of matrix channels
Mat.size(); Get matrix size
Mat.total() Get matrix area = [number of rows * number of columns] (regardless of the number of channels)
Mat.depth() Get matrix storage format (return 0~6): enum{<!-- -->CV_8U=0, CV_8S=1, CV_16U=2, CV_16S=3, CV_32S=4, CV_32F=5, CV_64F =6}

Mat.row(0) Gets an array of elements in the first row of the matrix.
Mat.col(0) Gets an array of elements in the first column of the matrix.
Mat.rowRange(0, 10) Gets an array of elements in rows 0-10 of the matrix.
Mat.colRange(0, 10) Gets an array of elements in columns 0-10 of the matrix.

Mat.empty(); Determine whether the matrix is empty, if it is empty, return true.
Mat.clone() copies a matrix and assigns it to a new matrix.

Mat.setTo(0); Sets the entire matrix to the specified value (0). For example: src.setTo(0, src<10); when a pixel value in src is less than 10, set the value to 0.
MatA.copyTo(MatB) copies matrix A into matrix B.
Mat.convertTo(img, CV_32F) Convert the data format of img to CV_32F.
Mat.push_back() Adds one or more elements to the bottom of the matrix. Its type and number of columns must be the same as in Mat matrix.

3. Basic data types

3.1, Point class: cv::Point()

The cv::Point class consists of two parts: cv::Point{<!-- -->2, 3}{<!-- -->b, s, i, f, d}.
(1) Dimensions 2 and 3 represent dimensions (representing 2 points and 3 points respectively)
(2) Storage type b means unsigned character
s means short integer
i represents a 32-bit integer
f represents a 32-bit floating point number
d represents a 64-bit floating point number
\t\t\t\t\t\t\t
Operations supported by the Point class:
Default constructor: cv::Point2i p;
cv::Point3i p;
Copy constructor: cv::Point3f p2(p1);
Value constructor: cv::Point2i(x0,x1);
cv::Point3d p(x0,x1,x2);
Construct a fixed vector class: cv::Vec3f p;
Member access: p.x, p.y;
Dot product: float x = p1.dot(p2);
Double precision dot product: double x =p1.ddot(p2);
Cross product: p1.cross(p2);

3.2, Scalar class: cv::Scalar()

cv::Scalar is essentially a four-dimensional vector, which can generate any four-element vector, usually of type double.

Operations supported by the Scalar class:
Default constructor: cv::Scalar s;
Copy constructor: cv::Scalar s2(s1);
Value constructor: cv::Scalar s(x0);
cv::Scalars(x0, x1, x2, x3);
Return all elements as scalar k: cv::Scalar::all(k)
\t\t
Element-wise multiplication: s1.mul(s2);
(quaternion) conjugate: s.conj(); //return cv::Scalar(s0,-s1,-s2,-s2)
(Quaternion) truth test: s.isReal(); //return ture, if s1==s2==s3==0.

3.3, Size class: cv::Size()

Operations supported by the Size class:
Default constructor: cv::Size sz;
cv::Size2i sz;
cv::Size2f sz;
Copy constructor: cv::Size sz2(sz1);
Value constructor: cv::Size2f sz(w,h);
Member access: sz.width, sz.height;
Calculate the area: sz.area();

3.4, Rect class: cv::Rect()

The

Rect class contains:
(1) Members (x, y) of the Point class. upper left corner of the rectangle
(2) Members of the Size class (width, height). Represents the size of the rectangle

4.1 Operations supported by the Rect class:
Default constructor: cv::Rect r;
Copy constructor: cv::Rect r2(r1);
Value constructor: cv::Rect(x, y, w, h);
Constructed from starting point and size: cv::Rect(p, sz);
Constructed from two diagonals: cv::Rect(p1, p2);
Member access: r.x, r.y, r.width, r.height;
Calculate the area: r.area();
Extract the top left and bottom right corners: r.tl(), r.br();
Determine whether point p is within the rectangle r: r.contains(p);

4.2 Override operation of Rect class:
Intersection of rectangle r1 and rectangle r2: cv::Rect r3 = r1 & amp;r2; r1 & amp;= r2;
The union of rectangle r1 and rectangle r2: cv::Rect r3 = r1|r2; r1 |= r2;
Translate the rectangle r x amount: cv::Rect rx = r + x; r + = x;
Expand the size of rectangle r s: cv::Rect rs = r + s; r + = s;
Compare rectangle r1 and rectangle r2 for equality: bool eq = (r1 == r2);
Compare whether rectangle r1 and rectangle r2 are not equal: bool ne = (r1 != r2);

3.5, Matx class: cv::Matx()

 Fixed matrix class (Matx class):
It is designed to make the dimensions of the matrix known at compile time, and all internal data is allocated on the stack.
It is the core of Opencv's C++ interface primitives.
It inherits from the fixed matrix class. And other classes: either inherit from the fixed vector class, or convert to a fixed vector class.
It is a template cv::Matx<>, but individual matrices are usually assigned via aliases. The basic format of the alias is cv::Matx{<!-- -->1,2,3,4,5,6}{<!-- -->1,2,3,4,5,6}{ <!-- -->f,d}.

5.1 Operations supported by the Matx class:
Default constructor: cv::Matx33f m22f;
cv::Matx43d m43d;
Copy constructor: cv::Matx22d m22d(n22d);
Value constructor: cv::Matx21f m(x0,x1);
Matrices with identical elements: m33f = cv::Matx33f::all(x);
All zero matrix: m23d = cv::Matx23d::zeros();
A matrix with all 1 elements: m16f = cv::Matx16f::ones();
Identity matrix: m33f = cv::Matx33f::eye();
Uniform distribution matrix: m33f = cv::Matx33f::randu(min,max);
Normal distribution matrix: m33f = cv::Matx33f::nrandu(mean,variance);
Member access: m(i,j), m(i);

Matrices can add, subtract, multiply and divide normally:
Dot product: float x = m1.dot(m2);
Double precision dot product: double x = m1.ddot(m2);
Transform operator: m44f = (Matx44f) m44d;
Extract the 2*2 sub-matrix at (i, j): m44f.get_minor<2,2>(i, j);
Extract row i or column j: m14f = m44f.row(i), m41f = m44f.col(j);
Extract the diagonal of the matrix: m41f = m44f.diag();
Calculate matrix transpose: n44f = m44f.t();
Calculate the inverse of the matrix: n44f = m44f.inv(method);
Multiplication per element: m1.mul(m2);

3.6, Vec class: cv::Vec()

6.1 Operations supported by the Vec class:
Default constructor: cv::Vec2s v2s;
Copy constructor: cv::Vec3f u3f(v3f);
Value constructor: cv::Vec2f v2f(x0,x1);
Member access: v4f[i]; v3w(j); //[] and () are both possible
Vector cross product: v3f, cross(u3f);

3.7, Range class: cv::Range()

cv::Range class: used to determine a continuous sequence of integers.

Function description: cv::Range(int start,int end)
Input parameters:
start starting point
end end point
\t\t
Remarks: Close left and open right, similar to Python's range().
Example: cv::Range rng(0, 4) contains [0,1,2,3], but does not contain 4.

4. Random number: cv::RNG

(1) cv::RNG rng(int seed);: Use the random number seed to generate a 64-bit random integer, the default is -1. The random numbers generated by the computer are all pseudo-random numbers, which are calculated based on the seed point seed and a specific algorithm. Therefore, as long as the number of seeds is constant and the algorithm is constant, the random number generated each time is also constant. Use system time as seed point

(2) cv::RNG rng((unsigned)time(NULL)); Use the system time as the seed point, you need to add the header file #include .

4.1. Generate a random number: cv::RNG::uniform() + cv::RNG::gaussian()

Three methods of generating random numbers:

cv::RNG rng(int seed) Use the random number seed to generate a 64-bit random integer, the default is -1.
\t
(1) cv::RNG::uniform(a, b): Returns a uniformly distributed random number in the range [a, b). The data types of a and b must be the same, and must be one of int, float, double, and the default is int.
(2) cv::RNG::gaussian(σ): Returns a random number with a mean of 0 and a standard deviation of σ. To generate random numbers with mean λ and standard deviation σ: λ + RNG::gaussian(σ)
#include<opencv2\opencv.hpp>
#include <string>
//using namespace cv;
//using namespace std;

int main(int argc,char* argv[])
{<!-- -->
cv::RNG rng(-1);
int randomNumber1 = rng;
double randomNumber2 = rng. uniform(0,99);
double randomNumber3 = rng.gaussian(2);
\t
std::cout << "randomNumber1=" << randomNumber1 << std::endl; //randomNumber=130063606
std::cout << "randomNumber2=" << randomNumber2 << std::endl; //randomNumber=14
std::cout << "randomNumber3=" << randomNumber3 << std::endl; //randomNumber=-1.40186
return 0;
}

4.2. Get the next random number: next + operator

(1) cv::RNG::next returns the next 64-bit random integer.
(2) cv::RNG::operator returns the next random number of the specified type.
#include<opencv2\opencv.hpp>
#include <string>
//using namespace cv;
//using namespace std;

int main(int argc,char* argv[])
{<!-- -->
cv::RNG rng(-1);
int randomNumber = rng.next(); //Return the next random integer, ie N1.next();
\t 
// Return the next random number of the specified type
int randomNumber1 = rng.operator uchar(); //return the next unsigned character number
int randomNumber2 = rng.operator schar(); //return the next number of signed characters
int randomNumber3 = rng.operator ushort(); // return the next unsigned short
int randomNumber4 = rng.operator short int(); // return the next short integer
int randomNumber5 = rng.operator int(); // return the next integer
int randomNumber6 = rng.operator unsigned int(); // return the next unsigned integer
int randomNumber7 = rng.operator float(); // return the next floating point number
int randomNumber8 = rng.operator double(); //return the next double number
int randomNumber9 = rng.operator ()(); //Equivalent to rng.next()
int randomNumber10 = rng.operator ()(100); //returns a random number in the range [0,100)
\t
std::cout << "randomNumber=" << randomNumber << std::endl; //randomNumber=130063605
std::cout << "randomNumber1=" << randomNumber1 << std::endl; //randomNumber=156
std::cout << "randomNumber2=" << randomNumber2 << std::endl; //randomNumber=-116
std::cout << "randomNumber3=" << randomNumber3 << std::endl; //randomNumber=24389
std::cout << "randomNumber4=" << randomNumber4 << std::endl; //randomNumber=31943
std::cout << "randomNumber5=" << randomNumber5 << std::endl; //randomNumber=-1348951784
std::cout << "randomNumber6=" << randomNumber6 << std::endl; //randomNumber=94037301
std::cout << "randomNumber7=" << randomNumber7 << std::endl; //randomNumber=0
std::cout << "randomNumber8=" << randomNumber8 << std::endl; //randomNumber=0
std::cout << "randomNumber9=" << randomNumber9 << std::endl; //randomNumber=776868985
std::cout << "randomNumber10=" << randomNumber10 << std::endl; //randomNumber=94
return 0;
}

4.3. Fill the matrix with random numbers: cv::RNG::fill()

Function description: void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturatedRange=false );
Input parameters:
(1) mat input matrix. 2D or N-dimensional matrix, supports up to 4 channels, if more than 4 channels, use reshape() to change the structure first.
(2) distType distribution type.
cv::RNG::UNIFORM uniform distribution.
cv::RNG::NORMAL Gaussian distribution.
(3)a The first distribution parameter. A lower boundary (closed interval) is represented when the distribution is uniform, and the average value is represented when the distribution is normal.
(4)b Second distribution parameter. When it is uniformly distributed, it represents an upper boundary (open interval), and when it is normally distributed, it represents the standard deviation.
(5) saturateRange=false is only valid for uniform distribution. When it is true, the range of generating random numbers will be converted to the range of the data type first, and then random numbers will be generated. If it is false, a random number will be generated first, and then truncated to the valid interval of the data type.
#include<opencv2\opencv.hpp>
#include <string>
//using namespace cv;
//using namespace std;

int main(int argc,char* argv[])
{<!-- -->
cv::RNG rng(-1);
\t
cv::Mat_<int>fillM1(3, 3); //Create a new 3x3 matrix, int type
cv::Mat_<double>fillM2(3, 3); //Create a new 3x3 matrix, double type

rng.fill(fillM1, cv::RNG::UNIFORM, 1, 100); // Randomly generate [1,100) evenly distributed int numbers and fill fillM.
rng.fill(fillM2, cv::RNG::NORMAL, 1, 3); // Randomly generate a double number with a mean of 1 and a standard deviation of 3, and fill in fillN.
\t
std::cout << "filM = " << fillM1 << std::endl;
std::cout << "filN = " << fillM2 << std::endl;
\t
return 0;
}

5. Calculate consumption time function

5.1, time-consuming: cv::getTickCount()

Function description: int64 cv::getTickCount();
Function function: Calculate the time consumed by executing the function by reading the time scale before and after the function call.

5.2, Frequency: cv::getTickFrequency()

Function description: double cv::getTickFrequency();
Function: Divide the loss time by the function (frequency) for unit conversion, and return the scale number unit of the time: second.

5.3, actual combat cases

#include <opencv2/opencv.hpp>
//using namespace cv;
//using namespace std;

int main(int argc, const char* argv[])
{<!-- -->
double count1 = cv::getTickCount();
\t
\t//deal with
\t//deal with
\t//deal with
\t
double count2 = cv::getTickCount();
double time_consume = (count2 - count1) / cv::getTickFrequency();
std::cout << "Time-consuming:" << time_consume << std::endl;
}

6. Mouse and track bar operation

[OpenCV] OpenCV Basic Tutorial (11) – HighGUI Graphical User Interface

6.1, the callback function of the mouse event: cv::MouseCallback

Use a callback function to handle mouse events. First create a callback function, and enter the callback function trigger event and trigger location. The function also needs to be informed whether the user has triggered a key such as Shift or Alt while triggering a mouse event.

#include <opencv2/highgui.hpp>
Function description: typedef void(* cv::MouseCallback) (int event, int x, int y, int flags, void *userdata)
Input parameters:
11. event: mouse event
Event Name Value Description
CV_EVENT_MOUSEMOVE 0 indicates that the mouse pointer has moved over the window.
CV_EVENT_LBUTTONDOWN 1 means the left mouse button is pressed.
CV_EVENT_RBUTTONDOWN 2 means the right mouse button is pressed.
CV_EVENT_MBUTTONDOWN 3 means the middle mouse button is pressed.
CV_EVENT_LBUTTONUP 4 Indicates that the left mouse button was released.
CV_EVENT_RBUTTONUP 5 Indicates that the right mouse button was released.
CV_EVENT_MBUTTONUP 6 Indicates that the middle mouse button was released.
CV_EVENT_LBUTTONDBLCLK 7 means double-click the left mouse button.
CV_EVENT_RBUTTONDBLCLK 8 means double-click the right mouse button.
CV_EVENT_MBUTTONDBLCLK 9 means double-click the middle mouse button.
22. (x, y): the coordinate position that triggers the mouse event
33, flags: mouse status
Flag Name Value Description
CV_EVENT_FLAG_LBUTTON 1 means the left mouse button is down.
CV_EVENT_FLAG_RBUTTON 2 means the right mouse button is down.
CV_EVENT_FLAG_MBUTTON 4 means the middle mouse button is down.
CV_EVENT_FLAG_CTRLKEY 8 means that the Ctrl key (8~15) is pressed.
CV_EVENT_FLAG_SHIFTKEY 16 indicates that the Shift key (16~31) is pressed.
CV_EVENT_FLAG_ALTKEY 32 indicates that the Alt key (32~39) is pressed.
44. param: (optional parameter) Additional parameter information can be passed in any structure.

6.2, set the callback function of the mouse event: cv::setMouseCallback()

#include <opencv2/highgui.hpp>
Function description: void cv::setMouseCallback(const String & amp;winname, MouseCallback onMouse, void *userdata = (void *)0)
Input parameters:
winname The name of the window.
The callback function of onMouse mouse event.
userdata Optional parameter passed to the callback (default 0).

6.3. Create a trackbar and attach it to the specified window: cv::createTrackbar()

  • Creates a trackbar (slider or range control) with the specified name and range, assigns a variable value as the position to synchronize with the trackbar, and specifies the callback function onChange to be called when the trackbar’s position changes.
  • The created trackbar will be displayed in the specified window winname.
#include <opencv2/highgui.hpp>
Function description: int cv::createTrackbar( const String & amp;trackbarname, const String & amp;winname, int *value, int count, TrackbarCallback onChange = 0, void *userdata = 0 )
Input parameters:
trackbarname The name of the created trackbar.
winname The name of the parent window for the trackbar.
value An optional pointer to an integer variable whose value reflects the position of the slider. When created, the slider position is defined by this variable.
The maximum position of the count slider. The minimum position is always 0.
onChange Pointer to a function to be called whenever the slider changes position (default 0). This function should be prototyped as void Foo(int, void*), where the first parameter is the trackbar position and the second parameter is the user data (see next parameter). If the callback is a NULL pointer, the callback will not be called, but only the value will be updated.
userdata Userdata passed to the callback as-is (default 0). It can be used to handle trackbar events without using global variables.

6.4. Get the current position of the specified trackbar: cv::getTrackbarPos()

#include <opencv2/highgui.hpp>
Function description: int cv::getTrackbarPos(const String & amp; trackbarname, const String & amp; winname)
Input parameters:
trackbarname The name of the trackbar.
winname The name of the parent window for the trackbar.
\t\t\t\t
Note: winname can be empty if the trackbar is connected to a control panel.

6.5. Set the position of the specified trackbar in the specified window: cv::setTrackbarPos()

#include <opencv2/highgui.hpp>
Function description: void cv::setTrackbarPos( const String & amp;trackbarname, const String & amp;winname, int pos )
Input parameters:
trackbarname The name of the trackbar.
winname The name of the parent window for the trackbar.
pos the new position.
\t\t\t\t
Note: winname can be empty if the trackbar is connected to a control panel.