Advertisement
WarPie90

Optimized ThresholdAdaptive

Aug 11th, 2014
487
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 1.58 KB | None | 0 0
  1. procedure TMufasaBitmap.ThresholdAdaptive(Alpha, Beta: Byte; Invert:Boolean; Method:TThreshAlgo; C:Integer); cdecl;
  2. var
  3.   i,size:Int32;
  4.   upper:PtrUInt;
  5.   vMin,vMax,threshold: UInt8;
  6.   Counter: Int64;
  7.   Tab: Array [0..256] of UInt8;
  8.   ptr:PRGB32;
  9. begin
  10.   if Alpha = Beta then Exit;
  11.   if Alpha > Beta then Swap(Alpha, Beta);
  12.  
  13.   size := (Self.Width * Self.Height) - 1;
  14.   upper := PtrUInt(@Self.FData[size]);
  15.   //Finding the threshold - While at it convert image to grayscale.
  16.   Threshold := 0;
  17.   case Method of
  18.     //Find the Arithmetic Mean / Average.
  19.     TM_MEAN:
  20.     begin
  21.       Counter := 0;
  22.       ptr := Self.FData;
  23.       while PtrUInt(Ptr) <= upper do
  24.       begin
  25.         Ptr^.B := (Ptr^.B + Ptr^.G + Ptr^.R) div 3;
  26.         Counter += Ptr^.B;
  27.         Inc(Ptr);
  28.       end;
  29.       threshold := (Counter div size) + C;
  30.     end;
  31.  
  32.     //Middle of Min- and Max-value
  33.     TM_MINMAX:
  34.     begin
  35.       vMin := 255;
  36.       vMax := 0;
  37.       ptr := Self.FData;
  38.       while PtrUInt(Ptr) <= upper do
  39.       begin
  40.         ptr^.B := (ptr^.B + ptr^.G + ptr^.R) div 3;
  41.         if ptr^.B < vMin then
  42.           vMin := ptr^.B
  43.         else if ptr^.B > vMax then
  44.           vMax := ptr^.B;
  45.         Inc(ptr);
  46.       end;
  47.       threshold := ((vMax+Int32(vMin)) shr 1) + C;
  48.     end;
  49.   end;
  50.  
  51.   if Invert then Swap(Alpha, Beta);
  52.   for i:=0 to (Threshold-1) do Tab[i] := Alpha;
  53.   for i:=Threshold to 255 do Tab[i] := Beta;
  54.  
  55.   ptr := Self.FData;
  56.   while PtrUInt(Ptr) <= upper do
  57.   begin
  58.     ptr^.R := Tab[Ptr^.B];
  59.     ptr^.G := 0;
  60.     ptr^.B := 0;
  61.     ptr^.A := 0;
  62.     Inc(ptr);
  63.   end;
  64. end;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement