quantize() reduces to far fewer colors than requested in some cases

未关闭
#5,204 3 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
42/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
停滞
技术栈
python

调研方向

Start by reproducing the reported result with test-in.png and the Python quantize() call described in the issue. Trace the quantization entry point and its handling of RGB values with varying alpha, then add a regression test for the 508-color image. Done means quantizing this case no longer unexpectedly produces only 25 colors and the existing test suite still passes.

由索引模型根据 Issue 内容生成。

描述

PNG
What did you do?

This image, named test-in.png, has 508 distinct colors according to getcolors().
test-in.png
I tried to quantize it to 256 colors with the following code.

from PIL import Image
MAXCOLORCOUNT = 1024
with Image.open("test-in.png") as im:
    colsbefore = im.getcolors(maxcolors=MAXCOLORCOUNT)
    colsbefore = len(colsbefore) if colsbefore is not None else f"{MAXCOLORCOUNT}<"
    im = im.quantize(colors=256)
    colsafter = len(im.getcolors(maxcolors=MAXCOLORCOUNT))
    print(f"colors {colsbefore} -> {colsafter}")
    im.save("test-out.png") 
What did you expect to happen?

Reduced to 256 colors, i.e. print colors 508 -> 256

What actually happened?

Reduced to only 25 colors, i.e. prints colors 508 -> 25

What are your OS, Python and Pillow versions?
  • OS: Ubuntu 20.04 (Kubuntu)
  • Python: 3.9.1 (via pyenv)
  • Pillow: 8.1.0
Other remarks

I'm guessing it's something about the image having only a few distinct RGB values but with a wide range of alpha values. A test image with over 256 distinct RGB values had no such issue.

Why don't I use pngquant or imagemagick instead? I depend on Pillow because I need a quantization method that preserves the colors of fully transparent pixels. (I'm modding a game whose texture filtering causes the colors of fully-transparent pixels to be faintly but noticeably visible around the edges of the fully-transparent regions.)

Edit: Using im.convert("P") on an image that already has 256 or fewer colors (according to len(im.getcolors())) can cause it to lose more colors unnecessarily during the conversion.

主要语言
Python
星标
14k
派生
2.6k
平均合并
1 天 1 小时
30 天内合并 PR
205

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

python-pillow/Pillow 的其他 Issue

查看 python-pillow/Pillow 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。