c++ builder 逐点实现彩色图变黑白图

//在画面上放置TImage控件(Image1)和2个按钮。然后。。。

//---------------------------------------------------------------------------

#include
#pragma hdrstop

#include "Unit7.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm7 *Form7;
Graphics::TBitmap *bitmap1;
//Graphics::TBitmap *bitmap2;
//int x,y;
AnsiString name;

//---------------------------------------------------------------------------
__fastcall TForm7::TForm7(TComponent* Owner)
    : TForm(Owner)
{
    name ="c:\\2.bmp";
}
//---------------------------------------------------------------------------
void __fastcall TForm7::Button1Click(TObject *Sender)
{

    bitmap1=new Graphics::TBitmap;
    //bitmap2=new Graphics::TBitmap;
    Image1->Picture->LoadFromFile(name);
    bitmap1->LoadFromFile(name);
    //bitmap2->LoadFromFile(name);
    //x=bitmap1->Width;
    //y=bitmap1->Height;
    bitmap1->PixelFormat=pf24bit;
   // bitmap2->PixelFormat=pf24bit;
    Image1->Picture->Bitmap->Assign(bitmap1);

}
//---------------------------------------------------------------------------
void __fastcall TForm7::Button2Click(TObject *Sender)
{
     int rgb,i,j,r,g,b;
     TColor color;
     for (i = 0; i Width; i++)
     {
          for (j = 0; j Height; j++)
          {
             color=Image1->Canvas->Pixels[i][j];
             r=GetRValue(color);
             g=GetGValue(color);
             b=GetBValue(color);
             rgb=(r+g+b)/3;//严格讲,要下行,但这样简单,人的眼睛不太灵敏。

             // rgb=(r*19595 + g*38469 +b*7472)>>16;//精确的色度转灰度,但计算复杂
             Image1->Canvas->Pixels[i][j] = TColor( RGB(rgb,rgb,rgb));

          }
     }

}

//1)关于色彩转灰度,有一个很著名的心理学公式:
//         GRAY = R*0.299 + G*0.587 + B*0.114

//2)其实浮点计算较慢,我们可以修改为
//        GRAY = (R*299 + G*587 + B*114)/1000
//    再进一步简化
//        GRAY = (R*30 + G*59 + B*11)/100

//3)再深一步考虑,除法计算较慢,可以修改为
 //       GRAY = (R*19595 + G*38469 +B*7472)>>16

//       19595 = 0.299*65536
//       38469 = 0.587*65536 + 0.264
//         7472 = 0.114*65536 + 0.896

//思考:借助位移,来简化计算量

你可能感兴趣的:(c++,builder,图像图形,c++)