三种彩色模型(RGB、CMY/CMYK、HSI)及其互相转换的全部代码
时间: 2023-12-11 11:05:35 浏览: 485
RGB转换为CMY/CMYK:
```python
def rgb_to_cmy(rgb):
cmy = [1 - val / 255 for val in rgb]
return cmy
def rgb_to_cmyk(rgb):
cmy = rgb_to_cmy(rgb)
k = min(cmy)
if k == 1:
return [0, 0, 0, 1]
cmyk = [(c - k) / (1 - k) for c in cmy]
cmyk.append(k)
return cmyk
```
CMY/CMYK转换为RGB:
```python
def cmy_to_rgb(cmy):
rgb = [int((1 - val) * 255) for val in cmy]
return rgb
def cmyk_to_rgb(cmyk):
cmy = [(c * (1 - k) + k) for c in cmyk[:3]]
rgb = cmy_to_rgb(cmy)
return rgb
```
RGB转换为HSI:
```python
def rgb_to_hsi(rgb):
r, g, b = rgb
i = (r + g + b) / 3.0
num = ((r - g) + (r - b)) / 2.0
den = ((r - g) ** 2 + (r - b) * (g - b)) ** 0.5
if den == 0:
den = 0.01
theta = math.acos(num / den)
h = theta if b <= g else 2 * math.pi - theta
s = 1 - 3 * min(rgb) / sum(rgb) if sum(rgb) != 0 else 0
return [h, s, i]
```
HSI转换为RGB:
```python
def hsi_to_rgb(hsi):
h, s, i = hsi
r, g, b = 0, 0, 0
if h < 2 * math.pi / 3:
b = i * (1 - s)
r = i * (1 + s * math.cos(h) / math.cos(math.pi / 3 - h))
g = 3 * i - (r + b)
elif h < 4 * math.pi / 3:
h -= 2 * math.pi / 3
r = i * (1 - s)
g = i * (1 + s * math.cos(h) / math.cos(math.pi / 3 - h))
b = 3 * i - (r + g)
else:
h -= 4 * math.pi / 3
g = i * (1 - s)
b = i * (1 + s * math.cos(h) / math.cos(math.pi / 3 - h))
r = 3 * i - (g + b)
return [int(r), int(g), int(b)]
```
阅读全文