Skip to content

Instantly share code, notes, and snippets.

@zischwartz
Created March 23, 2016 19:54
Show Gist options
  • Save zischwartz/830749e2fad3e312860a to your computer and use it in GitHub Desktop.
Save zischwartz/830749e2fad3e312860a to your computer and use it in GitHub Desktop.
Convert RGB to L*ab color space in Swift
//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))
}
@lws803
Copy link

lws803 commented Oct 17, 2016

Is this updated for swift3?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment