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

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

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

相关推荐
MicroTech20253 小时前
MLGO微算法科技发布多用户协同推理批处理优化系统,重构AI推理服务效率与能耗新标准
人工智能·科技·算法
说私域3 小时前
互联网企业外化能力与实体零售融合:基于定制开发开源AI智能名片S2B2C商城小程序的实践探索
人工智能·开源·零售
沫儿笙3 小时前
FANUC发那科焊接机器人薄板焊接节气
人工智能·机器人
IT_陈寒3 小时前
震惊!我用JavaScript实现了Excel的这5个核心功能,同事直呼内行!
前端·人工智能·后端
淞宇智能科技3 小时前
固态电池五大核心设备全解析
大数据·人工智能·自动化
AndrewHZ4 小时前
【图像处理基石】多波段图像融合算法入门:从概念到实践
图像处理·人工智能·算法·图像融合·遥感图像·多波段·变换域
胖哥真不错4 小时前
Python基于PyTorch实现多输入多输出进行BP神经网络回归预测项目实战
pytorch·python·毕业设计·论文·毕设·多输入多输出·bp神经网络回归预测
Web3_Daisy4 小时前
从透明到可控:链上换仓与资产路径管理的下一阶段
人工智能·安全·web3·区块链·比特币
Zyx20074 小时前
低代码革命:用 Coze AI 一键打造智能应用,人人都能当开发者!
人工智能