RGB to HSL
The R,G,B values are divided by 255 to change the range from 0..255 to
0..1:
R' = R/255
G' = G/255
B' = B/255
Cmax = max(R', G', B')
Cmin = min(R', G', B')
Δ = Cmax - Cmin
Hue calculation:
Saturation calculation:
Lightness calculation:
L = (Cmax + Cmin) / 2
HSL to RGB
When 0 ≤ H < 360, 0 ≤ S ≤ 1 and 0 ≤ L ≤ 1:
C = (1 - |2L - 1|) × S
X = C × (1 - |(H / 60º) mod 2 - 1|)
m = L - C/2
(R,G,B) = (R'+m, G'+m, B'+m)
算法参考来源:http://www.rapidtables.com/convert/color/index.htm
Code:
RGB TO HSL
function [H,S,L]=RgbToHsl(Image_Input)
Image_Input=double(Image_Input)/255;
R_Input=Image_Input(:,:,1);
G_Input=Image_Input(:,:,2);
B_Input=Image_Input(:,:,3);
[heigth,width]=size(R_Input);
S(1:heigth,1:width)=0;
H(1:heigth,1:width)=0;
L(1:heigth,1:width)=0;
for i=1:heigth
for j=1:width
temp=[R_Input(i,j),G_Input(i,j),B_Input(i,j)];
Max_value=max(temp);
Min_value=min(temp);
C_value=Max_value-Min_value;
L(i,j)=(Max_value+Min_value)/2;
if(C_value==0)
S(i,j)=0;
else
S(i,j)=C_value/(1-abs(2*L(i,j)-1));
end
X=R_Input(i,j);
Y=G_Input(i,j);
Z=B_Input(i,j);
if(C_value==0)
continue;
end
if(Max_value==X)
H(i,j)=mod((Y-Z)/C_value,6);
elseif(Max_value==Y)
H(i,j)=(Z-X)/C_value+2;
else
H(i,j)=(X-Y)/C_value+4;
end
H(i,j)=H(i,j)/6;
end
end
HSL to RGB
function Image_out=HslToRgb(H,S,L)
%% H(0,1),S(0,1),L(0,1)
[height,width]=size(H);
R(1:height,1:width)=0;
G(1:height,1:width)=0;
B(1:height,1:width)=0;
for i=1:height
for j=1:width
C=(1-abs(2*L(i,j)-1))*S(i,j);
X=C*(1-abs(mod(H(i,j)*6,2)-1));
m=L(i,j)-C/2;
temp=floor(H(i,j)*6+1);
switch(temp)
case 1
R(i,j)=C+m;
G(i,j)=X+m;
B(i,j)=m;
case 2
R(i,j)=X+m;
G(i,j)=C+m;
B(i,j)=m;
case 3
R(i,j)=m;
G(i,j)=C+m;
B(i,j)=X+m;
case 4
R(i,j)=m;
G(i,j)=X+m;
B(i,j)=C+m;
case 5
R(i,j)=X+m;
G(i,j)=m;
B(i,j)=C+m;
case 6
R(i,j)=C+m;
G(i,j)=m;
B(i,j)=X+m;
end
end
end
Image_out(:,:,1)=R;
Image_out(:,:,2)=G;
Image_out(:,:,3)=B;