由于工作要求,需要把rgb颜色转成Lab颜色空间。网上一搜一大把的代码,但是和PS一对比,基本上都不对。
下面这张图是OpenCV官方文档的计算方法。
用Python实现代码如下:
from math import pow
param_13 = 1.0 / 3.0
param_16116 = 16.0 / 116.0
Xn = 0.950456
Yn = 1.0
Zn = 1.088754
def RGB2XYZ(r, g, b):
x = 0.412453 * r + 0.357580 * g + 0.180423 * b
y = 0.212671 * r + 0.715160 * g + 0.072169 * b
z = 0.019334 * r + 0.119193 * g + 0.950227 * b
return x, y, z
def XYZ2Lab(x, y, z):
x /= 255 * Xn
y /= 255 * Yn
z /= 255 * Zn
if y > 0.008856:
fy = pow(y, param_13)
l = 116.0 * fy - 16.0
else:
fy = 7.787 * y + param_16116
l = 903.3 * fy
if l < 0:
l = 0.0
if x>0.008856:
fx = pow(x,param_13)
else:
fx = 7.787 * x + param_16116
if z>0.008856:
fz = pow(z,param_13)
else:
fz = 7.787 * z + param_16116
a = 500.0*(fx-fy)
b = 200.0*(fy-fz)
return [round(l,2), round(a,2), round(b,2)]
def RGB2Lab(r, g, b):
x, y, z = RGB2XYZ(r, g, b)
return XYZ2Lab(x, y, z)
if __name__ == '__main__':
rgb = [134, 156, 106]
print("Lab: " + str(rgb))
lab = RGB2Lab(rgb[0], rgb[1], rgb[2])
print("Lab: " + str(lab))
下面测试一下运行结果:
rgb: [255, 0, 0]
Lab: [53.24, 80.09, 67.2]
rgb: [134, 156, 106]
Lab: [80.7, -10.37, 14.71]
rgb: [110, 99, 165]
Lab: [70.6, 11.6, -20.76]
从对比可以看出当rbg为(255,0,0)时和PS的着色器对比基本差不多,但是后面两个就差得多了。
于是乎经过一番操作,终于实现了和PS结果一样的算法,代码如下:
def rgb2lab(rgb):
r = rgb[0] / 255.0 # rgb range: 0 ~ 1
g = rgb[1] / 255.0
b = rgb[2] / 255.0
# gamma 2.2
if r > 0.04045:
r = pow((r + 0.055) / 1.055, 2.4)
else:
r = r / 12.92
if g > 0.04045:
g = pow((g + 0.055) / 1.055, 2.4)
else:
g = g / 12.92
if b > 0.04045:
b = pow((b + 0.055) / 1.055, 2.4)
else:
b = b / 12.92
# sRGB
X = r * 0.436052025 + g * 0.385081593 + b * 0.143087414
Y = r * 0.222491598 + g * 0.716886060 + b * 0.060621486
Z = r * 0.013929122 + g * 0.097097002 + b * 0.714185470
# XYZ range: 0~100
X = X * 100.000
Y = Y * 100.000
Z = Z * 100.000
# Reference White Point
ref_X = 96.4221
ref_Y = 100.000
ref_Z = 82.5211
X = X / ref_X
Y = Y / ref_Y
Z = Z / ref_Z
# Lab
if X > 0.008856:
X = pow(X, 1 / 3.000)
else:
X = (7.787 * X) + (16 / 116.000)
if Y > 0.008856:
Y = pow(Y, 1 / 3.000)
else:
Y = (7.787 * Y) + (16 / 116.000)
if Z > 0.008856:
Z = pow(Z, 1 / 3.000)
else:
Z = (7.787 * Z) + (16 / 116.000)
Lab_L = round((116.000 * Y) - 16.000, 2)
Lab_a = round(500.000 * (X - Y), 2)
Lab_b = round(200.000 * (Y - Z), 2)
return Lab_L, Lab_a, Lab_b
对比一下结果:
rgb: [255, 0, 0]
Lab: (54.29, 80.81, 69.89)
rgb: [134, 156, 106]
Lab: (61.66, -14.83, 23.57)
rgb: [110, 99, 165]
Lab: (45.21, 16.45, -34.45)
从结果可以看出和PS的结果基本一致。