苦练Python第72天:colorsys 模块 10 分钟入门,让你的代码瞬间“好色”!

前言

大家好,我是 倔强青铜三 。欢迎关注我,微信公众号: 倔强青铜三。点赞、收藏、关注,一键三连!

欢迎来到 苦练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 的全部核心用法。

最后感谢阅读!欢迎关注我,微信公众号: 倔强青铜三
点赞、收藏、关注 ,一键三连!!

欢迎 点击 【👍喜欢作者】 按钮进行 打赏💰💰,请我喝一杯咖啡☕️!

相关推荐
小陈工16 小时前
Python Web开发入门(十七):Vue.js与Python后端集成——让前后端真正“握手言和“
开发语言·前端·javascript·数据库·vue.js·人工智能·python
A__tao21 小时前
Elasticsearch Mapping 一键生成 Java 实体类(支持嵌套 + 自动过滤注释)
java·python·elasticsearch
墨染天姬21 小时前
【AI】端侧AIBOX可以部署哪些智能体
人工智能
研究点啥好呢21 小时前
Github热门项目推荐 | 创建你的像素风格!
c++·python·node.js·github·开源软件
AI成长日志21 小时前
【Agentic RL】1.1 什么是Agentic RL:从传统RL到智能体学习
人工智能·学习·算法
2501_9481142421 小时前
2026年大模型API聚合平台技术评测:企业级接入层的治理演进与星链4SAPI架构观察
大数据·人工智能·gpt·架构·claude
小小工匠21 小时前
LLM - awesome-design-md 从 DESIGN.md 到“可对话的设计系统”:用纯文本驱动 AI 生成一致 UI 的新范式
人工智能·ui
迷藏49421 小时前
**发散创新:基于Rust实现的开源合规权限管理框架设计与实践**在现代软件架构中,**权限控制(RBAC)** 已成为保障
java·开发语言·python·rust·开源
哈里谢顿21 小时前
如何实现分布式锁
面试
黎阳之光21 小时前
黎阳之光:视频孪生领跑者,铸就中国数字科技全球竞争力
大数据·人工智能·算法·安全·数字孪生