C++, Negative RGB values of pixels using OpenCV

本小妞迷上赌 提交于 2019-11-30 15:48:42

Try this:

IplImage* img = cvLoadImage("c:\\test.png");

for (int i = 0; i < img->height; i++)
{
    for (int j = 0; j < img->width; j += img->nChannels)
    {
        unsigned char red = img->imageData[i * img->widthStep + j + 2];
        unsigned char green = img->imageData[i * img->widthStep + j + 1];
        unsigned char blue = img->imageData[i * img->widthStep + j];

        outputRGBValues(red, green, blue);
        if (red == REDCOLOUR && green == GREENCOLOUR && blue == BLUECOLOUR)
        {
            count++;
        }
    }
}
cvReleaseImage(&img);

I don't understand why you are accessing pixel data blindly (by 1D index) while you already know the image dimension (proved by the usage of IplImage::height and IplImage::width) and opencv does provide function to access pixel value (cvGet*D).

You are getting odd values in the direct pointer access because you did not factor in the byte padding performed by OpenCV. You may find in 8 bit images, (width*nChannels <= widthStep) for this reason.

A quick revised code can be as follow:

IplImage* img = cvLoadImage("c:\\test.png");
for(int iRow=0; iRow<img->height; ++iRow)
{
    for(int iCol=0; iCol<img->width; ++iCol)
    {
        CvScalar pixelVal = cvGet2D( img, iRow, iCol);
        unsigned char red = pixelVal.val[2];
        unsigned char green = pixelVal.val[1];
        unsigned char blue = pixelVal.val[0];

        outputRGBValues(red, green, blue);
        if (red == REDCOLOUR && green == GREENCOLOUR && blue == BLUECOLOUR)
        {
            count++;
        }
    }
}
cvReleaseImage(&img);

Also, note that usually OpenCV arrange data in BGR format, which can verified at IplImage::channelSeq. Do not confused by IplImage::colorModel, which tells the color model.

I'll go with Paul R suggestion that you should find a reference and understand the library before attempting to use them.

I've never used OpenCV, but I would imagine that cvCreateImage doesn't initialise the contents of the image, and certainly not to anything meaningful.

Quite some issues here:

  • You need to fill the image with meaningful data
  • Depending on how the image was constructed, you may have swapped red and blue
  • You should use unsigned char red
  • You declare a vector for each pixel and don't use it
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!