介绍几种常用颜色空间之间的转换算法。在转换过程中,设各个参数的变化范围为:
0≤R, G, B≤1; 0≤C, M, Y≤1; (-1)0°≤H≤360° 0≤S, V, L≤1。
1.RGB←→CMY
(1) RGB→CMY
C = 1- R M = 1- G Y = 1 - B
(2) CMY→RGB
R = 1- C G = 1- M B = 1 - Y
2.RGB←→HSL
(1) RGB→HSL
设M = max(R, G, B), m = min(R, G, B),P = M + m,D = M – m,则
L = (M + m)/2
若M = m,则S = H = 0
若M ≠ m,
若L < 0.5,则S = D / P
若L ≥ 0.5,则S = D / (2 - P)
若R = M,则H = (G - B) / D
若G = M,则H = 2 + (B - R) / D
若B = M,则H = 4 + (R - G) / D
若H ≥ 0,则H = H * 60
若H < 0,则H = H * 60 + 360
(2) HSL→RGB
若S = 0,则R = G = B = L
若S ≠ 0,则
若L < 0.5,则T2 = L * (1 + S)
若L ≥ 0.5,则T2 = L + S – L * S
T1 = 2 * L – T2
[ H = H / 360
T3r = H + 1/3, T3g = H, T3b = H –1/3
若T3 < 0,则T3 = T3 +1
若T3 > 1,则T3 = T3 –1
若6 * T3 < 1,则color = T1 + (T2 – T1) * 6 * T3
否则,若 2 * T3 < 1,则color = T2
否则,若 3 * T3 < 2,则color = T1 + (T2 – T1) * (2/3 –T3) * 6
否则color = T1
]
其中的[ ]段可用下一段代替:
T3r = H + 120, T3g = H, T3b = H –120
若T3 < 0,则T3 += 360
若T3 > 360,则T3 -= 360
若 T3 < 60,则 color = T1 + (T2 – T1) * T3 / 60
否则,若 T3 < 180,则 color = T2
否则,若 T3 < 240,则 color = T1 + (T2 – T1) * (240 – T3) / 60
否则color = T1
3.RGB←→YCbCr
(1) RGB→YCbCr
Y = 0.299R + 0.587G + 0.114B
Cb = -0.1687R – 0.3313G + 0.5B +128
Cr = 0.5R – 0.4187G – 0.0813B + 128
(2) YCbCr→RGB
R = Y + 1.402 * (Cr - 128)
G = Y – 0.3441 * (Cb – 128) – 0.7141 * (Cr - 128)
B = Y + 1.772 * (Cb - 128)