本文共 2554 字,大约阅读时间需要 8 分钟。
转自:http://blog.csdn.net/liangjialang/article/details/33320093
头文件
- class 你的类名
- {
- public:
-
-
-
-
-
-
-
- void MatToCImage(Mat& mat, CImage& cimage);
-
-
-
-
-
-
-
-
-
- void CImageToMat(CImage& cimage, Mat& mat);
- };
实现文件
- void 你的类名::MatToCImage(Mat& mat, CImage& cimage)
- {
- if (0 == mat.total())
- {
- return;
- }
-
-
- int nChannels = mat.channels();
- if ((1 != nChannels) && (3 != nChannels))
- {
- return;
- }
- int nWidth = mat.cols;
- int nHeight = mat.rows;
-
-
-
- cimage.Destroy();
- cimage.Create(nWidth, nHeight, 8 * nChannels);
-
-
-
-
-
- uchar* pucRow;
- uchar* pucImage = (uchar*)cimage.GetBits();
- int nStep = cimage.GetPitch();
-
-
- if (1 == nChannels)
- {
- RGBQUAD* rgbquadColorTable;
- int nMaxColors = 256;
- rgbquadColorTable = new RGBQUAD[nMaxColors];
- cimage.GetColorTable(0, nMaxColors, rgbquadColorTable);
- for (int nColor = 0; nColor < nMaxColors; nColor++)
- {
- rgbquadColorTable[nColor].rgbBlue = (uchar)nColor;
- rgbquadColorTable[nColor].rgbGreen = (uchar)nColor;
- rgbquadColorTable[nColor].rgbRed = (uchar)nColor;
- }
- cimage.SetColorTable(0, nMaxColors, rgbquadColorTable);
- delete []rgbquadColorTable;
- }
-
-
- for (int nRow = 0; nRow < nHeight; nRow++)
- {
- pucRow = (mat.ptr<uchar>(nRow));
- for (int nCol = 0; nCol < nWidth; nCol++)
- {
- if (1 == nChannels)
- {
- *(pucImage + nRow * nStep + nCol) = pucRow[nCol];
- }
- else if (3 == nChannels)
- {
- for (int nCha = 0 ; nCha < 3; nCha++)
- {
- *(pucImage + nRow * nStep + nCol * 3 + nCha) = pucRow[nCol * 3 + nCha];
- }
- }
- }
- }
- }
-
- void 你的类名::CImageToMat(CImage& cimage, Mat& mat)
- {
- if (true == cimage.IsNull())
- {
- return;
- }
-
-
- int nChannels = cimage.GetBPP() / 8;
- if ((1 != nChannels) && (3 != nChannels))
- {
- return;
- }
- int nWidth = cimage.GetWidth();
- int nHeight = cimage.GetHeight();
-
-
-
- if (1 == nChannels)
- {
- mat.create(nHeight, nWidth, CV_8UC1);
- }
- else if(3 == nChannels)
- {
- mat.create(nHeight, nWidth, CV_8UC3);
- }
-
-
-
-
-
- uchar* pucRow;
- uchar* pucImage = (uchar*)cimage.GetBits();
- int nStep = cimage.GetPitch();
-
-
- for (int nRow = 0; nRow < nHeight; nRow++)
- {
- pucRow = (mat.ptr<uchar>(nRow));
- for (int nCol = 0; nCol < nWidth; nCol++)
- {
- if (1 == nChannels)
- {
- pucRow[nCol] = *(pucImage + nRow * nStep + nCol);
- }
- else if (3 == nChannels)
- {
- for (int nCha = 0 ; nCha < 3; nCha++)
- {
- pucRow[nCol * 3 + nCha] = *(pucImage + nRow * nStep + nCol * 3 + nCha);
- }
- }
- }
- }
- }