PIL and format conversions -- Noobie.

Fredrik Lundh fredrik at pythonware.com
Tue Dec 14 08:32:15 EST 2004


Ron Phillips wrote:

>I have a monster jpg (128 mb) that comprises a handful of colors (20 or
> so, max). It should never have been compressed with jpeg compression, as
> I understand it. It should have been a png or gif, since they are made
> to handle blocks of a few colors.

if you compress an image that originally had 20 or so colors, max, as JPEG, and
then decompress it, you get a lot more colors in the resulting image.  an example:

>>> import Image

let's load an arbitrary color image:

>>> im = Image.open("lenna.ppm")
>>> im.mode
'RGB'
>>> len(im.getcolors())
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: len() of unsized object

by default, getcolors() returns None if the image contains
more than 256 colors.  let's try raising that limit:

>>> len(im.getcolors(1000000))
119023

okay, we have some 120000 unique colors in this RGB image.
let's cut the number of colors down to 20:

>>> im = im.quantize(20)
>>> im.mode
'P'
>>> len(im.getcolors())
20

and roundtrip via JPEG:

>>> im.convert("RGB").save("out.jpg")
>>> im = Image.open("out.jpg")
>>> len(im.getcolors(1000000))
32593

oops.

> I used PIL to convert it to png and to gif, and it got even bigger (6 -
> 8 x) -- am I using PIL wrong, or is PIL the wrong tool? If so, how
> should I use PIL so it best compresses the outfile? Or, what tool should
> I use?

this might work:

    im = Image.open("myimage.jpg")
    im = im.convert(
        "P", dither=Image.NONE, palette=Image.ADAPTIVE, colors=20
    )
    im.save("myimage.png")

(trying various colors settings might be a good idea; if you leave it out, you'll
get no more than 256 colors).

</F> 






More information about the Python-list mailing list