Created
March 23, 2016 19:54
-
-
Save zischwartz/830749e2fad3e312860a to your computer and use it in GitHub Desktop.
Convert RGB to L*ab color space in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//http://stackoverflow.com/a/24201042/83859 | |
infix operator ^^ { } | |
func ^^ (radix: Double, power: Double) -> Double { | |
return Double(pow(Double(radix), Double(power))) | |
} | |
//Based on https://github.com/d3/d3-color/blob/master/src/lab.js | |
let Kn:Double = 18, | |
Xn:Double = 0.950470, // D65 standard referent | |
Yn:Double = 1, | |
Zn:Double = 1.088830, | |
t0:Double = 4 / 29, | |
t1:Double = (6 / 29), | |
t2:Double = 3 * t1 * t1, | |
t3:Double = t1 * t1 * t1; | |
func rgb2xyz(x:Double) -> Double { | |
let val = x/255; | |
if val <= 0.04045 | |
{ return (val / 12.92)} | |
else { return ((val + 0.055) / 1.055^^2.4); } | |
} | |
func xyz2lab(tee:Double) -> Double{ | |
if tee > t3 { return (tee^^(1/3));} | |
else { return tee / t2 + t0 ;} | |
} | |
func rgb_to_lab(red:Double, green:Double, blue:Double) -> (Double, Double, Double) | |
{ | |
let b = rgb2xyz(red), | |
a = rgb2xyz(green), | |
l = rgb2xyz(blue), | |
x = xyz2lab((0.4124564 * b + 0.3575761 * a + 0.1804375 * l) / Xn), | |
y = xyz2lab((0.2126729 * b + 0.7151522 * a + 0.0721750 * l) / Yn), | |
z = xyz2lab((0.0193339 * b + 0.1191920 * a + 0.9503041 * l) / Zn); | |
return (116 * y - 16, 500 * (x - y), 200 * (y - z)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is this updated for swift3?