[NCNN] The difference between the use of Mat in NCNN and Mat in CV and the mutual conversion method

similarities and differences

ncnn::Mat and cv::Mat are similar in some respects, but there are also some differences.
Similarities:

Both ncnn::Mat and cv::Mat are classes used to represent image or matrix data.

They both provide similar APIs to access and manipulate image data.

They both support multiple pixel formats and channel counts.

The difference:

The difference in the library: ncnn::Mat is a data type in the ncnn library, which is used for model reasoning and image processing in ncnn. And cv::Mat is a data type in the OpenCV library, which is used for image processing and computer vision tasks.

Data storage method: ncnn::Mat uses row-first storage, while cv::Mat uses column-first storage. This means that when accessing pixels, their memory layout is different.

Function and usage: ncnn::Mat is mainly used for model reasoning and image processing in ncnn, and provides functions and interfaces related to the ncnn library. cv::Mat is mainly used for image processing and computer vision tasks, and provides a wealth of image processing and computer vision functions.
To sum up, ncnn::Mat and cv::Mat have some differences in purpose and function, but they are both used to process image and matrix data, and provide similar APIs for easy access and manipulation of these data.

The arrangement format of the data in ncnn is (channel, h, w), and the arrangement format of the data in cv::Mat is (h, w, channel).

cv::Mat to ncnn::Mat

cv::Mat CV_8UC3 -> ncnn::Mat 3 channel + swap RGB/BGR

// cv::Mat a(h, w, CV_8UC3);
ncnn::Mat in = ncnn::Mat::from_pixels(a.data, ncnn::Mat::PIXEL_BGR2RGB, a.cols, a.rows);

cv::Mat CV_8UC3 -> ncnn::Mat 1 channel + do RGB2GRAY/BGR2GRAY

ncnn::Mat inbgr = ncnn::Mat::from_pixels(bgr.data, ncnn::Mat::PIXEL_BGR2GRAY, bgr.cols, bgr.rows);

cv::Mat CV_8UC1 -> ncnn::Mat 1 channel

ncnn::Mat in = ncnn::Mat::from_pixels(a.data, ncnn::Mat::PIXEL_GRAY, a.cols, a.rows);

ncnn::Mat to cv::Ma

ncnn::Mat 3 channel -> cv::Mat CV_8UC3 + swap RGB/BGR

cv::Mat a(in.h, in.w, CV_8UC3);
in.to_pixels(a.data, ncnn::Mat::PIXEL_BGR2RGB);

ncnn::Mat 3 channel -> cv::Mat CV_8UC3 + keep RGB/BGR order

// ncnn::Mat in(w, h, 3);
cv::Mat a(in.h, in.w, CV_8UC3);
in.to_pixels(a.data, ncnn::Mat::PIXEL_RGB);

ncnn::Mat 1 channel -> cv::Mat CV_32FC1

You could consume or manipulate ncnn::Mat data directly to avoid data copy
// ncnn::Mat in;
cv::Mat a(in.h, in.w, CV_32FC1);
memcpy((uchar*)a.data, in.data, in.w * in.h * sizeof(float));

ncnn::Mat multiple channels -> std::vector < cv::Mat > + CV_32FC1

// ncnn::Mat in(w, h, channels);
std::vector<cv::Mat> a(in.c);
for (int p=0; p<in.c; p++)
{
    
    
    a[p] = cv::Mat(in.h, in.w, CV_32FC1);
    memcpy((uchar*)a[p].data, in.channel(p), in.w * in.h * sizeof(float));
}

Guess you like

Origin blog.csdn.net/hh1357102/article/details/131845594