You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python基于主色调限制图像颜色数:原代码失效求修复或替代方案

修复图像颜色数量限制的PIL代码及替代方案

原代码的问题修复

你提供的代码存在导入拼写错误——PIL的图像模块应为大写的Image,而非小写的image,这是导致代码失效的核心原因。修复后的代码如下:

from PIL import Image

image = Image.open("input.png")
result = image.convert('P', palette=Image.ADAPTIVE, colors=2)
result.save("saved.png")

替代方案(适配新版Pillow)

如果修复导入后仍无法正常运行,可能是Pillow版本更新导致convert方法的行为变化,推荐使用更稳定的quantize方法实现颜色量化:

from PIL import Image

image = Image.open("input.png")
# 量化为指定颜色数,采用自适应调色板
result = image.quantize(colors=2, method=Image.Quantize.ADAPTIVE)
result.save("saved.png")

额外排查建议

  • 确保Pillow版本为最新:执行pip install --upgrade pillow更新依赖
  • 检查输入图像路径是否正确,以及保存目录是否有写入权限

内容的提问来源于stack exchange,提问作者fchpro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 19:20:35