delphi vcl图像的二值化

2017-10-23 18:59:44来源:CSDN作者:qq_38204686人点击

unit Unit2;interfaceuses  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls;type  TForm2 = class(TForm)    im: TImage;    load: TButton;    save: TButton;    ScrollBox1: TScrollBox;    ScrollBox2: TScrollBox;    im1: TImage;    StaticText1: TStaticText;    StaticText2: TStaticText;    TrackBar1: TTrackBar;    StaticText3: TStaticText;    procedure loadClick(Sender: TObject);    procedure saveClick(Sender: TObject);    procedure FormShow(Sender: TObject);    procedure TrackBar1Change(Sender: TObject);  private    { Private declarations }  public    { Public declarations }  end;var  Form2: TForm2;implementation{$R *.dfm}procedure TForm2.FormShow(Sender: TObject);begin    TrackBar1.Max := 255;    TrackBar1.Min := 0;end;//加载图片  loadprocedure TForm2.loadClick(Sender: TObject);begin    //加载 与 exe 同级目录下的 bmp 文件 gg.bmp    im.Picture.Bitmap.LoadFromFile(ExtractFilePath(ParamStr(0))+'gg.bmp');end;//保存图片  saveprocedure TForm2.saveClick(Sender: TObject);begin    //save im1    im1.Picture.Bitmap.SaveToFile('save.bmp');end;//二值化    heibaiprocedure TForm2.TrackBar1Change(Sender: TObject);var   p : PByteArray;   g , x , y : Integer;   //保存修改后的值  b   b : TBitmap;begin   //创建一个位图 b   b := TBitmap.Create;   b.Assign(im.Picture.Bitmap);   for y := 0 to b.Height - 1 do   begin     //这里返回的是一个指针 p     p := b.ScanLine[y];     for x := 0 to b.Width - 1 do     begin       //灰度化   g       g := round(p[x*3+2]*0.3+p[x*3+1]*0.59+p[x*3]*0.11);       //TrackBar1 一个可以拉动的控件  t       if g>=TrackBar1.Position then       begin          //白色 255          p[x*3+2] := 255; p[x*3+1] := 255;p[x*3] := 255;       end       else       begin          //黑色  0          p[x*3+2] := 0; p[x*3+1] := 0;p[x*3] := 0;       end;     end;   end;   //在 image 控件上显示位图 释放内存 b   im1.Picture.Bitmap.Assign(b);   b.Destroy;end;end.