# [R] [OT] two question about color space.

Jinsong Zhao jszhao at mail.hzau.edu.cn
Sat Mar 14 14:08:37 CET 2009

```> Hi,
>
> For a good discussion of the link between colour and spectra I would
> suggest,
>
> http://www.fourmilab.ch/documents/specrend/
>
> which provides an open-source C code to perform the conversion you ask
> for. I asked for some advice on how to wrap a R function around this
> code last week but sadly I didn't get anywhere. Do let me know if you
> succeed. (alternatively, one could port the implementation in pure R
> as the code is not too complicated or computationally demanding).
>
> Hope this helps,
>
> baptiste
>

I have visited the site before I posted my question. I don't know what's
the relationship between black body spectra and specific wavelength.
And frankly, I don't understand C.

I have translate a Fortran code
(http://www.isc.tamu.edu/~astro/color/spectra.html) to R as given below,
however, I don't know how to modify it and make it could accept a
vector, e.g., 380:780, as input.

And when plot a line, how to color the line using different color?

Jinsong

wl2rgb <- function(wl, gamma) {
if (missing(gamma)) gamma <- 1
if (wl >= 380 & wl <= 440) {
r <- -1 * (wl - 440) / (440 - 380)
g <- 0
b <- 1
}
if (wl >= 440 & wl <= 490 ) {
r <- 0
g <- (wl - 440) / (490 - 440)
b <- 1
}
if (wl >= 490 & wl <= 510) {
r <- 0
g <- 1
b <- -1 * (wl - 510) / (510 - 490)
}
if (wl >= 510 & wl <= 580) {
r <- (wl - 510) / (580 - 510)
g <- 1
b <- 0
}
if (wl >= 580 & wl <= 645) {
r <- 1
g <- -1 * (wl - 645) / (645 - 580)
b <- 0
}
if (wl >= 645 & wl <= 780) {
r <- 1
g <- 0
b <- 0
}
s <- 1
if (wl > 700) {
s <- .3 + .7 * (780 - wl) / (780 - 700)
}
if ( wl < 420) {
s <- .3 + .7 * (wl - 380) / (420 - 380)
}
r <- as.integer(255 * (s * r)^gamma)
g <- as.integer(255 * (s * g)^gamma)
b <- as.integer(255 * (s * b)^gamma)
return(rgb(r, g, b, maxColorValue = 255))
}

```