PDA

View Full Version : [Delphi] FindColorTolerance - Improve Speed?



CharMz
08-14-2009, 08:42 PM
type
PRGBQuadArray = ^TRGBQuadArray;
TRGBQuadArray = array [0..0] of TRGBQuad;

function FindColorTolerance(Client : HDC; TargetColor : TRGBQuad; var dx, dy : Integer; x1, y1, x2, y2, Tolerance : Integer) : Boolean;

const
Offset : array [0..0] of Integer = (1);

var
bmpW, bmpH : Integer;
bmi : TBitmapInfo;
DIBHandle : HBitmap;
CompDC : HDC;
PrevObj : HGDIOBJ;
Pixels : PRGBQuadArray;
i, l , HW : Integer;
j : Integer;

begin

Result := False;

bmpW := x2 - x1 + 1;
bmpH := y2 - y1 + 1;

FillMemory(@bmi, SizeOf(TBitmapInfo), 0);
with bmi.bmiHeader do
begin
biSize := SizeOf(TBitmapInfoHeader);
biWidth := bmpW;
biHeight := -bmpH;
biPlanes := 1;
biBitCount := 32;
biCompression := BI_RGB;
end;

try
DIBHandle := CreateDIBSection(0, bmi, DIB_RGB_COLORS, Pointer(Pixels), 0, 0);

CompDC := CreateCompatibleDC(Client);
PrevObj := SelectObject(CompDC, DIBHandle);

BitBlt(CompDC, 0, 0, bmpW, bmpH, Client, x1, y1, SRCCOPY);

l := High(Offset);

HW := ( bmpH - 1 ) * ( bmpW - 1 );

for j := 0 to l do
begin
if Result then
Break;

i := 0 - OffSet[j];
while ( i < ( HW ) - OffSet[j] ) and ( not Result ) do
begin
Inc(i, Length(OffSet));
if Sqr(Tolerance) >= (Sqr(TargetColor.rgbRed - Pixels^[i].rgbRed)
+ Sqr(TargetColor.rgbGreen - Pixels^[i].rgbGreen)
+ Sqr(TargetColor.rgbBlue - Pixels^[i].rgbBlue)) then
begin
dx := x1 + ( i mod bmpW );
dy := y1 + ( i div bmpW );
Result := True;
end;
end;
end;

finally
PrevObj := SelectObject(CompDC, PrevObj);
DeleteDC(CompDC);
DeleteObject(DIBHandle);
end;

end;

if you can make this faster, i will bake you a cake

Jamesrt2004
08-17-2009, 12:10 PM
man that looks neat!! doubt you can change that around much ill have a go though =) havnt done delphi in a year n half :D

W1zzard
08-17-2009, 02:30 PM
get rid of the sqr. what are you trying to do? elaborate
check if two images are equal yes no or calculate the difference?

CharMz
08-17-2009, 09:41 PM
get rid of the sqr. what are you trying to do? elaborate
check if two images are equal yes no or calculate the difference?

Its a pixel finder. This function checks an image for a certain pixel, and tolerance can be added if needed. It will return the x, y positition of the pixel found.

the sqr is needed to see if the tolerance of the pixel found is in range of our pixel and our tolerance range.