1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
unit ImageUtils;
interface
uses
System.SysUtils, System.UITypes, System.UIConsts , System.Math,
FMX.Types, FMX.Graphics, FMX.Utils;
type Talgorithm = (algnone,algluminosity,algaverage,alglightness);
function ConvertToGrayscale(const aBitmap: TBitmap; const aMethod : TAlgorithm=algnone) : TBitmap;
implementation
function Colortogray(const aColor : Talphacolor; const aAlgo : TAlgorithm=algnone) : Talphacolor;
var
H,S,L : Single;
C : TAlphacolorRec;
// https://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/
begin
RGBToHSL(aColor,H,S,L);
c.Color:=acolor;
case aAlgo of
algluminosity: begin // erreur
L:=0.21*c.R + 0.72*c.G + 0.07*c.B;
Exit(HSLToRGB(H,S,L));
end;
algaverage: begin
var mean : integer := (c.R + c.G + c.B) div 3;
c.R:=mean;
c.G:=mean;
c.B:=mean;
Exit(c.Color);
end;
alglightness: begin
H:=(maxvalue([TAlphacolorRec(aColor).R,TAlphacolorRec(aColor).G,TAlphacolorRec(aColor).B]) +
minvalue([TAlphacolorRec(aColor).R,TAlphacolorRec(aColor).G,TAlphacolorRec(aColor).B])) / 2;
Exit(HSLToRGB(H,S,L));
end;
else Exit(HSLtoRGB(0,0, L));
end;
end;
function ConvertToGrayscale(const aBitmap: TBitmap; const aMethod : TAlgorithm=algnone): TBitmap;
var
X, Y: Integer;
bd1, bd2: TBitmapData;
p1, p2: PAlphaColorArray;
begin
Result := TBitmap.Create(Round(aBitmap.Width), Round(aBitmap.Height));
if (aBitmap.Map(TMapAccess.Read, bd1)
and Result.Map(TMapAccess.Write, bd2)) then
begin
try
for Y := 0 to (aBitmap.Height - 1) do
begin
p1 := PAlphaColorArray(bd1.GetScanline(Y));
p2 := PAlphaColorArray(bd2.GetScanline(Y));
for X := 0 to (aBitmap.Width - 1) do
begin
p2[X] := Colortogray(p1[X],aMethod);
end;
end;
finally
aBitmap.Unmap(bd1);
Result.Unmap(bd2);
end;
end;
end;
end. |
Partager