Skip to content

Ignore padding bytes in getcolors() for two band images - #10510

Merged
radarhere merged 2 commits into
python-pillow:mainfrom
qodelicious:fix-getcolors-two-band
Nov 15, 2026
Merged

radarhere merged 2 commits into
python-pillow:mainfrom
qodelicious:fix-getcolors-two-band

Conversation

@qodelicious

Copy link
Copy Markdown
Contributor

Changes proposed in this pull request:

  • For LA, La and PA images, getcolors() compares the whole 4 byte pixel, including the 2 unused middle bytes. Those bytes are not always the same. Image.merge() and point() leave them as 0, while new(), convert() and frombytes() copy the L value into them.
  • So if an image mixes pixels from these sources, the same colour is counted more than once.
from PIL import Image

im = Image.new("LA", (2, 1), (1, 2))
bands = (Image.new("L", (1, 1), 1), Image.new("L", (1, 1), 2))
im.paste(Image.merge("LA", bands))
print(im.getcolors())  # [(1, (1, 2)), (1, (1, 2))]
  • This masks out the unused bytes for two band images, the same way the unused fourth byte is already masked for three band images.

@radarhere
radarhere enabled auto-merge (squash) November 15, 2026 03:56
@radarhere
radarhere disabled auto-merge November 15, 2026 03:57
@radarhere
radarhere merged commit b8865b5 into python-pillow:main Nov 15, 2026
78 of 84 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants