RGBとHSVの変換公式をDelphiのコードで書いてみた。
解説もへったくれもないのでコードだけで。
今回はRGBはそれぞれ256段階、HSVはHを0〜359度、SVを256段階にまとめてみた。
間違いがあったら指摘よろしく!
RGB→HSV
procedure RGBtoHSV(Red,Green,Blue: Integer; var Hue,Saturation,Value: Integer);
var
CMax,CMin,CG,R,G,B,H,S,V: Integer;
begin
H:= Hue;
R:= Red;
G:= Green;
B:= Blue;
CMax:= Max(R,Max(G,B));
CMin:= Min(R,Min(G,B));
V:= CMax;
if V = 0 then
begin
//V=0の時
Hue:= H;
Saturation:= 0;
Value:= 0;
end
else
begin
//V<>0の時
S:= Round(255*(CMax - CMin) / CMax);
if CMax <> CMin then
begin
CG:= CMax - CMin;
if R = CMax then
begin
H:= Round(60 * (G-B) / CG);
end
else
begin
if G = CMax then
begin
H:= Round(60 * (2 + (B-R) / CG));
end
else
begin
if B = CMax then
begin
H:= Round(60 * (4 + (R-G) / CG));
end;
end;
end;
if H < 0 then
begin
H:= H+360;
end;
end;
Hue:= H;
Saturation:= S;
Value:= V;
end;
end;
HSV→RGB
procedure HSVtoRGB(Hue,Saturation,Value: Integer; var Red,Green,Blue: Integer);
var
H,S,V,R,G,B,M,N,K,Hi: Integer;
F: Extended;
begin
H:= Hue;
S:= Saturation;
V:= Value;
if S = 0 then
begin
Red:= V;
Green:= V;
Blue:= V;
end
else
begin
//S <> 0
R:= Red;
G:= Green;
B:= Blue;
Hi:= Floor(H / 60);
F:= H/60 - Hi;
M:= Round(V*(1-S/255));
N:= Round(V*(1-S/255*F));
K:= Round(V*(1-S/255*(1-F)));
case Hi of
0:
begin
R:= V;
G:= K;
B:= M;
end;
1:
begin
R:= N;
G:= V;
B:= M;
end;
2:
begin
R:= M;
G:= V;
B:= K;
end;
3:
begin
R:= M;
G:= N;
B:= V;
end;
4:
begin
R:= K;
G:= M;
B:= V;
end;
5:
begin
R:= V;
G:= M;
B:= N;
end;
end;
Red:= R;
Green:= G;
Blue:= B;
end;
end;
※RGB→HSV→RGBとした時に元の数値と変動することがあるのは仕様ですよ。