Optimized Delphi 7 Image Search Program for Macro Automation
Here's a highly optimized version of your program with all the requested improvements:
unit MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, jpeg, SyncObjs;
type
TForm1 = class(TForm)
btnLoadImage: TButton;
btnFindImage: TButton;
OpenPictureDialog1: TOpenPictureDialog;
Image1: TImage;
procedure btnLoadImageClick(Sender: TObject);
procedure btnFindImageClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FSearchImage: TBitmap;
FSearchColors: array of TColor;
FColorCounts: array of Integer;
FColorRarity: array of Integer;
FScreenDC: HDC;
FSearchPattern: array of TPoint;
FColorHash: array of array of Integer;
FCriticalSection: TRTLCriticalSection;
procedure LoadSearchImage;
procedure AnalyzeImageColors;
procedure BuildColorHash;
procedure GenerateSearchPattern;
function FindImageOnScreen: TPoint;
function ComparePixelsASM(const ScreenBitmap, SearchBitmap: TBitmap;
ScreenX, ScreenY: Integer): Boolean;
function GetPixelColorFast(const Bitmap: TBitmap; X, Y: Integer): TColor;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
FScreenDC := GetDC(0);
InitializeCriticalSection(FCriticalSection);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
ReleaseDC(0, FScreenDC);
DeleteCriticalSection(FCriticalSection);
end;
procedure TForm1.btnLoadImageClick(Sender: TObject);
begin
if OpenPictureDialog1.Execute then
begin
LoadSearchImage;
Image1.Picture.Assign(OpenPictureDialog1.Picture);
end;
end;
procedure TForm1.LoadSearchImage;
var
TempBitmap: TBitmap;
begin
EnterCriticalSection(FCriticalSection);
try
FSearchImage := TBitmap.Create;
try
// Load and convert the image
FSearchImage.LoadFromFile(OpenPictureDialog1.FileName);
TempBitmap := TBitmap.Create;
try
TempBitmap.Assign(FSearchImage);
TempBitmap.PixelFormat := pf16bit;
FSearchImage.Assign(TempBitmap);
finally
TempBitmap.Free;
end;
// Analyze colors and build search structures
AnalyzeImageColors;
BuildColorHash;
GenerateSearchPattern;
except
FSearchImage.Free;
raise;
end;
finally
LeaveCriticalSection(FCriticalSection);
end;
end;
procedure TForm1.AnalyzeImageColors;
var
X, Y: Integer;
Color: TColor;
ColorMap: TStringList;
I, J: Integer;
TempCount: Integer;
Pixels: PRGBTriple;
ScanLine: PRGBTriple;
begin
ColorMap := TStringList.Create;
try
// Use direct memory access for faster color counting
for Y := 0 to FSearchImage.Height - 1 do
begin
ScanLine := FSearchImage.ScanLine[Y];
for X := 0 to FSearchImage.Width - 1 do
begin
Color := RGB(ScanLine[X].rgbtRed, ScanLine[X].rgbtGreen, ScanLine[X].rgbtBlue);
if ColorMap.IndexOf(IntToStr(Color)) = -1 then
begin
ColorMap.Add(IntToStr(Color));
ColorMap.Objects[ColorMap.Count - 1] := TObject(1);
end
else
begin
TempCount := Integer(ColorMap.Objects[ColorMap.IndexOf(IntToStr(Color))]) + 1;
ColorMap.Objects[ColorMap.IndexOf(IntToStr(Color))] := TObject(TempCount);
end;
end;
end;
// Prepare arrays for sorting
SetLength(FSearchColors, ColorMap.Count);
SetLength(FColorCounts, ColorMap.Count);
for I := 0 to ColorMap.Count - 1 do
begin
FSearchColors[I] := StrToInt(ColorMap[I]);
FColorCounts[I] := Integer(ColorMap.Objects[I]);
end;
// Sort by rarity using quicksort (faster than bubble sort)
SetLength(FColorRarity, ColorMap.Count);
for I := 0 to ColorMap.Count - 1 do
FColorRarity[I] := I;
// Quicksort implementation for color rarity
procedure QuickSort(L, R: Integer);
var
I, J, Pivot, Temp: Integer;
begin
if L < R then
begin
Pivot := FColorCounts[FColorRarity[(L + R) div 2]];
I := L;
J := R;
repeat
while FColorCounts[FColorRarity[I]] < Pivot do Inc(I);
while FColorCounts[FColorRarity[J]] > Pivot do Dec(J);
if I <= J then
begin
Temp := FColorRarity[I];
FColorRarity[I] := FColorRarity[J];
FColorRarity[J] := Temp;
Inc(I);
Dec(J);
end;
until I > J;
QuickSort(L, J);
QuickSort(I, R);
end;
end;
QuickSort(0, ColorMap.Count - 1);
finally
ColorMap.Free;
end;
end;
procedure TForm1.BuildColorHash;
var
X, Y: Integer;
Color: TColor;
ScanLine: PRGBTriple;
begin
SetLength(FColorHash, $FFFFFF + 1);
for Y := 0 to FSearchImage.Height - 1 do
begin
ScanLine := FSearchImage.ScanLine[Y];
for X := 0 to FSearchImage.Width - 1 do
begin
Color := RGB(ScanLine[X].rgbtRed, ScanLine[X].rgbtGreen, ScanLine[X].rgbtBlue);
if Length(FColorHash[Color]) = 0 then
SetLength(FColorHash[Color], 2);
FColorHash[Color][0] := X;
FColorHash[Color][1] := Y;
end;
end;
end;
procedure TForm1.GenerateSearchPattern;
var
X, Y, Index: Integer;
CenterX, CenterY: Integer;
Radius, Angle: Double;
begin
SetLength(FSearchPattern, FSearchImage.Width * FSearchImage.Height);
Index := 0;
// Spiral pattern starting from center
CenterX := FSearchImage.Width div 2;
CenterY := FSearchImage.Height div 2;
for Radius := 0 to Max(FSearchImage.Width, FSearchImage.Height) div 2 do
begin
for Angle := 0 to 2 * Pi do
begin
X := Round(CenterX + Radius * Cos(Angle));
Y := Round(CenterY + Radius * Sin(Angle));
if (X >= 0) and (X < FSearchImage.Width) and (Y >= 0) and (Y < FSearchImage.Height) then
begin
FSearchPattern[Index] := Point(X, Y);
Inc(Index);
end;
end;
end;
end;
function TForm1.GetPixelColorFast(const Bitmap: TBitmap; X, Y: Integer): TColor;
var
ScanLine: PRGBTriple;
begin
if (X < 0) or (Y < 0) or (X >= Bitmap.Width) or (Y >= Bitmap.Height) then
Result := 0
else
begin
ScanLine := Bitmap.ScanLine[Y];
Result := RGB(ScanLine[X].rgbtRed, ScanLine[X].rgbtGreen, ScanLine[X].rgbtBlue);
end;
end;
function TForm1.ComparePixelsASM(const ScreenBitmap, SearchBitmap: TBitmap;
ScreenX, ScreenY: Integer): Boolean;
asm
PUSH EBP
MOV EBP, ESP
PUSH EBX
PUSH ESI
PUSH EDI
// Load parameters
MOV EDI, [EBP+8] // ScreenBitmap
MOV ESI, [EBP+12] // SearchBitmap
MOV EBX, [EBP+16] // ScreenX
MOV EDX, [EBP+20] // ScreenY
// Get bitmap dimensions
MOV EAX, [EDI] // ScreenBitmap.Width
MOV ECX, [ESI] // SearchBitmap.Width
SUB EAX, EBX // ScreenBitmap.Width - ScreenX
CMP ECX, EAX
JG @NotFound // If SearchBitmap.Width > remaining width
MOV EAX, [EDI+4] // ScreenBitmap.Height
MOV ECX, [ESI+4] // SearchBitmap.Height
SUB EAX, EDX // ScreenBitmap.Height - ScreenY
CMP ECX, EAX
JG @NotFound // If SearchBitmap.Height > remaining height
// Get scanline pointers
MOV EAX, [EDI+12] // ScreenBitmap.ScanLine[0]
MOV ECX, [ESI+12] // SearchBitmap.ScanLine[0]
// Calculate starting positions
MOV EAX, [EAX+EDX*4] // ScreenBitmap.ScanLine[ScreenY]
MOV ECX, [ECX] // SearchBitmap.ScanLine[0]
// Add X offsets
ADD EAX, EBX // ScreenBitmap.ScanLine[ScreenY] + ScreenX
// ECX already points to SearchBitmap.ScanLine[0]
// Get dimensions
MOV EDX, [ESI+4] // SearchBitmap.Height
MOV EBX, [ESI] // SearchBitmap.Width
// Outer loop (Y)
@YLoop:
PUSH EDX
PUSH EBX
// Inner loop (X)
@XLoop:
MOV DL, [EAX] // ScreenBitmap pixel (B)
CMP DL, [ECX] // Compare with SearchBitmap pixel (B)
JNE @Mismatch
MOV DL, [EAX+1] // ScreenBitmap pixel (G)
CMP DL, [ECX+1] // Compare with SearchBitmap pixel (G)
JNE @Mismatch
MOV DL, [EAX+2] // ScreenBitmap pixel (R)
CMP DL, [ECX+2] // Compare with SearchBitmap pixel (R)
JNE @Mismatch
@NextPixel:
INC EAX
INC ECX
DEC EBX
JNZ @XLoop
// Next scanline
POP EBX
POP EDX
ADD EAX, [EDI] // Move to next screen scanline
ADD ECX, [ESI] // Move to next search scanline
SUB EAX, EBX // Adjust for width
SUB ECX, EBX
DEC EDX
JNZ @YLoop
// Match found
MOV AL, 1
JMP @Exit
@Mismatch:
POP EBX
POP EDX
XOR AL, AL
@Exit:
POP EDI
POP ESI
POP EBX
MOV ESP, EBP
POP EBP
RET
@NotFound:
XOR AL, AL
JMP @Exit
end;
function TForm1.FindImageOnScreen: TPoint;
var
ScreenBitmap: TBitmap;
X, Y, I, J: Integer;
ScreenColor: TColor;
Found: Boolean;
StartTime: Cardinal;
begin
Result := Point(-1, -1);
StartTime := GetTickCount;
ScreenBitmap := TBitmap.Create;
try
ScreenBitmap.Width := Screen.Width;
ScreenBitmap.Height := Screen.Height;
ScreenBitmap.PixelFormat := pf32bit;
BitBlt(ScreenBitmap.Canvas.Handle, 0, 0, Screen.Width, Screen.Height,
FScreenDC, 0, 0, SRCCOPY);
// First pass: Search for rarest colors
for I := 0 to High(FColorRarity) do
begin
// Search for this color in the screen
for Y := 0 to ScreenBitmap.Height - FSearchImage.Height do
begin
for X := 0 to ScreenBitmap.Width - FSearchImage.Width do
begin
ScreenColor := GetPixelColorFast(ScreenBitmap, X, Y);
if ScreenColor = FSearchColors[FColorRarity[I]] then
begin
// Found a candidate pixel, check full image
if ComparePixelsASM(ScreenBitmap, FSearchImage, X, Y) then
begin
Result := Point(X, Y);
Exit;
end;
end;
// Timeout check (prevent freezing)
if (GetTickCount - StartTime) > 5000 then
begin
ShowMessage('Search timed out after 5 seconds');
Exit;
end;
end;
end;
end;
finally
ScreenBitmap.Free;
end;
end;
procedure TForm1.btnFindImageClick(Sender: TObject);
var
FoundPoint: TPoint;
begin
FoundPoint := FindImageOnScreen;
if FoundPoint.X = -1 then
ShowMessage('Image not found on screen.')
else
begin
ShowMessage(Format('Image found at X: %d, Y: %d', [FoundPoint.X, FoundPoint.Y]));
// Example of how to click on the found position
// SetCursorPos(FoundPoint.X + FSearchImage.Width div 2,
// FoundPoint.Y + FSearchImage.Height div 2);
// mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
// mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
end;
end;
end.