[Image-SIG] Writting ppm files??

Fredrik Lundh fredrik at pythonware.com
Tue Aug 19 13:28:07 CEST 2008

Fredrik Lundh wrote:

 > looks like you could save yourself a lot of time and effort by first
 > checking if you can install:
 > http://www.pythonware.com/products/pil/

sorry, thought you'd posted this to c.l.python, and didn't see the 
"import" statement at first.

>> I am working with PPM/PGM/PBM file formats
>> which have the basic format :-

 > where line1= type of file(p1=PBM,p2=PGM,p3=PPM), line2=comment,
 > line3=dimension of the image (x and y length),line4=maximum value of
 > color( here 15 means 4 bit R,G,B data)

not really -- the 15 means that the images contain data in the range 
0-15.  that fits in 4 bits, but since it's a text format, it isn't 
stored in 4 bits.  far from it.

why are you using PPM text files?  does the application your using 
really require that, or is this just something you thought would make 
things easier?

if you're only interested in making sure that all RGB values in an image 
fits inside the 0-15 range, you can simply do:

    im = Image.open(infile)
    im = im.point(lambda x: x/16)

if you insist on writing this out as a text file, replace the "save" 
with a simple loop that uses the im.load() accessor.  something like 
this should work:

    pix = im.load()

    out = open(outfile, "w")
    print >>out, "P2"
    print >>out, "%d %d" % im.size
    print >>out, "15"
    for y in range(im.size[1]):
        for x in range(im.size[0]):
            r, g, b = pix[x, y]
            print >>out, r, g, b,
        print >>out

tweak as necessary.


More information about the Image-SIG mailing list