[Image-SIG] PIL Programming Questions
Fredrik Lundh
fredrik at pythonware.com
Tue Aug 22 12:40:38 CEST 2006
Paul Prescod wrote:
> 1. I wanted to take 24 bit data, count the colours and make an 8-bit BMP
> if there are fewer than 256 colours. My brute force solution required me
> to build the palette by hand from the data and rewrite the data one
> pixel at a time. (a simple '.convert("P")' seems to use an arbitrary
> palette or something???)
colors = im.getcolors()
if colors is None:
print "image has more than 256 colors"
else:
print "image has", len(colors)
im.getcolors() returns a list of all colours in an image, and by default, it stops
counting if it finds more than 256 colors:
http://www.effbot.org/imagingbook/image.htm#Image.getcolors
> 2. I wanted to pad a bitmap by adding some space to the right and
> bottom. I did this by creating a new one and pasting the old one into
> it.
that's the usual way to do this.
> 3. I wanted to convert every occurrence of one colour to another. I
> walked each pixel.
you can use the (undocumented) quantize method for this:
>>> import Image
>>> im = Image.open("/images/photo.im")
>>> im.getcolors()
>>> len(im.getcolors(im.size[0]*im.size[1]))
119023
>>> im = im.quantize(256)
>>> len(im.getcolors())
256
> I also could not figure out how to get to a 4-bit BMP. I inferred from
> the documentation that this just isn't possible with out of box PIL.
afaik, no. patches are welcome.
> Overall: PIL really rocks.
thanks!
cheers /F
More information about the Image-SIG
mailing list