Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: PIL and format conversions -- Noobie.

Thread Tools

Re: PIL and format conversions -- Noobie.

Fredrik Lundh
Posts: n/a
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 ="lenna.ppm")
>>> im.mode

>>> 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))


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

>>> len(im.getcolors())


and roundtrip via JPEG:

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



> 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 ="myimage.jpg")
im = im.convert(
"P", dither=Image.NONE, palette=Image.ADAPTIVE, colors=20

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


Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
PIL: problem to convert an image array to PIL format Sverre Python 2 12-17-2009 04:33 PM
XML different format conversions C++ 2 10-26-2007 03:28 PM
Linux and RAW file format conversions m II Digital Photography 14 02-10-2007 02:38 PM
Pointer conversions and Data types conversions C Programming 10 08-05-2005 09:51 AM
[PIL] is there a downloadable docs for PIL Egor Bolonev Python 2 12-24-2004 11:05 AM