前言
大家好,我是 倔强青铜三 。欢迎关注我,微信公众号: 倔强青铜三。点赞、收藏、关注,一键三连!
欢迎来到 苦练Python第 72 天!
今天我们来学习python标准库中的colorsys库。
10 分钟带你上手 Python 的 colorsys。
模块定位与导入
什么是 colorsys
colorsys 是 Python 标准库中 轻量级 的颜色空间转换工具,提供 RGB ↔ HLS、RGB ↔ HSV、RGB ↔ YIQ 的双向转换,源码不到 200 行,零依赖,跨平台。
导入方式
python
import colorsys
就这么简单,无需安装第三方包。
颜色空间速览
| 空间 | 通道 | 数值范围 | 特点 |
|---|---|---|---|
| RGB | Red, Green, Blue | 0.0--1.0 浮点 | 屏幕物理三原色 |
| HLS | Hue, Lightness, Saturation | Hue: 0--1 环绕,L/S: 0--1 | Photoshop 常用 |
| HSV/HSB | Hue, Saturation, Value/Brightness | Hue: 0--1 环绕,S/V: 0--1 | Web 配色常见 |
| YIQ | Luma, In-phase, Quadrature | Y: 0--1,I/Q: −1~1 | NTSC 电视信号 |
核心函数速查表
| 功能 | 调用 |
|---|---|
| RGB → HLS | colorsys.rgb_to_hls(r, g, b) |
| HLS → RGB | colorsys.hls_to_rgb(h, l, s) |
| RGB → HSV | colorsys.rgb_to_hsv(r, g, b) |
| HSV → RGB | colorsys.hsv_to_rgb(h, s, v) |
| RGB → YIQ | colorsys.rgb_to_yiq(r, g, b) |
| YIQ → RGB | colorsys.yiq_to_rgb(y, i, q) |
数值范围与精度
0.0--1.0 浮点区间
colorsys 只认 浮点 ,且所有通道必须在 0.0 到 1.0(YIQ 的 I/Q 为 −1~1)。
与 0--255 整数的转换方法
python
def norm(x):
"""0-255 → 0-1"""
return x / 255.0
def denorm(x):
"""0-1 → 0-255 整数"""
return round(x * 255)
运行结果(无输出,仅定义函数)。
快速上手实验
将 RGB 转 HSV 并打印
python
import colorsys
r, g, b = 0.2, 0.6, 0.9 # 天蓝色
h, s, v = colorsys.rgb_to_hsv(r, g, b)
print(f"RGB({r}, {g}, {b}) → HSV({h:.3f}, {s:.3f}, {v:.3f})")
运行结果
scss
RGB(0.2, 0.6, 0.9) → HSV(0.583, 0.778, 0.900)
调整亮度再转回 RGB
python
import colorsys
h, s, v = 0.583, 0.778, 0.900
v_darker = max(v - 0.3, 0.0) # 降低亮度
r2, g2, b2 = colorsys.hsv_to_rgb(h, s, v_darker)
print(f"调暗后 RGB({r2:.3f}, {g2:.3f}, {b2:.3f})")
运行结果
scss
调暗后 RGB(0.140, 0.420, 0.600)
批量生成彩虹色
python
import colorsys
def norm(x):
"""0-255 → 0-1"""
return x / 255.0
def denorm(x):
"""0-1 → 0-255 整数"""
return round(x * 255)
print("彩虹 7 色(RGB 0-255):")
for i in range(7):
hue = i / 7.0
r, g, b = colorsys.hsv_to_rgb(hue, 1.0, 1.0)
print(f"#{i} H={hue:.3f} → RGB({denorm(r)}, {denorm(g)}, {denorm(b)})")
运行结果
scss
彩虹 7 色(RGB 0-255):
#0 H=0.000 → RGB(255, 0, 0)
#1 H=0.143 → RGB(255, 127, 0)
#2 H=0.286 → RGB(255, 255, 0)
#3 H=0.429 → RGB(0, 255, 0)
#4 H=0.571 → RGB(0, 255, 255)
#5 H=0.714 → RGB(0, 0, 255)
#6 H=0.857 → RGB(127, 0, 255)
典型应用场景
颜色渐变动画
python
import colorsys
def norm(x):
"""0-255 → 0-1"""
return x / 255.0
def denorm(x):
"""0-1 → 0-255 整数"""
return round(x * 255)
def gradient_demo(steps=20):
for i in range(steps + 1):
hue = i / steps
r, g, b = colorsys.hsv_to_rgb(hue, 1, 1)
# 终端 ANSI 24-bit 真彩
esc = f"\033[38;2;{denorm(r)};{denorm(g)};{denorm(b)}m"
print(esc + "█" * 3, end="")
print("\033[0m") # 复位
gradient_demo()
运行结果 (终端可见彩色渐变条)
███ 从红到紫的连续渐变。
主题色提取与转换
python
import colorsys
def norm(x):
"""0-255 → 0-1"""
return x / 255.0
def denorm(x):
"""0-1 → 0-255 整数"""
return round(x * 255)
# 假设从图片拿到主题 RGB(120, 80, 200)
r, g, b = norm(120), norm(80), norm(200)
h, l, s = colorsys.rgb_to_hls(r, g, b)
# 生成互补色
h_comp = (h + 0.5) % 1.0
r2, g2, b2 = colorsys.hls_to_rgb(h_comp, l, s)
print(f"互补色 RGB({denorm(r2)}, {denorm(g2)}, {denorm(b2)})")
运行结果
scss
互补色 RGB(200, 240, 80)
命令行彩色输出
python
def norm(x):
"""0-255 → 0-1"""
return x / 255.0
def denorm(x):
"""0-1 → 0-255 整数"""
return round(x * 255)
def color_print(text, rgb):
r, g, b = rgb
print(f"\033[38;2;{denorm(r)};{denorm(g)};{denorm(b)}m{text}\033[0m")
color_print("Hello colorsys!", (1.0, 0.5, 0.0)) # 橙色
运行结果
橙色字体的 Hello colorsys!
常见错误与调试技巧
范围溢出
python
# 错误示例
import colorsys
colorsys.rgb_to_hsv(1.2, 0, 0)
运行结果
sql
ValueError: float RGB values must be between 0 and 1
浮点精度误差
python
import colorsys
# 往返转换后可能差 1e-15
r = 0.123456789
h, s, v = colorsys.rgb_to_hsv(r, 0.5, 0.7)
r2, _, _ = colorsys.hsv_to_rgb(h, s, v)
print(abs(r - r2)) # 误差
运行结果
1.3877787807814457e-17
误用整数导致异常
python
import colorsys
colorsys.rgb_to_hsv(255, 255, 255) # 忘记归一化
运行结果
sql
ValueError: float RGB values must be between 0 and 1
至此,你已掌握 colorsys 的全部核心用法。
最后感谢阅读!欢迎关注我,微信公众号: 倔强青铜三 。
点赞、收藏、关注 ,一键三连!!欢迎 点击 【👍喜欢作者】 按钮进行 打赏💰💰,请我喝一杯咖啡☕️!