RGB to Gray Scale Conversion Using Delphi

We can code an RGB to Gray scale conversion directly in the main unit of our color inversion project. It is easy, as easy as our color inversion project.
  1. Open our previous color inversion project.
  2. Double click the main menu component, and add a menu item 'Convert to Gray Scale' under Image menu (see figure 1).
  3. Double click on the menu item, and you'll be directed to the event handler, edit as shown below:

    procedure TMainForm.ConverttoGrayScale1Click(Sender: TObject);
    var
    i,j:integer;
    ptr:PByteArray;
    begin
    try
    ImageForm:=TImageForm(ActiveMDIChild);
    for i:=0 to (ImageForm.Image1.Height-1) do
    begin
    ptr:=ImageForm.Image1.Picture.Bitmap.ScanLine[i];
    for j:=0 to (ImageForm.Image1.Width-1) do
    begin
    if ImageForm.Image1.Picture.Bitmap.PixelFormat
    =pf24bit then
    begin
    ptr[3*j]:=round(0.114* ptr[3*j]
    +0.587*ptr[3*j+1] + 0.299*ptr[3*j+2]);
    ptr[3*j+1]:=ptr[3*j];
    ptr[3*j+2]:=ptr[3*j];
    end;
    end;
    ImageForm.Image1.Refresh;
    end;
    except
    ShowMessage('Cannot complete the operation');
    end
    end;
  4. Save all files, and now you can compile/run the project. The execution looks like shown in figure 2.

Figure 1. RGB to Gray Scale Conversion Menu


Figure 2. RGB to Gray Scale Conversion

Source Code Download
You can download the Delphi 7 source code here, and the Turbo Delphi Explorer source code here.

1 comments:

Lancelot59 said...

very nice article!.
But how about gamma corrections?
And by the way you forgot to include the final code for the final chapter...

Thanks.