如何从opencv中的RGB图像(3通道图像)访问图像数据

我想在这里拍摄图像的imageData,其中w =图像宽度,h =图像高度

for (int i = x; i < x+h; i++) //height of frame pixels { for (int j = y; j imageData[pos]>0) //Taking data (here is the problem how to take) { xPos += j; yPos += i; nPix++; } } } 

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

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

有关在OpenCV中访问IplImage中像素的多种方法,请参阅此处的详细说明。

从您发布的代码中,您的问题在于您的位置变量,您需要类似int pos = i*w*Channels + j*Channels ,然后您可以访问RGB像素

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

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

unsigned char b = data->imageData[pos+2];

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

这篇文章的源代码显示了您要完成的任务:

访问负像素值OpenCV

 uchar* colorImgPtr; for(int i=0; iwidth; i++){ for(int j=0; jheight; 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 } } } 

有很多方法可以做到这一点(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*

不确定这是否是最有效的方式,但我觉得这是最简单,最简单的方法。

您可以在此处找到此方法的文档。