Skip to content

Correct transparency when converting with matrix - #10468

Merged
radarhere merged 2 commits into
python-pillow:mainfrom
yxshee:fix/matrix-transparency-rounding
Nov 9, 2026
Merged

radarhere merged 2 commits into
python-pillow:mainfrom
yxshee:fix/matrix-transparency-rounding

Conversation

@yxshee

@yxshee yxshee commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Changes proposed in this pull request:

  • When convert() is given a matrix, the transparency color in info is now calculated the same way as the pixels, m[0] * r + m[1] * g + m[2] * b + m[3] + 0.5. The Python helper had m[3] * 0.5, so the offset was halved and the rounding term was lost, and the transparent color no longer matched the pixel it was meant to mark.
from PIL import Image

im = Image.new("RGB", (1, 1), (255, 0, 0))
im.info["transparency"] = (255, 0, 0)
out = im.convert("L", (1, 0, 0, -10))
print(out.getpixel((0, 0)), out.info["transparency"])  # 245 250, expected 245 245

With (0.5, 0.5, 0, 0) the pixel is 128 and the transparency was 127.

  • Added test_matrix_transparency, which checks that the transparency equals the converted pixel. On main it fails with assert 127 == 128 and assert (123, 61, 100) == (123, 62, 101).
  • test_matrix_xyz expected (105, 54, 4), but the C conversion turns (255, 0, 0) into (105, 54, 5) with that matrix, so the expected value is updated to match.

The full test suite passes locally, apart from test_grab, which also fails on main here because of macOS screen capture permissions. pre-commit and tox -e mypy pass.

@radarhere radarhere added the 🤖-assisted AI-assisted label Nov 9, 2026
@radarhere

Copy link
Copy Markdown
Member

You're pointing out that

float v = m[0] * in[0] + m[1] * in[1] + m[2] * in[2] + m[3] + 0.5;

and
value = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5

disagree.

The C code has been there since PIL. The Python code was added in #3205 by me. I am inclined to believe that I made a mistake.

@radarhere radarhere changed the title Add matrix offset when converting transparency Correct transparency when converting with matrix Nov 9, 2026
@radarhere
radarhere enabled auto-merge (squash) November 9, 2026 09:05
@radarhere
radarhere force-pushed the fix/matrix-transparency-rounding branch from 5298b68 to eb58ce8 Compare November 9, 2026 09:07
@radarhere
radarhere merged commit 4d01b94 into python-pillow:main Nov 9, 2026
54 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants