上一篇:Delphi图像匹配算法
下一篇:TListView按指定列排序

Delphi二值图像投影算法

发布于: 2013/1/19 8:43:28   |  发布在: Delphi文章   |  点击:

本文介绍的是二值图像水平和垂直两个方向对图像进行投影的算法。

说明:此处处理的二值图像是指只有黑白两种颜色的24位真彩位图,并不是Windows画图程序生成的单色位图。

进行水平方向投影

procedure TForm1.Button1Click(Sender: TObject);
var
   X, Y, i, j: integer;
   P: pByteArray;
   bmp: TBitmap;
   iCount: integer;
begin
   bmp := TBitmap.Create;
   bmp.Assign(Image1.Picture.Bitmap);
   for Y := 0 to bmp.Height - 1 do
   begin
      P := bmp.ScanLine[Y];
      iCount := 0; // 设置每一行扫描的初值
      for X := 0 to bmp.Width - 1 do
         if ((P[3 * X + 2] = 0) and (P[3 * X + 1] = 0) and (P[3 * X] = 0)) then
            Inc(iCount);  // 统计每一行的黑色点的数目,记录为iCount
      for i := 0 to iCount do // 从左边开始,给一行iCount个像素点涂上黑色
      begin
         P[3 * i] := 0;
         P[3 * i + 1] := 0;
         P[3 * i + 2] := 0;
      end;
      for j := iCount to bmp.Width - 1 do // 其他点涂白色
      begin
         P[3 * j] := 255;
         P[3 * j + 1] := 255;
         P[3 * j + 2] := 255;
      end;
   end;
   Image2.Picture.Bitmap.Assign(bmp);
   bmp.Free;
end;

进行垂直方向投影

procedure TForm1.Button2Click(Sender: TObject);
const
 
 CI_PIC_MAX_WIDTH = 1024; //图片最大宽度
var
   X, Y, iWidth: integer;
   P: pByteArray;
   bmp: TBitmap;
   iCount: array[0..CI_PIC_MAX_WIDTH] of Integer;
begin
   for X:= 0 to CI_PIC_MAX_WIDTH do iCount[X] := 0; //初始化数组
   bmp := TBitmap.Create;
   bmp.Assign(Image1.Picture.Bitmap);
   if bmp.Width > CI_PIC_MAX_WIDTH then iWidth := CI_PIC_MAX_WIDTH else iWidth := bmp.Width;
   for Y := 0 to bmp.Height - 1 do
   begin
      P := bmp.ScanLine[Y];
      for X := 0 to iWidth - 1 do
         if ((P[3 * X + 2] = 255) and (P[3 * X + 1] = 255) and (P[3 * X] = 255)) then
            Inc(iCount[X]);  // 统计每一列的白色点的数目,记录为iCount数组
   end;
   for Y := 0 to bmp.Height - 1 do
   begin
     P := bmp.ScanLine[Y];
     for X := 0 to iWidth - 1 do if iCount[X] > Y then
     begin
       P[3 * X] := 255;
       P[3 * X + 1] := 255;
       P[3 * X + 2] := 255;
     end else begin
       P[3 * X] := 0;
       P[3 * X + 1] := 0;
       P[3 * X + 2] := 0;
     end;
   end;
   Image3.Picture.Bitmap.Assign(bmp);
   bmp.Free;
end;

二值图像垂直水平