matlab练习程序(RGB2HSL、HSL2RGB)

  色相饱和度亮度和三原色的相互转换

function main
    img=imread('lena_color.jpg');
    img=mat2gray(img);  %任意区间映射到[0,1];
    [m n dim]=size(img);
    imshow(img);
    %%图像的RGB
    R=img(:,:,1);
    G=img(:,:,2);
    B=img(:,:,3);

   %%图像RGB2HSL
    H=zeros(m,n);   %色相角
    S=zeros(m,n);   %饱和度
    L=zeros(m,n);   %亮度
    for i=1:m
        for j=1:n
           r=R(i,j);
           g=G(i,j);
           b=B(i,j);
           MAX=max([r,g,b]);
           MIN=min([r,g,b]);

           if MAX==MIN
                H(i,j)=0;
           elseif MAX==r && g>=b
                H(i,j)=60*(g-b)/(MAX-MIN);
           elseif MAX==r && g<b
                H(i,j)=60*(g-b)/(MAX-MIN)+360;
           elseif MAX==g
                H(i,j)=60*(b-r)/(MAX-MIN)+120;
           elseif MAX==b
                H(i,j)=60*(r-g)/(MAX-MIN)+240;
           end

           L(i,j)=(MAX+MIN)/2;

           if L(i,j)==0 || MAX==MIN
                S(i,j)=0;
           elseif 0<L(i,j) && L(i,j)<=0.5
                S(i,j)=(MAX-MIN)/(2*L(i,j));
           elseif L(i,j)>0.5
                S(i,j)=(MAX-MIN)/(2-2*L(i,j));
           end
        end
    end

    wa=waitbar(0,'wait');
    %%图像HSL2RGB
    for i=1:m
        for j=1:n
            s=S(i,j);   
            l=L(i,j);         
            if s~=0
                h=H(i,j);      
                if l<0.5
                    q=l*(1+s);
                else
                    q=l+s-(l*s);
                end
                p=2*l-q;
                hk=h/360;
                tR=hk+1/3;
                tG=hk;
                tB=hk-1/3;
           
                R(i,j)=foo(tR,p,q);
                G(i,j)=foo(tG,p,q);
                B(i,j)=foo(tB,p,q);
            else
                R(i,j)=l;
                G(i,j)=l;
                B(i,j)=l;
            end
        end
        waitbar(i/m);
    end
    close(wa);
    
    function re=foo(t,p,q)
        if t<0
            t=t+1.0;
        elseif t>1
            t=t-1.0;
        end
        
        if t<1/6
            re=p+((q-p)*6*t);
        elseif 1/6<=t && t<0.5
            re=q;
        elseif 0.5<=t && t<2/3
            re=p+((q-p)*6*(2/3-t));
        else
            re=p;
        end
    end    
    
    %%如果正反变换都没错的话,那么图像是不变的
    img(:,:,1)=R;
    img(:,:,2)=G;
    img(:,:,3)=B;
    figure;
    imshow(img)

end

参考:http://zh.wikipedia.org/wiki/HSV_%E8%89%B2%E5%BD%A9%E7%A9%BA%E9%97%B4#.E4.BB.8E_HSV_.E5.88.B0_RGB_.E7.9A.84.E8.BD.AC.E6.8D.A2

你可能感兴趣的:(matlab)