在写相机接口的时候,经常需要把byte*类型转成OpenCV mat类型进行图像运算,下面给出两者互相转换的函数
Byte *->Mat
bool ByteToMat(BYTE* pImg, int nH, int nW, int nChannel, cv::Mat& out_img)
{
if (pImg == nullptr)
{
return false;
}
int nByte = nH * nW * nChannel / 8;
int nType = nChannel == 8 ? CV_8UC1 : CV_8UC3;
out_img = cv::Mat::zeros(nH, nW, nType);
memcpy(out_img.data, pImg, nByte);
return true;
}
Mat->Byte *
bool MatToByte(cv::Mat img, BYTE*& pImg)
{
int nChannel = img.channels() * 8;
int nHeight = img.rows;
int nWidth = img.cols;
int nBytes = nHeight * nWidth * nChannel / 8;
if (pImg)
delete[] pImg;
pImg = new BYTE[nBytes];
memcpy(pImg, img.data, nBytes);
return true;
}