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

前端 未结 5 713
予麋鹿
予麋鹿 2021-01-21 14:55

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
{
          


        
相关标签:
5条回答
  • 2021-01-21 15:15

    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.

    0 讨论(0)
  • 2021-01-21 15:19

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

    Accessing negative pixel values OpenCV

    0 讨论(0)
  • 2021-01-21 15:32

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

    0 讨论(0)
  • 2021-01-21 15:32
    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 讨论(0)
  • 2021-01-21 15:39

    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.

    0 讨论(0)
提交回复
热议问题