Performance 像素搜索功能效率很低,如何优化?

Performance 像素搜索功能效率很低,如何优化?,performance,delphi,canvas,Performance,Delphi,Canvas,我目前在一个循环中拍摄一个区域的屏幕截图,然后在其中搜索4个像素。 这些像素有相同的颜色-红色或$001300FF。 使用的变量在OnCreate事件中定义和初始化: //The variables for the area: ScanL := 500; // Left ScanR := 800; // Right ScanT := 180; // Top ScanB := 400; // Bottom screenshot: TBitMap; canvas : TCanvas; 要拍摄屏幕

我目前在一个循环中拍摄一个区域的屏幕截图,然后在其中搜索4个像素。 这些像素有相同的颜色-红色或$001300FF。 使用的变量在OnCreate事件中定义和初始化:

//The variables for the area:
ScanL := 500; // Left
ScanR := 800; // Right
ScanT := 180; // Top
ScanB := 400; // Bottom

screenshot: TBitMap;
canvas : TCanvas;
要拍摄屏幕截图,我使用以下功能:

procedure TFormMain.GetSCREENSHOT(var a: TBitMap);
var
  Locked: Boolean;
begin
  Locked := Canvas.TryLock;
  try
    screenshot.Canvas.CopyRect(screenshot.Canvas.ClipRect, Canvas, Rect(ScanL, ScanT, ScanR, ScanB)); 
  finally
    if Locked then
      Canvas.Unlock;
  end;
end;
  QueryPerformanceFrequency(freq);
  QueryPerformanceCounter(startTime);

  findImage;

  QueryPerformanceCounter(endTime);
  ShowMessage('the function needs about ' + IntToStr((endTime - startTime) * 1000 div freq) + 'ms');
全局定义的变量“screenshot:TBitMap”被传递给GetSCREENSHOT函数。为了搜索这4个像素,我做了一个新手会做的事情:

   function TFormMain.findImage : Boolean;
    var
      x,y : Integer;
    begin
      Result := false;
      for x := 0 to screenshot.Width-10 do
      begin
        for y := 0 to screenshot.Height-10 do
        begin
          if screenshot.Canvas.Pixels[x,y] = $001300FF then
          begin
            if screenshot.Canvas.Pixels[x,y+1] = $001300FF then
              if screenshot.Canvas.Pixels[x,y+2] = $001300FF then
                if screenshot.Canvas.Pixels[x,y+3] = $001300FF then
                begin
                  FoundPixelX := ScanL + x;
                  FoundPixelY := ScanT + Y;
                  Result := True;
                  Exit;
                end;
          end;
        end;
      end;
    end;
因为它的性能很差,我测量了运行函数所需的时间:

procedure TFormMain.GetSCREENSHOT(var a: TBitMap);
var
  Locked: Boolean;
begin
  Locked := Canvas.TryLock;
  try
    screenshot.Canvas.CopyRect(screenshot.Canvas.ClipRect, Canvas, Rect(ScanL, ScanT, ScanR, ScanB)); 
  finally
    if Locked then
      Canvas.Unlock;
  end;
end;
  QueryPerformanceFrequency(freq);
  QueryPerformanceCounter(startTime);

  findImage;

  QueryPerformanceCounter(endTime);
  ShowMessage('the function needs about ' + IntToStr((endTime - startTime) * 1000 div freq) + 'ms');
而且它需要108ms!那太疯狂了。我不知道为什么,我希望你能帮助我如何改进它!我想这可能和访问像素属性有关


比较:getSCREENSHOT所需时间不到1毫秒。

可以通过几种方式加快扫描速度。
首先,避免调用
pixels
。虽然方便,但速度却出了名的慢。
打电话吧。这使您可以直接访问位图的原始数据

第二步是优化搜索循环。
循环像素时,始终将x维度放入内循环。
因为我在寻找4个相同颜色的像素,所以我可以使用一个简单的类似优化,将每个循环的
y
增加4个(见下文)。
如果我在寻找4个不同颜色的像素,那么这个优化的实际代码就会复杂得多

{$pointermath on}

function TFormMain.findImage : Boolean;
var
  ScanLine, NextScanLine: PInteger;
  Stride: integer;
  MaxX: integer;
const
  MinX = 0;
  BytesPerPixel = SizeOf(integer);
  MagicColor = $001300FF; 
begin
  MaxX:= Screenshot.Width - 10;
  Assert(Screenshot.PixelFormat = pf32bit);
  Result := false;
  ScanLine:= Screenshot.ScanLine[0];
  Stride:= (NativeInt(Screenshot.ScanLine[1]) - NativeInt(ScanLine)) div BytesPerPixel; 
  y := 0
  repeat
    NextScanLine:= @ScanLine[Stride]; 
    for x:= MinX to MaxX do begin
      if (ScanLine[0] = MagicColor) then begin
        if (ScanLine[stride] = MagicColor) then begin
          if (ScanLine[stride*2] = MagicColor) then begin
            if (ScanLine[stride*3] = MagicColor) then begin
              FoundPixelX := ScanL + x;
              FoundPixelY := ScanT + Y;
              Exit(True);
            end;
          end;
        end;
      end;
      Inc(ScanLine);
    end; {for x}
    ScanLine:= NextScanLine;
    Inc(y);
  until (y > (Height - 10));
