Skip to content

Extra output from getpalette() and getcolors() in quantized image #6046

@clarkemw

Description

@clarkemw

What did you do?

I am using Image.quantize to reduce an image down to a simple 12 color palette and count the prevalence of each color in quantized image.

What did you expect to happen?

getpalette() should return a 36 integer list reflecting the R,G,B values of the 12 color palette
getcolors() should return a list of 12 tuples with the second index in the tuples ranging from 1-12 referencing the colors in the palette.

What actually happened?

When I call getpalette() the first 36 items reflect my palette but the remaining items up to index 768 are a sequence of 12, 12, 12, 13, 13, 13 etc. I'm guessing the code does this to avoid resizing the array and internally detects these additional items and discards them...so maybe not a big deal.

The real issue is when I call getcolors(). Instead of receiving a list of 12 tuples (with second index in the tuples referencing a palette colors in the range 1-12) I receive a list of 208 tuples which reference palette colors as high as 252. I can't seem to make sense of the output. Am I supposed to just ignore anything that references an out of range palette index?

What are your OS, Python and Pillow versions?

  • OS:
  • Python: 3.9.10
  • Pillow: 9.01
RGB_flat = (2, 62, 255, 255, 124, 0, 26, 201, 56, 232, 0, 11, 139, 43, 226, 159, 72, 0, 241, 76, 193, 163, 163, 163, 255, 196, 0, 0, 215, 255, 0, 0, 0, 255, 255, 255)
img = Image.open('cherry.jpg')
pimg = Image.new('P',(16,16))
pimg.putpalette(RGB_flat)
imgq = img.quantize(palette=pimg)
colors = imgq.getcolors()
palette = imgq.getpalette()

cherry

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions