简体   繁体   中英

Convert a colored image to greyscale with visual studio 2010 using c++

I'm facing a problem while trying to convert a colored image to grey scale image using C++. I think there's a problem in the use of function GetRGB().

Here is the source code and related header file.

void CCorner::RGBToGrayScale(CImage* pIn, CImage* pOut)
{
//
// INPUT:
//     CImage* pIn:     The input image with 24bit depth
//
// OUTPUT:
//     CImage* pOut:    The output image. It has ALREADY been initialized
//                      with the same dimension as the input image (pIN) and 
//                      formatted to 8bit depth (256 gray levels).
//

int height = pIn->GetHeight();
int width = pIn->GetWidth();
int clrOriginal=pIn->GetColorType();
if (height && width){
    for(int i=0;i<height;i++){
        for(int j=0;j<width;j++){
            byte *r,*g,*b;
            r=NULL; g=NULL; b=NULL;
            bool colors=pIn->GetRGB(i,j,r,g,b);
            double newindex = 0.299**r+0.587**g+0.114**b;
            pOut->SetIndex(i,j,newindex);

            }
        }
    }
}

While GetRGB() is defined as

virtual BOOL GetRGB(int x, int y, byte* r, byte* g, byte* b)
 { return implementation->GetRGB(x, y, r, g, b); }

Thanks for helping!

GetRGB is expecting you to provide pointers to actual byte s where it will output the results for r , g and b . This is a way of returning multiple results from a function in C++, by using output parameters.

However, you're giving it pointers to NULL here:

byte *r,*g,*b;
r=NULL; g=NULL; b=NULL;

So there's nowhere to write the results. When you dereference them later (via *r , *g , *b ) you'll get undefined behaviour because they're null .

What you should be doing, is this:

byte r, g, b;
bool colors = pIn->GetRGB(i, j, &r, &g, &b);

And naturally, no need to deference them later because they're not pointers:

double newindex = 0.299*r+0.587*g+0.114*b;

You are passing null pointers to a function that expects to write to those memory addresses. Give it valid memory addresses where it can store the result for you.

byte r = 0, g = 0, b = 0;
bool colors = pIn->GetRGB(i, j, &r, &g, &b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM