Re: PIL and format conversions -- Noobie.

Discussion in 'Python' started by Fredrik Lundh, Dec 14, 2004.

  1. 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>
    Fredrik Lundh, Dec 14, 2004
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Shaun
    Replies:
    2
    Views:
    555
    Simon Brunning
    Apr 22, 2005
  2. Replies:
    10
    Views:
    704
    Jasen Betts
    Aug 5, 2005
  3. Replies:
    2
    Views:
    273
    Victor Bazarov
    Oct 26, 2007
  4. Sverre
    Replies:
    2
    Views:
    3,544
    Sverre
    Dec 17, 2009
  5. Alpha Blue

    Time Format Conversions

    Alpha Blue, Aug 31, 2009, in forum: Ruby
    Replies:
    4
    Views:
    86
    Alpha Blue
    Sep 1, 2009
Loading...

Share This Page