cv::Mat使用构造函数可以从二维数组构建Mat对象OpenCV笔记-Mat类型;
二维数组是各种类型(char、short、long、float、double)的内存数据;
项目中常见放置灰度图的数组转换为cv::Mat图像;
Mat2Buffer
void Mat2Buffer(const cv::Mat &img, unsigned char *&output)
{
// Mat图像总的字节
int nBytes = img.rows * img.cols * img.channels();
if (output) delete[]output;
output = new unsigned char[nBytes];
// 转化函数,注意使用Mat的data成员
memcpy(output, img.data, nBytes);
}
Buffer2Mat
// bits是input数组的类型长度:char,short,int,long,float,double等等,是sizeof(T)
void Buffer2Mat(const unsigned char *input, int width, int height, int bits, cv::Mat &img)
{
if (input == NULL) return;
int bytes = width * height * bits / 8;
img = cv::Mat::zeros(height, width, bits == 8 ? CV_8UC1 : CV_8UC3);
memcpy(img.data, input, bytes);
}