在visual studio 2010中使用c++将彩色图像转换为灰度

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

本文关键字:彩色图像 转换 灰度 c++ studio visual 2010      更新时间:2023-10-16

在尝试使用c++将彩色图像转换为灰度图像时,我面临一个问题。我认为函数GetRGB()的使用有问题。

这是源代码和相关的头文件。

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

而GetRGB()定义为

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

谢谢你的帮助!

GetRGB期望您提供指向实际byte s的指针,它将输出r, gb的结果。这是一种在c++中通过使用输出参数从函数返回多个结果的方法。

然而,你在这里给它指向NULL的指针:

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

所以没有地方写结果。当你稍后解引用它们时(通过*r, *g, *b),你会得到未定义的行为,因为它们是null

你应该做的是:

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

当然,后面不需要遵守它们,因为它们不是指针:

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

您正在将空指针传递给期望写入这些内存地址的函数。给它一个有效的内存地址,它可以在那里为你存储结果。

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