Skip to content

Instantly share code, notes, and snippets.

@TellAnAx
Last active August 4, 2022 15:08
Show Gist options
  • Save TellAnAx/06ace666a92d0849d6b774de1790cc7a to your computer and use it in GitHub Desktop.
Save TellAnAx/06ace666a92d0849d6b774de1790cc7a to your computer and use it in GitHub Desktop.
R function to convert from RGB to CIELAB color space. Code adapted from Python version https://gist.github.com/manojpandey/f5ece715132c572c80421febebaf66ae
# RGB to Lab conversion
# Step 1: RGB to XYZ
# http://www.easyrgb.com/index.php?X=MATH&H=02#text2
# Step 2: XYZ to Lab
# http://www.easyrgb.com/index.php?X=MATH&H=07#text7
rgb2lab <- function(inputColor, maxColorValue = 255){
num <- 1
RGB <- c(0, 0, 0)
for(value in inputColor){
value <- value / maxColorValue
if(value > 0.04045){
value <- ((value + 0.055) / 1.055)^2.4
} else{
value <- value / 12.92
}
RGB[num] <- value * 100
num <- num + 1
}
XYZ <- c(0, 0, 0)
X = RGB[1] * 0.4124 + RGB[2] * 0.3576 + RGB[3] * 0.1805
Y = RGB[1] * 0.2126 + RGB[2] * 0.7152 + RGB[3] * 0.0722
Z = RGB[1] * 0.0193 + RGB[2] * 0.1192 + RGB[3] * 0.9505
XYZ[1] = round(X, 4)
XYZ[2] = round(Y, 4)
XYZ[3] = round(Z, 4)
# Observer= 2°, Illuminant= D65
XYZ[1] = XYZ[1] / 95.047 # ref_X = 95.047
XYZ[2] = XYZ[2] / 100.0 # ref_Y = 100.000
XYZ[3] = XYZ[3] / 108.883 # ref_Z = 108.883
num = 1
for(value in XYZ){
if(value > 0.008856){
value = value ** (0.3333333333333333)
} else{
value = (7.787 * value) + (16 / 116)
}
XYZ[num] <- value
num <- num + 1
}
Lab <- c(0, 0, 0)
L = (116 * XYZ[2]) - 16
a = 500 * (XYZ[1] - XYZ[2])
b = 200 * (XYZ[2] - XYZ[3])
Lab[1] = round(L, 4)
Lab[2] = round(a, 4)
Lab[3] = round(b, 4)
return(Lab)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment