Stéphane Laurent
Stéphane Laurent

Reputation: 84649

wrong color conversion with colorspace package

Look at the following example:

> library(colorspace)
> # convert color with coordinates (0.2,0.3,0.4) in the RGB space into a character string:
> ( x <- hex(RGB(0.2,0.3,0.4)) )
[1] "#7C95AA"
> # reverse conversion:
> hex2RGB(x)  ## not the original coordinates !
             R         G         B
[1,] 0.4862745 0.5843137 0.6666667
> # now do the first conversion with the rgb() function from grDevices package:
> library(grDevices)
> ( y <- rgb(0.2,0.3,0.4) )
[1] "#334C66"
> # reverse conversion:
> hex2RGB(y)  ## close to the original coordinates
       R         G   B
[1,] 0.2 0.2980392 0.4

It seems that the conversion of three coordinates in the RGB color space into a character string is wrong with the hex() function from the colorspace package. Is it a bug, or is it me who wrongly use the package ?

Upvotes: 2

Views: 418

Answers (1)

Achim Zeileis
Achim Zeileis

Reputation: 17203

The difference in the conversion is due using the linearized RGB color model instead of the gamma-corrected sRGB color model. The latter is employed by base R and most other software that generates colors for graphics. The former is relevant as an intermediate step to converting to other models such as CIE XYZ, also provided in the colorspace package as illustrated below.

colorspace

If you are using the sRGB function your example works as expected:

library("colorspace")
( x <- hex(sRGB(0.2, 0.3, 0.4)) )
## [1] "#334D66"
hex2RGB(x)
##        R         G   B
## [1,] 0.2 0.3019608 0.4

The reason for the difference on the G coordinate is that 0.3 * 255 is not an integer. (The hex color codes integers 0 to 255.)

Upvotes: 0

Related Questions