Mark Ruzon发来的邮件:
代码如下:
===========================rgb2lab.m
==========================================lab2rgb.m
代码如下:
===========================rgb2lab.m
- function[L,a,b]=RGB2Lab(R,G,B)
- %function[L,a,b]=RGB2Lab(R,G,B)
- %RGB2LabtakesmatricescorrespondingtoRed,Green,andBlue,and
- %transformsthemintoCIELab.ThistransformisbasedonITU-R
- %RecommendationBT.709usingtheD65whitepointreference.
- %TheerrorintransformingRGB->Lab->RGBisapproximately
- %10^-5.RGBvaluescanbeeitherbetween0and1orbetween0and255.
- %ByMarkRuzonfromCcodebyYossiRubner,23September1997.
- %UpdatedforMATLAB528January1998.
- %
- %Ifyourimageisloadedintouint8formatasanMxNx3tensor,you
- %canpassitinasoneargument.Ifyoubreakitinto3pieces,convert
- %themintodoublebeforecallingthisfunction.
- if(nargin==1)
- B=double(R(:,:,3));
- G=double(R(:,:,2));
- R=double(R(:,:,1));
- end
- if((max(max(R))>1.0)|(max(max(G))>1.0)|(max(max(B))>1.0))
- R=R/255;
- G=G/255;
- B=B/255;
- end
- [M,N]=size(R);
- s=M*N;
- %Setathreshold
- T=0.008856;
- RGB=[reshape(R,1,s);reshape(G,1,s);reshape(B,1,s)];
- %RGBtoXYZ
- MAT=[0.4124530.3575800.180423;
- 0.2126710.7151600.072169;
- 0.0193340.1191930.950227];
- XYZ=MAT*RGB;
- X=XYZ(1,:)/0.950456;
- Y=XYZ(2,:);
- Z=XYZ(3,:)/1.088754;
- XT=X>T;
- YT=Y>T;
- ZT=Z>T;
- fX=XT.*X.^(1/3)+(~XT).*(7.787.*X+16/116);
- %ComputeL
- Y3=Y.^(1/3);
- fY=YT.*Y3+(~YT).*(7.787.*Y+16/116);
- L=YT.*(116*Y3-16.0)+(~YT).*(903.3*Y);
- fZ=ZT.*Z.^(1/3)+(~ZT).*(7.787.*Z+16/116);
- %Computeaandb
- a=500*(fX-fY);
- b=200*(fY-fZ);
- L=reshape(L,M,N);
- a=reshape(a,M,N);
- b=reshape(b,M,N);
- if((nargout==1)|(nargout==0))
- L=cat(3,L,a,b);
- end
- function[R,G,B]=Lab2RGB(L,a,b)
- %function[R,G,B]=Lab2RGB(L,a,b)
- %Lab2RGBtakesmatricescorrespondingtoL,a,andbinCIELabspace
- %andtransformsthemintoRGB.ThistransformisbasedonITU-R
- %RecommendationBT.709usingtheD65whitepointreference.
- %andtheerrorintransformingRGB->Lab->RGBisapproximately
- %10^-5.ByMarkRuzonfromCcodebyYossiRubner,23September1997.
- %UpdatedforMATLAB528January1998.
- %Fixedabuginconversionbacktouint89September1999.
- if(nargin==1)
- b=L(:,:,3);
- a=L(:,:,2);
- L=L(:,:,1);
- end
- %Thresholds
- T1=0.008856;
- T2=0.206893;
- [M,N]=size(L);
- s=M*N;
- L=reshape(L,1,s);
- a=reshape(a,1,s);
- b=reshape(b,1,s);
- %ComputeY
- fY=((L+16)/116).^3;
- YT=fY>T1;
- fY=(~YT).*(L/903.3)+YT.*fY;
- Y=fY;
- %AlterfYslightlyforfurthercalculations
- fY=YT.*(fY.^(1/3))+(~YT).*(7.787.*fY+16/116);
- %ComputeX
- fX=a/500+fY;
- XT=fX>T2;
- X=(XT.*(fX.^3)+(~XT).*((fX-16/116)/7.787));
- %ComputeZ
- fZ=fY-b/200;
- ZT=fZ>T2;
- Z=(ZT.*(fZ.^3)+(~ZT).*((fZ-16/116)/7.787));
- X=X*0.950456;
- Z=Z*1.088754;
- MAT=[3.240479-1.537150-0.498535;
- -0.9692561.8759920.041556;
- 0.055648-0.2040431.057311];
- RGB=max(min(MAT*[X;Y;Z],1),0);
- R=reshape(RGB(1,:),M,N)*255;
- G=reshape(RGB(2,:),M,N)*255;
- B=reshape(RGB(3,:),M,N)*255;
- if((nargout==1)|(nargout==0))
- R=uint8(round(cat(3,R,G,B)));
- end