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

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

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

相关推荐
予枫的编程笔记几秒前
【Java进阶】深入浅出 Java 锁机制:从“单身公寓”到“交通管制”的并发艺术
java·人工智能·
科技云报道2 分钟前
科技云科技云报到:RPA+Agent,为什么可以1+1>2?
人工智能·科技
SEO_juper2 分钟前
应对 AI 概览导致的网站流量流失:诊断、优化与长期策略
人工智能·seo·数字营销
longxibo4 分钟前
mysql数据快速导入doris
android·大数据·python·mysql
Mintopia7 分钟前
🌌 信任是否会成为未来的货币?
前端·人工智能·aigc
青春不败 177-3266-05209 分钟前
AI支持下的临床医学日常工作、论文撰写、数据分析与可视化、机器学习建模中的实践应用
人工智能·数据挖掘·数据分析·医学
闲看云起13 分钟前
大模型注意力机制进化史:从全局到稀疏,从标准到线性、滑动窗口、MQA……
人工智能·语言模型·nlp
数说星榆18113 分钟前
可信AI:透明度、公平性与问责制
人工智能
实战项目15 分钟前
基于深度学习的音乐分类算法研究
人工智能·深度学习·分类
才兄说15 分钟前
机器人租赁中的现场确认痛点
人工智能·机器人