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 143 210 96 #8FD260

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 191 184 201 #BFB8C9 75.94563   5.473204 -7.532564
#> 2    leaf_2 172 199 175 #ACC7AF 77.70915 -13.652753  9.003911
#> 3    leaf_3 158 181 194 #9EB5C2 72.32000  -4.948629 -9.435452
#> 4    leaf_4 218 181 184 #DAB5B8 76.85865  14.004340  3.584069
#> 5    leaf_5 196 204 187 #C4CCBB 80.92846  -5.719798  7.240532

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 191 184 201 #BFB8C9
#> 2         2   0   0   0 #000000
#> 3         3 158 181 194 #9EB5C2
#> 4         4 218 181 184 #DAB5B8
#> 5         5 196 204 187 #C4CCBB

# Drop with warning:
suppressWarnings(spectra_to_rgb(df2, na_action = "drop"))
#>   Sample_ID   R   G   B     hex
#> 1         1 191 184 201 #BFB8C9
#> 2         3 158 181 194 #9EB5C2
#> 3         4 218 181 184 #DAB5B8
#> 4         5 196 204 187 #C4CCBB

# Preserve NA:
spectra_to_rgb(df2, na_action = "keep")
#>   Sample_ID   R   G   B     hex
#> 1         1 191 184 201 #BFB8C9
#> 2         2  NA  NA  NA    <NA>
#> 3         3 158 181 194 #9EB5C2
#> 4         4 218 181 184 #DAB5B8
#> 5         5 196 204 187 #C4CCBB