views:

454

answers:

3

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++;
        }
    }
}
+1  A: 

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
+1  A: 

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
A: 

This post has source code that shows what you are trying to accomplish:

http://stackoverflow.com/questions/3293471/accessing-negative-pixel-values-opencv/3295141#3295141

karlphillip