RGB 转 HSV(H-色读,S-饱和度,V-亮度) 的算法 max = maximum of RGB min = minimum of RGB V = max S = (max - min) / max if S = 0, H is undefined, else delta = max-min if R = max, H = (G-b)/delta if G = max, H = 2 + (B-R)/delta if B = max, H = 4 + (R-G)/delta H = H*60 if H < 0, H = H + 360
const HLSMAX = 240; RGBMAX = 255; UnDefined = 160; // = HLSMax * 2 div 3 procedure RGB2HLS(R, G, B: Word; var H, L, S: Word); var cMax,cMin : Word; Rdelta,Gdelta,Bdelta : WORD; HH : integer; begin cMax := Max(Max(R,G) , B); cMin := Min(Min(R,G) , B); L := ((cMax+cMin)*HLSMAX + RGBMAX) div (RGBMAX + RGBMAX); if cMax = cMin then begin H := UnDefined; S := 0; end else begin if (L <= HLSMAX div 2) then S := (((cMax-cMin)*HLSMAX) + ((cMax+cMin) div 2)) div (cMax+cMin) else S := (((cMax-cMin)*HLSMAX) + ((RGBMAX+RGBMAX-cMax-cMin) div 2)) div (RGBMAX+RGBMAX-cMax-cMin); Rdelta := (((cMax-R)*(HLSMAX div 6)) + ((cMax-cMin) div 2) ) div (cMax-cMin); Gdelta := (((cMax-G)*(HLSMAX div 6)) + ((cMax-cMin) div 2) ) div (cMax-cMin); Bdelta := (((cMax-B)*(HLSMAX div 6)) + ((cMax-cMin) div 2) ) div (cMax-cMin); if (R = cMax) then HH := Bdelta - Gdelta else if (G = cMax) then HH := (HLSMAX div 3) + Rdelta - Bdelta else HH := ((HLSMAX+HLSMAX) div 3) + Gdelta - Rdelta; if (HH < 0) then HH := HH + HLSMAX; if (HH > HLSMAX) then HH := HH - HLSMAX; H := HH; end; end;
begin
Form1.Canvas.Pen.Color := clBtnFace;
Memo1.Lines.Add('Red := ' +
IntToStr(GetRValue(Form1.Canvas.Pen.Color)));
Memo1.Lines.Add('Green := ' +
IntToStr(GetGValue(Form1.Canvas.Pen.Color)));
Memo1.Lines.Add('Blue := ' +
IntToStr(GetBValue(Form1.Canvas.Pen.Color)));
end;
max = maximum of RGB
min = minimum of RGB
V = max
S = (max - min) / max
if S = 0, H is undefined,
else delta = max-min
if R = max, H = (G-b)/delta
if G = max, H = 2 + (B-R)/delta
if B = max, H = 4 + (R-G)/delta
H = H*60
if H < 0, H = H + 360
RGBMAX = 255;
UnDefined = 160; // = HLSMax * 2 div 3
procedure RGB2HLS(R, G, B: Word; var H, L, S: Word);
var cMax,cMin : Word;
Rdelta,Gdelta,Bdelta : WORD;
HH : integer;
begin
cMax := Max(Max(R,G) , B);
cMin := Min(Min(R,G) , B); L := ((cMax+cMin)*HLSMAX + RGBMAX) div (RGBMAX + RGBMAX); if cMax = cMin then
begin
H := UnDefined;
S := 0;
end else begin
if (L <= HLSMAX div 2) then
S := (((cMax-cMin)*HLSMAX) + ((cMax+cMin) div 2)) div (cMax+cMin)
else
S := (((cMax-cMin)*HLSMAX) + ((RGBMAX+RGBMAX-cMax-cMin) div 2))
div (RGBMAX+RGBMAX-cMax-cMin); Rdelta := (((cMax-R)*(HLSMAX div 6)) + ((cMax-cMin) div 2) ) div (cMax-cMin);
Gdelta := (((cMax-G)*(HLSMAX div 6)) + ((cMax-cMin) div 2) ) div (cMax-cMin);
Bdelta := (((cMax-B)*(HLSMAX div 6)) + ((cMax-cMin) div 2) ) div (cMax-cMin); if (R = cMax) then
HH := Bdelta - Gdelta
else if (G = cMax) then
HH := (HLSMAX div 3) + Rdelta - Bdelta
else
HH := ((HLSMAX+HLSMAX) div 3) + Gdelta - Rdelta; if (HH < 0) then
HH := HH + HLSMAX;
if (HH > HLSMAX) then
HH := HH - HLSMAX;
H := HH;
end;
end;