mathieu@14
|
1 function hsl=rgb2hsl(rgb)
|
mathieu@14
|
2
|
mathieu@14
|
3 %Converts Red-Green-Blue Color value to Hue-Saturation-Luminance Color value
|
mathieu@14
|
4 %
|
mathieu@14
|
5 %Usage
|
mathieu@14
|
6 % HSL = rgb2hsl(RGB)
|
mathieu@14
|
7 %
|
mathieu@14
|
8 % converts RGB, a M X 3 color matrix with values between 0 and 1
|
mathieu@14
|
9 % into HSL, a M X 3 color matrix with values between 0 and 1
|
mathieu@14
|
10 %
|
mathieu@14
|
11 %See also hsl2rgb, rgb2hsv, hsv2rgb
|
mathieu@14
|
12
|
mathieu@14
|
13 %Suresh E Joel, April 26,2003
|
mathieu@14
|
14
|
mathieu@14
|
15 if nargin<1,
|
mathieu@14
|
16 error('Too few arguements for rgb2hsl');
|
mathieu@14
|
17 return;
|
mathieu@14
|
18 elseif nargin>1,
|
mathieu@14
|
19 error('Too many arguements for rgb2hsl');
|
mathieu@14
|
20 return;
|
mathieu@14
|
21 end;
|
mathieu@14
|
22
|
mathieu@14
|
23 if max(max(rgb))>1 | min(min(rgb))<0,
|
mathieu@14
|
24 error('RGB values have to be between 0 and 1');
|
mathieu@14
|
25 return;
|
mathieu@14
|
26 end;
|
mathieu@14
|
27
|
mathieu@14
|
28 for i=1:size(rgb,1),
|
mathieu@14
|
29 mx=max(rgb(i,:));%max of the 3 colors
|
mathieu@14
|
30 mn=min(rgb(i,:));%min of the 3 colors
|
mathieu@14
|
31 imx=find(rgb(i,:)==mx);%which color has the max
|
mathieu@14
|
32 hsl(i,3)=(mx+mn)/2;%luminance is half of max value + min value
|
mathieu@14
|
33 if(mx-mn)==0,%if all three colors have same value,
|
mathieu@14
|
34 hsl(i,2)=0;%then s=0 and
|
mathieu@14
|
35 hsl(i,1)=0;%h is undefined but for practical reasons 0
|
mathieu@14
|
36 return;
|
mathieu@14
|
37 end;
|
mathieu@14
|
38 if hsl(i,3)<0.5,
|
mathieu@14
|
39 hsl(i,2)=(mx-mn)/(mx+mn);
|
mathieu@14
|
40 else
|
mathieu@14
|
41 hsl(i,2)=(mx-mn)/(2-(mx+mn));
|
mathieu@14
|
42 end;
|
mathieu@14
|
43 switch(imx(1))%if two colors have same value and be the maximum, use the first color
|
mathieu@14
|
44 case 1 %Red is the max color
|
mathieu@14
|
45 hsl(i,1)=((rgb(i,2)-rgb(i,3))/(mx-mn))/6;
|
mathieu@14
|
46 case 2 %Green is the max color
|
mathieu@14
|
47 hsl(i,1)=(2+(rgb(i,3)-rgb(i,1))/(mx-mn))/6;
|
mathieu@14
|
48 case 3 %Blue is the max color
|
mathieu@14
|
49 hsl(i,1)=(4+(rgb(i,1)-rgb(i,2))/(mx-mn))/6;
|
mathieu@14
|
50 end;
|
mathieu@14
|
51 if hsl(i,1)<0,hsl(i,1)=hsl(i,1)+1;end;%if hue is negative, add 1 to get it within 0 and 1
|
mathieu@14
|
52 end;
|
mathieu@14
|
53
|
mathieu@14
|
54 hsl=round(hsl*100000)/100000; %Sometimes the result is 1+eps instead of 1 or 0-eps instead of 0 ... so to get rid of this I am rounding to 5 decimal places) |