Python Lab转RGB

阅读 1716

Python 3,实现Lab转RGB颜色色域。
A simple Python 3 code to convert form Lab to RGB.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import math

def lab2rgb( inputColor ):
    num = 0
    Lab = [0, 0, 0]

    for value in inputColor:
        Lab[num] = float(value)
        num = num + 1

    xyz = [0, 0, 0]
   
    xyz[1] = (Lab[0] + 16) / 116
    xyz[0] = Lab[1] / 500 + xyz[1]
    xyz[2] = xyz[1] - float(Lab[2]) / 200

    for value in range(len(xyz)):
        if ( math.pow( xyz[value] , 3 ) > 0.008856 ):
            xyz[value] = math.pow( xyz[value] , 3 )
        else:
            xyz[value] = ( xyz[value] - 16 / 116 ) / 7.787

    xyz[0] = 95.047 * xyz[0]        # ref_X =  95.047   Observer= 2°, Illuminant= D65
    xyz[1] = 100.000 * xyz[1]       # ref_Y = 100.000
    xyz[2] = 108.883 * xyz[2]       # ref_Z = 108.883
   
    for value in range(len(xyz)):
        xyz[value] = xyz[value] / 100
   
    RGB = [0, 0, 0]    

    RGB[0] = xyz[0] * 3.24063 + xyz[1] * -1.53721 + xyz[2] * -0.498629
    RGB[1] = xyz[0] * -0.968931 + xyz[1] * 1.87576 + xyz[2] * 0.0415175
    RGB[2] = xyz[0] * 0.0557101 + xyz[1] * -0.204021 + xyz[2] * 1.0570

    for value in range(len(RGB)):
        if ( RGB[value] > 0.0031308 ):
            RGB[value] = 1.055 * math.pow( RGB[value]  , ( 1 / 2.4 ) ) - 0.055
        else:
            RGB[value] = 12.92 * RGB[value]
        RGB[value] = round( RGB[value] * 255, 4)
        if ( RGB[value] < 0 ):
            RGB[value] = 0
        elif ( RGB[value] > 255 ):
            RGB[value] = 255
   
    return RGB

示例 Example

1
2
3
4
5
if __name__ == '__main__':
    color_rgb = lab2rgb( [100, 0, 0] )
    print(color_rgb)

#Output: [254.9988, 255, 254.9802]