end;
注意事项
请注意,
scanline[0]
scanline[1]
不一定在
Width*BytePerPixel
上有所不同。由于对齐的原因,Windows有时会在位图数据中放置一点松弛。这就是我测试两条扫描线之间差异的原因。
在循环本身中,我从不调用
scanline
,这是另一种优化

进一步优化:战舰救援
如果您正在寻找四个相同的像素(即您最喜欢的红色)。每4条扫描线只需扫描1条。一旦找到一个红色像素,上下查看(就像在经典游戏《战舰》中一样),看看是否有一行4个红色像素。
如果是这样的话,你已经找到了匹配的

在这种情况下,内部循环变为:

//Start with ScanLine[3]: the fourth scanline {we start at 0}
NextScanLine:= @ScanLine[Stride*4]; 
for x:= MinX to MaxX do begin
  if (ScanLine[0] = MagicColor) then begin
    Count:=   (integer(ScanLine[-stride*3] = MagicColor) * 1 
             + integer(ScanLine[-stride*2] = MagicColor) * 2
             + integer(ScanLine[-stride*1] = MagicColor) * 4
             + 8; //The line itself
    case Count of  
      1+2+4+8: begin
        FoundPixelX := ScanL + x;
        FoundPixelY := ScanT + Y-3;
        Exit(True);
      end;
      4+8+16: if (ScanLine[stride] = MagicColor) then begin
        FoundPixelX := ScanL + x;
        FoundPixelY := ScanT + Y-2;
        Exit(True);
      end;
      8+16, 1+8+16: if (ScanLine[stride] = MagicColor) and
                       (ScanLine[stride*2] = MagicColor) then begin
        FoundPixelX := ScanL + x;
        FoundPixelY := ScanT + Y-1;
        Exit(True);
      end;
    end; {case}
    if   (ScanLine[stride] = MagicColor) and
         (ScanLine[stride*2] = MagicColor) and
         (ScanLine[stride*3] = MagicColor) then begin
      FoundPixelX := ScanL + x;
      FoundPixelY := ScanT + Y;
      Exit(True);
    end;
  end;
  Inc(ScanLine);
end; {for x}
ScanLine:= NextScanLine;
Inc(y);
在优化版本中,我使用了一些技巧来简化测试逻辑,以加速匹配。
首先,我滥用
true=1
false=0
的快捷键将匹配项转换为整数。
然后我使用连续位的值为1、2、4、8等的事实来跟踪红色匹配。我只在需要的时候做进一步的测试

我可以进一步限制内存访问的数量,但这将以更多测试为代价。在代码中,Delphi生成的测试通常比内存访问要贵一点,所以我错误地选择了后者

Knuth Morris Pratt
如果您正在寻找4个不同的像素,该技巧将不起作用,您将需要实现更复杂的代码。
复杂性会占用CPU周期,因此我怀疑使用Knuth Morris Pratt是否会有所帮助。

当你的搜索“字符串”变长时,这种特殊的算法工作得更好。搜索字符串中只有四个“字符”不足以让它发光

您需要使用该属性来加速您的例程。请查看这篇文章哦,那么像素会调用2个WindowsAPI函数吗?好的,现在它是有意义的。不完全是,重点是扫描线提供了对像素数据的直接内存访问,而像素[x,y]正在为每个像素使用GetPixel Winapi函数。使用
ScanLine
可以大大加快搜索速度。不仅仅是两倍,而且比使用
像素的速度快10-100倍
@XYZ再优化一次(来自《海战笔与纸》游戏:-D)-你不必搜索每一条y线!只扫描第0行、第4行、第8行等,速度可以提高4倍。当你要找到红点时,你必须上下扫描以找到红段的确切末端,但这只会在每一场比赛中进行一次。75%的数据您根本不需要扫描:-)请看我上面的评论,您扫描的y线是您现有y线的四倍to@Arioch即使要搜索水平段,您仍然可以减少75%的工作量:使用Knuth–Morris–Pratt-like优化:-如果第一个
if(扫描线^=$001300FF)
测试失败-您不必进行下一次“+1”迭代!你必须
Inc(x,4);公司(扫描线,4)而不是“你做错了”:-P-当你找到第一个红色pt时,你也必须向后搜索。现在,在[4*k..4*(k+1)-1]
中,您只会发现段以
y的形式出现,这意味着您将错过75%的匹配:-P您必须考虑到,您找到的第一个点不一定是段中的第一个点-它可能是段中的任何点,您必须上下查找;-)你从来没玩过“战舰”是吗-谢谢你的工作!其他人也是:)