I was recently making a function that needed to convert between several different colorspaces, and I decided to do it manually. @J.M. used many built-in functions to accomplish the same goal. When I was trying to delve in and see if they produced the same results, I found that visually they did, but numerically there were differences, and so I tried to track them down.
In my code, I needed a function to convert from RGB to XYZ colorspaces, and I used the recipe described on this Wikipedia page, which is the same as is used by EasyRGB, and appears in this paper.
The recipe goes as follows: first, the RGB values are converted to "linear RGB" via
$$C_\mathrm{linear}= \begin{cases}\frac{C_\mathrm{srgb}}{12.92}, & C_\mathrm{srgb}\le0.04045\\ \left(\frac{C_\mathrm{srgb}+a}{1+a}\right)^{2.4}, & C_\mathrm{srgb}>0.04045 \end{cases}$$
and then the XYZ values are obtained from a linear transformation,
$$\begin{bmatrix} X\\Y\\Z\end{bmatrix}= \begin{bmatrix} 0.4124&0.3576&0.1805\\ 0.2126&0.7152&0.0722\\ 0.0193&0.1192&0.9505 \end{bmatrix} \begin{bmatrix} R_\mathrm{linear}\\ G_\mathrm{linear}\\ B_\mathrm{linear}\end{bmatrix}$$
So I define this as a function rgb2xyz
,
rgb2xyz[r_, g_, b_] := Module[
{transm, rl, gl, bl},
{rl, gl, bl} = If[# > .04045,
((# + 0.055)/1.055)^2.4,
#/12.92] & /@ {r, g, b};
transm = {{0.4124, 0.3576, 0.1805},
{0.2126, 0.7152, 0.0722},
{0.0193, 0.1192, 0.9505}};
transm.{rl, gl, bl}
];
and then I can apply it to a test color,
testcolor = {43, 15, 155}/255.;
rgb2xyz @@ testcolor
(* {0.0708348, 0.032218, 0.312589} *)
Then I realized there is a ColorConvert
function, and test it against my function.
List @@ ColorConvert[RGBColor @@ testcolor, XYZColor]
(* {0.0592725, 0.0286686, 0.234891} *)
which seems to be a reasonably large discrepancy. Visually, I can see a very small difference
XYZColor @@@ {%, %%}
When I go to other websites, like ColorMine or EasyRGB their results agree with mine completely (although they scale their results by a factor of 100).
What is going on here? Is Mathematica using a different RGB colorspace than sRGB?
ColorConvert
$\endgroup$ – Jason B. Dec 10 '15 at 13:06