2

I am trying to take the imageData of image in this where w= width of image and h = height of image

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++;
        }
    }
}
codaddict
  • 445,704
  • 82
  • 492
  • 529
smile
  • 169
  • 2
  • 4
  • 13
  • This post has source code that shows what you are trying to accomplish: https://stackoverflow.com/questions/3293471/accessing-negative-pixel-values-opencv/3295141#3295141 – karlphillip Aug 20 '10 at 16:50

4 Answers4

4

jeff7 gives you a link to a very old version of OpenCV. OpenCV 2.0 has a new C++ wrapper that is much better than the C++ wrapper mentioned in the link. I recommend that you read the C++ reference of OpenCV for information on how to access individual pixels.

Another thing to note is: you should have the outer loop being the loop in y-direction (vertical) and the inner loop be the loop in x-direction. OpenCV is in C/C++ and it stores the values in row major.

Dat Chu
  • 10,822
  • 13
  • 58
  • 82
1

See good explanation here on multiple methods for accessing pixels in an IplImage in OpenCV.

From the code you've posted your problem lies in your position variable, you'd want something like int pos = i*w*Channels + j*Channels, then you can access the RGB pixels at

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

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

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

(assuming RGB, but on some platforms I think it can be stored BGR).

jeff7
  • 2,172
  • 14
  • 9
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
        }
    }
}
jsan
  • 733
  • 11
  • 26
0

There are quite a few methods to do this (the link provided by jeff7 is very useful).

My preferred method to access image data is the cvPtr2D method. You'll want something like:

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 is an IplImage* in the above code)

Not sure if this is the most efficient way of doing this etc. but I find it the easiest and simplest way of doing it.

You can find documentation for this method here.

Synxis
  • 9,236
  • 2
  • 42
  • 64