[Image-SIG] Converting PPM-P3 file type to PPM-P6 file type

Ashish Sethi ashishbitsgoa at gmail.com
Fri Aug 29 07:56:51 CEST 2008


Hey freinds,
I have a problem...PIL doesnt understand PPM-P3 (ascii) file type.
It only accepts PPM-P6 (binary) as an image file.Since I am dealing
with both these file types and wish to use python for my processing
tasks..I descided to create a script to convert P3 to P6 type...here
is my code :

import Image
import string

im=open("C:\\Documents and Settings\\ashishs trainee\\Desktop\\lena3.ppm")
x=im.readline()

x=x.rstrip("\r\n")
print x
if x=="P3":
    y=im.readline()
    z=im.readline()
    y=y.rstrip("\r\n")
    a=string.split(y,' ')
    m,n=a
    ftype='P6'
    ppmfile=open('C:\\Documents and Settings\\ashishs
trainee\\Desktop\\lena5.ppm','wb')
    ppmfile.write("%s\n" % (ftype))
    ppmfile.write("%d %d\n" % (int(m),int(n)))
    ppmfile.write("255\n")

    q=im.readline()

    while (q!=''):
        q=q.rstrip("\r\n")
        a=string.split(q,' ')
        red,green,blue=a
        red=int(red)
        green=int(green)
        blue=int(blue)
        ppmfile.write("%c%c%c" % (red,green,blue))
        q=im.readline()
    ppmfile.close()

i=Image.open("C:\\Documents and Settings\\ashishs trainee\\Desktop\\lena5.ppm")
i.show()

The file created using this script is an truncated image which when
viewed using xv shows the correct image but with python gives the
following error :
Traceback (most recent call last):
  File "C:/ash/imaging/p3_2_p6.py", line 38, in <module>
    i.show()
  File "C:\Python25\Lib\site-packages\PIL\Image.py", line 1449, in show
    _showxv(self, title, command)
  File "C:\Python25\Lib\site-packages\PIL\Image.py", line 2082, in _showxv
    file = image._dump(format=format)
  File "C:\Python25\Lib\site-packages\PIL\Image.py", line 476, in _dump
    self.load()
  File "C:\Python25\Lib\site-packages\PIL\ImageFile.py", line 192, in load
    raise IOError("image file is truncated (%d bytes not processed)" % len(b))
IOError: image file is truncated (381 bytes not processed)

The first few lines of my input file are :
P3
128 128
255
214 167 126
218 169 114
218 167 118
213 165 111
213 167 112
213 161 91
213 161 98
210 160 113
215 162 96
and so on

Can you please tell me where am i going wrong??


More information about the Image-SIG mailing list