1. 程式人生 > >OpenCV中讀取影象畫素值

OpenCV中讀取影象畫素值

OpenCV中用於讀取影象畫素點的值的方法很多,這裡主要提供了兩種常用的方法。

方法一

利用IplImage資料型別的imageData定位資料緩衝區來實現,imageData包含指向影象第一個畫素資料的指標

例:

If( imgSource != 0 )//imgSource為IplImage*

{

for ( int i = 0; i < imgSource->height; ++i )

{

                  uchar * pucPixel = (uchar*)imgSource->imageData + i*imgSource->widthStep;

                  for ( int j = 0; j < imgSource->width; ++j )

                  {       

pucPixel[3*j] = 0;//畫素第一個通道的值

                          pucPixel[3*j + 1] = 0;//畫素第二個通道的值

                          pucPixel[3*j + 2] = 0;//畫素第三個通道的值

                  }

}

}

方法二

利用OpenCV提供的GetReal*D,SetReal*D和Get*D,Set*D,這裡*為2,對於單通道影象可以使用前兩個函式,對於多通道影象可以使用後兩個函式

例:

If( imgSource != 0 )//imgSource為IplImage*

{

for ( int i = 0; i < imgSource->height; ++i )

                  for ( int j = 0; j < imgSource->width; ++j )

                  {       

                       //獲取(i, j)處的三通道影象畫素值

                       CvScalar scaPixelVal = cvGet2D( imgSource, i, j );

                            //獲取(i, j)處的單道影象畫素值

                            double dPixelVal = cvGetReal2D( imgSource, i, j );

                            //設定(i, j)處的三通道影象畫素值

                            cvSet2D( imgSource, i, j, scalPixelVal );

                            //設定(i, j)處的單通道影象畫素值

                            cvSetReal2D( imgSource, i, j, dPixelVal );

                  }

}