[OpenCV] Problem converting array to Mat

Mat type Corresponding data type
CV_8UC1 unsigned char
CV_8SC1 char
CV_16UC1 unsigned short
CV_16SC1 short
CV_32UC1 unsigned int / unsigned long
CV_32SC1 int / long
CV_32FC1 float
CV_64FC1 double

In C++, generally
char is 1 byte (8 bits)
short is 2 bytes (16 bits)
long and int are 4 bytes (32 bits)
float is 4 bytes (32 bits)
double is 8 bytes (64 bits) bit)

Precautions
When converting an array into a Mat type, pay attention to matching the data types in the above table, otherwise some strange problems will occur.

Example:
There is an array of type Int that needs to be converted into Mat and performed floating point operations.

int ddd[3] = {
    
    197111, 297111, 397111};
cv::Mat height_img = cv::Mat(1, 3, CV_32SC1, ddd);
cv::Mat gray_img;
height_img.convertTo(gray_img, CV_32FC1);
gray_img = gray_img / 100000.0;

std::cout << gray_img;

The method is: select when converting the Int array to Mat CV_32SC1, and then convert the Mat to CV_32FC1perform floating point operations.

Remember: Do not select directly during initialization CV_32FC1, otherwise it will still be treated as an integer operation in subsequent calculations.

Guess you like

Origin blog.csdn.net/iiinoname/article/details/127600364