Skip to main content

colorsys

colorsys 模块提供 RGB 与其他颜色空间(HSV、HLS、YIQ)之间的双向转换。

colorsys

info

所有颜色空间的坐标值均为 01 之间的浮点数(YIQ 的 I、Q 分量除外,可以为负值)。这与常见的 0255 整数表示不同,使用时需要做归一化。

RGB 与 HSV 互转

HSV(色相 Hue、饱和度 Saturation、明度 Value)是图像处理和调色中最常用的颜色空间。

import colorsys

# RGB -> HSV
r, g, b = 0.2, 0.4, 0.4
h, s, v = colorsys.rgb_to_hsv(r, g, b)
print(f"HSV: h={h:.3f}, s={s:.3f}, v={v:.3f}")
# HSV: h=0.500, s=0.500, v=0.400

# HSV -> RGB
r, g, b = colorsys.hsv_to_rgb(0.5, 0.5, 0.4)
print(f"RGB: r={r:.3f}, g={g:.3f}, b={b:.3f}")
# RGB: r=0.200, g=0.400, b=0.400

RGB 与 HLS 互转

HLS(色相 Hue、亮度 Lightness、饱和度 Saturation)与 HSV 类似,但亮度的定义不同。

import colorsys

# RGB -> HLS
h, l, s = colorsys.rgb_to_hls(1.0, 0.0, 0.0)
print(f"纯红色的 HLS: h={h:.3f}, l={l:.3f}, s={s:.3f}")
# 纯红色的 HLS: h=0.000, l=0.500, s=1.000

# HLS -> RGB
r, g, b = colorsys.hls_to_rgb(0.0, 0.5, 1.0)
print(f"RGB: r={r:.3f}, g={g:.3f}, b={b:.3f}")
# RGB: r=1.000, g=0.000, b=0.000

RGB 与 YIQ 互转

YIQ 是 NTSC 电视系统使用的颜色空间,Y 为亮度分量,I 和 Q 为色度分量。

import colorsys

# RGB -> YIQ
y, i, q = colorsys.rgb_to_yiq(1.0, 1.0, 1.0)
print(f"白色的 YIQ: y={y:.3f}, i={i:.3f}, q={q:.3f}")
# 白色的 YIQ: y=1.000, i=0.000, q=0.000

# YIQ -> RGB
r, g, b = colorsys.yiq_to_rgb(1.0, 0.0, 0.0)
print(f"RGB: r={r:.3f}, g={g:.3f}, b={b:.3f}")

实用场景:与 0~255 整数值互转

import colorsys

def rgb_int_to_hsv(r: int, g: int, b: int):
"""将 0~255 的 RGB 值转换为 HSV"""
h, s, v = colorsys.rgb_to_hsv(r / 255, g / 255, b / 255)
return round(h * 360), round(s * 100), round(v * 100)

def hsv_to_rgb_int(h: int, s: int, v: int):
"""将 HSV(H:0~360, S:0~100, V:0~100)转换为 0~255 RGB"""
r, g, b = colorsys.hsv_to_rgb(h / 360, s / 100, v / 100)
return round(r * 255), round(g * 255), round(b * 255)

print(rgb_int_to_hsv(255, 128, 0)) # (30, 100, 100) 橙色
print(hsv_to_rgb_int(30, 100, 100)) # (255, 128, 0)

实用场景:生成和谐配色

利用 HSV 空间中色相的均匀分布,可以快速生成互补色或等距配色方案。

import colorsys

def generate_colors(n: int, saturation=0.7, value=0.9):
"""生成 n 个等距分布的和谐颜色,返回十六进制色值列表"""
colors = []
for i in range(n):
hue = i / n
r, g, b = colorsys.hsv_to_rgb(hue, saturation, value)
hex_color = "#{:02x}{:02x}{:02x}".format(
round(r * 255), round(g * 255), round(b * 255)
)
colors.append(hex_color)
return colors

# 生成 5 个和谐颜色
for color in generate_colors(5):
print(color)
# #e64d4d, #e6c24d, #5ce64d, #4d9ee6, #b44de6
tip

调色时一般在 HSV/HLS 空间操作更直观:固定饱和度和明度/亮度,只调整色相即可生成同一风格的多种颜色。

实用场景:调整颜色亮度

import colorsys

def adjust_lightness(hex_color: str, factor: float) -> str:
"""调整十六进制颜色的亮度,factor > 1 变亮,< 1 变暗"""
r = int(hex_color[1:3], 16) / 255
g = int(hex_color[3:5], 16) / 255
b = int(hex_color[5:7], 16) / 255

h, l, s = colorsys.rgb_to_hls(r, g, b)
l = max(0, min(1, l * factor))
r, g, b = colorsys.hls_to_rgb(h, l, s)

return "#{:02x}{:02x}{:02x}".format(
round(r * 255), round(g * 255), round(b * 255)
)

base = "#3498db"
print(f"原色: {base}")
print(f"变亮: {adjust_lightness(base, 1.3)}")
print(f"变暗: {adjust_lightness(base, 0.7)}")