how to convert rgb to lab
5 views (last 30 days)
Show older comments
can any1 tell me how excatly this works
function [L,a,b] = RGB2Lab(R,G,B)
if nargin == 1
B = double(R(:,:,3)); .........why double
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......... why max(max())
R = double(R) / 255; ...................why 255
G = double(G) / 255;
B = double(B) / 255;
end
% Set a threshold
T = 0.008856; .............
[M, N] = size(R);
s = M * N;
RGB = [reshape(R,1,s); reshape(G,1,s); reshape(B,1,s)];
% RGB to XYZ
MAT = [0.412453 0.357580 0.180423;
0.212671 0.715160 0.072169;
0.019334 0.119193 0.950227];
XYZ = MAT * RGB;
% Normalize for D65 white point
X = XYZ(1,:) / 0.950456;
Y = XYZ(2,:);
Z = XYZ(3,:) / 1.088754;
XT = X > T;
YT = Y > T;
ZT = Z > T;
Y3 = Y.^(1/3);
fX = XT .* X.^(1/3) + (~XT) .* (7.787 .* X + 16/116);
fY = YT .* Y3 + (~YT) .* (7.787 .* Y + 16/116);
fZ = ZT .* Z.^(1/3) + (~ZT) .* (7.787 .* Z + 16/116);
L = reshape(YT .* (116 * Y3 - 16.0) + (~YT) .* (903.3 * Y), M, N);
a = reshape(500 * (fX - fY), M, N);
b = reshape(200 * (fY - fZ), M, N);
if nargout < 2
L = cat(3,L,a,b);
end
0 Comments
Answers (1)
Image Analyst
on 9 Mar 2015
No. Not really interested in explaining the formulas especially when there is a built in function to do it: rgb2lab(). Just use the built in function instead and don't worry about what the code does or if it's right, because it will be. Well, as "right" as a "book formula" can be, which of course will never give you the actual "TRUE" lab values you'd get from measuring your object with a spectrophotometer.
1 Comment
Image Analyst
on 9 Mar 2015
By the way, 255 is the max for a uint8 image and it needs to divide by that to get a "normalized" image. Why is normalized in quotes? Because it's not really normalized. I can get different "normalized" values using that method of normalization just by changing my exposure. The only way to get calibrated lab values out of a system is to show it a calibrated standard such as the X-rite Color Checker Chart and develop a transform to map RGB into LAB.
See Also
Categories
Find more on Image Processing Toolbox in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!