How to access image Data from a RGB image (3channel image) in opencv

13,632

Solution 1

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.

Solution 2

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).

Solution 3

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

Accessing negative pixel values OpenCV

Solution 4

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
        }
    }
}
Share:
13,632
smile
Author by

smile

Updated on June 04, 2022

Comments

  • smile
    smile almost 2 years

    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++;
            }
        }
    }