OpenCV中图像Mat,二维指针和CxImage类之间的转换
在做圖像處理中,常用的函數(shù)接口有Opencv中的Mat圖像類,有時(shí)候需要直接用二維指針開辟內(nèi)存直接存儲(chǔ)圖像數(shù)據(jù),有時(shí)候需要用到CxImage類存儲(chǔ)圖像。本文主要是總結(jié)下這三類存儲(chǔ)方式之間的圖像數(shù)據(jù)的轉(zhuǎn)換和相應(yīng)的對(duì)應(yīng)關(guān)系。
一、OpenCV的Mat類到圖像二值指針的轉(zhuǎn)換
以下為函數(shù)代碼:
unsigned char** MatTopImgData(Mat img)
{//獲取圖像參數(shù)int row = img.rows;int col = img.cols;int band = img.channels;//定義圖像二維指針unsigned char** pImgdata = new unsigned char*[band];for(int i=0;i<band;i++)pImgdata[i] = new unsigned char[row*col];for(int i=0;i<row;i++) //行數(shù)--高度{unsigned char* data = img.ptr<unsigned char>(i); //指向第i行的數(shù)據(jù)for(int j=0;j<col;j++) //列數(shù) -- 寬度{for(int m=0;m<band;m++) //將各個(gè)波段的數(shù)據(jù)存入數(shù)組pImgdata[m][i*col+j] = data[j*band+m];}}return pImgdata;
}
需要注意的是:(1)在Mat類中,圖像數(shù)據(jù)的存儲(chǔ)方式是BGR形式,這樣得到的二維指針的數(shù)據(jù)存儲(chǔ)順序則為BGR形式。(2)在Mat類中圖像無論是灰度圖還是RGB圖都是以以為指針的形式存儲(chǔ)的,所以在讀取每個(gè)數(shù)據(jù)時(shí),先找到每行數(shù)據(jù)的首地址,再順序讀取每行數(shù)據(jù)的BGR的灰度值。(3)在Mat類中的row為行數(shù),對(duì)應(yīng)平時(shí)所說的圖像的高度,col為列數(shù)對(duì)用圖像的寬度。
二、圖像二維指針到OpenCV的Mat類的轉(zhuǎn)換
以下為函數(shù)代碼:
Mat ImgData(unsigned char** pImgdata, int width, int height, int band)
{Mat Img;if(band == 1) //灰度圖Img.create(height, width, CV_8UC1);else //彩色圖Img.create(height, width, CV_8UC3);for(int i=0;i<height;i++) //行數(shù)--高度{unsigned char* data = Img.ptr<unsigned char>(i); //指向第i行的數(shù)據(jù)for(int j=0;j<width;j++) //列數(shù) -- 寬度{for(int m=0;m<band;m++) //將各個(gè)波段的數(shù)據(jù)存入數(shù)組data[j*band+m]=pImgdata[m][i*width+j];}}return Img;
}
三、CxImage類到圖像二維指針的轉(zhuǎn)換
以下為函數(shù)代碼:
unsigned char** CxImageToPimgdata(CxImage Image)
{int width = Image.GetWidth();int height = Image.GetHeight();RGBQUAD rgbdata;unsigned char** pImgdata = new unsigned char*[3];for(int m=0;m<3;m++)pImgdata[m] = new unsigned char[width*height];for(int i = 0; i < width; i++){for(int j = 0; j < height; j++){//獲取主窗口圖片每一個(gè)像素的rgb數(shù)據(jù)rgbdata = Image.GetPixelColor(i, (height-j-1), true); pImgdata[0][j*width + i] = rgbdata.rgbRed;pImgdata[1][j*width + i] = rgbdata.rgbGreen;pImgdata[2][j*width + i] = rgbdata.rgbBlue;}}return pImgdata;
}
需要注意的是:CxImage讀取圖像數(shù)據(jù)后圖像的原點(diǎn)是在圖像的左下角,與我們的傳統(tǒng)的圖像數(shù)據(jù)原點(diǎn)為左上角相反,所以在讀取圖像時(shí)”(height-j-1)”的由來。
總結(jié):
不同的實(shí)際情況中可能需要用到不同的圖像庫和對(duì)應(yīng)的函數(shù)接口,因此經(jīng)常需要用到這些不同的庫的圖像對(duì)象之間的數(shù)據(jù)的轉(zhuǎn)換,實(shí)際根據(jù)情況進(jìn)行下緩緩即可。
[轉(zhuǎn)自](https://blog.csdn.net/u012273127/article/details/70311970)總結(jié)
以上是生活随笔為你收集整理的OpenCV中图像Mat,二维指针和CxImage类之间的转换的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OpenCV Mat矩阵(图像Mat)初
- 下一篇: 图像指针与矩阵格式转换——Mat转uch