2010-02-24 99 views
2

我试图采取的imageData图像在这其中w =图像和h的宽度=图像的高度如何从RGB图像(3channel图像)访问图像数据的OpenCV

for (int i = x; i < x+h; i++) //height of frame pixels 
{ 
    for (int j = y; j < y+w; j++)//width of frame pixels 
    { 
     int pos = i * w * Channels + j; //channels is 3 as rgb 
     // if any data exists 
     if (data->imageData[pos]>0) //Taking data (here is the problem how to take) 
     { 
      xPos += j; 
      yPos += i; 
      nPix++; 
     } 
    } 
} 

回答

1

看到好的关于访问OpenCV中IplImage中像素的多种方法的说明here

从您发布您的问题的代码就在于你的位置的变量,你想要的东西像int pos = i*w*Channels + j*Channels,那么你可以在

unsigned char r = data->imageData[pos];

unsigned char g = data->imageData[pos+1];

unsigned char b = data->imageData[pos+2];访问RGB像素

(假设为RGB,但在某些平台上我认为它可以存储BGR)。

4

jeff7为您提供了一个非常旧版OpenCV的链接。 OpenCV 2.0有一个新的C++包装,比链接中提到的C++包装要好得多。我建议您阅读C++ reference of OpenCV以获取有关如何访问各个像素的信息。

另一件需要注意的事情是:你应该让外层循环成为y方向的循环(垂直),内层循环成为x方向的循环。 OpenCV使用C/C++,它将这些值存储在主行中。

1
uchar* colorImgPtr; 
for(int i=0; i<colorImg->width; i++){ 

    for(int j=0; j<colorImg->height; j++){ 

     colorImgPtr = (uchar *)(colorImg->imageData) + (j*colorImg->widthStep + i-colorImg->nChannels) 

     for(int channel = 0; channel < colorImg->nChannels; channel++){ 

      //colorImgPtr[channel] here you have each value for each pixel for each channel 
     } 
    } 
} 
0

有相当多的方法来做到这一点(由jeff7提供的链接是非常有用的)。

我的首选访问图像数据的方法是cvPtr2D方法。你会想是这样的:

for(int x = 0; x < width; ++x) 
{ 
    for(int y = 0; y < height; ++y) 
    { 
     uchar* ptr = cvPtr2D(img, y, x, NULL); 
     // blue channel can now be accessed with ptr[0] 
     // green channel can now be accessed with ptr[1] 
     // red channel can now be accessed with ptr[2] 
    } 
} 

(IMG是IplImage*在上面的代码)

不知道这是做这等的最有效的方式,但我觉得它最简单,最简单的这样做的方式。

你可以找到这种方法的文档here