上一篇:Delphi图像细化处理
下一篇:Delphi二值图像腐蚀算法

Delphi二值图像膨胀算法

发布于: 2013/1/4 15:19:10   |  发布在: Delphi文章   |  点击:

procedure BitmapDilate(Bitmap: TBitmap);
//传入的Bitmap为二值位图
var
   X, Y: integer;
   O, P, Q, R: pByteArray;
   newbmp: TBitmap;
begin
   newbmp := TBitmap.Create;
   newbmp.Assign(bitmap);
   for Y := 1 to newbmp.Height - 2 do
   begin
      O := bitmap.ScanLine[Y];
      P := newbmp.ScanLine[Y - 1];
      Q := newbmp.ScanLine[Y];
      R := newbmp.ScanLine[Y + 1];
      for X := 1 to newbmp.Width - 2 do
      begin
         if ((O[3 * X] = 255) and (O[3 * X + 1] = 255) and (O[3 * X + 2] = 255)) then
         begin
            if (((Q[3 * (X - 1)] = 0) and (Q[3 * (X - 1) + 1] = 0) and (Q[3 * (X - 1) + 2] = 0))
                or ((Q[3 * (X + 1)] = 0) and (Q[3 * (X + 1) + 1] = 0) and (Q[3 * (X + 1) + 2] = 0))
                or ((P[3 * X] = 0) and (P[3 * X + 1] = 0) and (P[3 * X + 2] = 0))
               or ((R[3 * X] = 0) and (R[3 * X + 1] = 0) and (R[3 * X + 2] = 0))) then
            begin
               O[3 * X] := 0;
               O[3 * X + 1] := 0;
               O[3 * X + 2] := 0;
            end;
         end;
      end;
   end;
end;

过程调用示例:

uses Math;

//打开图片
procedure TForm1.Button1Click(Sender: TObject);
begin
  if OpenPictureDialog1.Execute then
    Image1.Picture.LoadFromFile(OpenPictureDialog1.FileName);
end;

//图像二值化处理
procedure TForm1.Button2Click(Sender: TObject);
var
    p: PByteArray;
    Gray, x, y: Integer;
    Bmp: TBitmap;
begin
    Bmp := TBitmap.Create;
    Bmp.Assign(Image1.Picture.Bitmap);
    //设置为24位真彩色
    Bmp.PixelFormat := pf24Bit;
    randomize;
    for y := 0 to Bmp.Height - 1 do
    begin
        p := Bmp.scanline[y];
        for x := 0 to Bmp.Width - 1 do
        begin
            //一个象素点三个字节
            Gray := Round(p[x * 3 + 2] * 0.3 + p[x * 3 + 1] * 0.59 + p[x * 3] * 0.11);
            if gray > 128 then //全局阀值128
            begin
                p[x * 3] := 255;
                p[x * 3 + 1] := 255;
                p[x * 3 + 2] := 255;
            end else begin
                p[x * 3] := 0;
                p[x * 3 + 1] := 0;
                p[x * 3 + 2] := 0;
            end;
        end;
    end;
    Image2.Picture.Bitmap.Assign(Bmp);
    Bmp.Free;
end;

//图像膨胀处理
procedure TForm1.Button3Click(Sender: TObject);
begin
  BitmapDilate(Image2.Picture.Bitmap);
  Image2.Repaint; //更新显示
end;

二值图像