Introduction to spectra2rgb

Overview

spectra2rgb converts hyperspectral reflectance signatures to sRGB hex codes and CIELAB coordinates. It bundles the CIE 1931 standard observer and D65 illuminant, so no external colour-science package is required.

Quick start

library(spectra2rgb)

wl  <- seq(400, 700, by = 10)
ref <- 0.1 + 0.6 * exp(-((wl - 550) / 60)^2)   # synthetic green peak

hs_to_xyz(wl, ref)
#>          X        Y        Z
#> 1 36.62317 52.90519 19.42392
xyz_to_rgb(hs_to_xyz(wl, ref))
#>     R   G  B     hex
#> 1 159 207 90 #9FCF5A

Data-frame workflow

set.seed(1)
wl  <- seq(400, 700, by = 10)
mat <- matrix(runif(5 * length(wl), 0.1, 0.9), nrow = 5)
colnames(mat) <- as.character(wl)
df  <- as.data.frame(mat)

spectra_to_rgb_lab(df, id_col = paste0("leaf_", 1:5))
#>   Sample_ID   R   G   B     hex        L         a         b
#> 1    leaf_1 208 180 193 #D0B4C1 76.00948 12.239545 -2.876998
#> 2    leaf_2 189 195 167 #BDC3A7 77.66141 -6.993776 13.378715
#> 3    leaf_3 176 177 186 #B0B1BA 72.37501  1.385273 -4.708219
#> 4    leaf_4 233 175 176 #E9AFB0 76.75054 21.293901  7.753842
#> 5    leaf_5 213 199 179 #D5C7B3 80.87628  1.597983 11.767690

Missing values

df2 <- df
df2[2, ] <- NA

# Silent zero-fill (default):
spectra_to_rgb(df2, na_action = "zero")
#>   Sample_ID   R   G   B     hex
#> 1         1 208 180 193 #D0B4C1
#> 2         2   0   0   0 #000000
#> 3         3 176 177 186 #B0B1BA
#> 4         4 233 175 176 #E9AFB0
#> 5         5 213 199 179 #D5C7B3

# Drop with warning:
suppressWarnings(spectra_to_rgb(df2, na_action = "drop"))
#>   Sample_ID   R   G   B     hex
#> 1         1 208 180 193 #D0B4C1
#> 2         3 176 177 186 #B0B1BA
#> 3         4 233 175 176 #E9AFB0
#> 4         5 213 199 179 #D5C7B3

# Preserve NA:
spectra_to_rgb(df2, na_action = "keep")
#>   Sample_ID   R   G   B     hex
#> 1         1 208 180 193 #D0B4C1
#> 2         2  NA  NA  NA    <NA>
#> 3         3 176 177 186 #B0B1BA
#> 4         4 233 175 176 #E9AFB0
#> 5         5 213 199 179 #D5C7B3