实现灰度值与彩色值之间的相互转化python代码
时间: 2024-05-15 22:16:05 浏览: 73
将RGB转为灰度值:
```python
def rgb_to_gray(r, g, b):
return 0.2989 * r + 0.5870 * g + 0.1140 * b
```
将灰度值转为RGB:
```python
def gray_to_rgb(gray):
return (gray, gray, gray)
```
将RGB转为HSV:
```python
def rgb_to_hsv(r, g, b):
r /= 255.0
g /= 255.0
b /= 255.0
cmax = max(r, g, b)
cmin = min(r, g, b)
delta = cmax - cmin
if delta == 0:
hue = 0
elif cmax == r:
hue = ((g - b) / delta) % 6
elif cmax == g:
hue = (b - r) / delta + 2
else:
hue = (r - g) / delta + 4
hue = round(hue * 60)
if hue < 0:
hue += 360
saturation = 0 if cmax == 0 else delta / cmax
value = cmax
return (hue, saturation, value)
```
将HSV转为RGB:
```python
def hsv_to_rgb(h, s, v):
c = v * s
x = c * (1 - abs((h / 60) % 2 - 1))
m = v - c
if h < 60:
r, g, b = c, x, 0
elif h < 120:
r, g, b = x, c, 0
elif h < 180:
r, g, b = 0, c, x
elif h < 240:
r, g, b = 0, x, c
elif h < 300:
r, g, b = x, 0, c
else:
r, g, b = c, 0, x
r, g, b = (r + m) * 255, (g + m) * 255, (b + m) * 255
return (round(r), round(g), round(b))
```
阅读全文