[Image-SIG] Converting a binary file to ascii

abel deuring adeuring at gmx.net
Wed Sep 3 15:52:02 CEST 2008

On 03.09.2008 11:10, Ashish Sethi wrote:
> I have PPM-P6 image file which is in binary format .The file is of the type  :-
> P6
> 128 128
> 255
> ߢ…ä£{ä¡~ߟxÞ¡yàšfß›lÜšyâ›jåŸhæ¦ué­yê§vé¡pÛš»ubž^Y¦f](c)g ..........and so on.
> How can i read the 4th line (binary) and convert it to an equivalent
> ascii string. I used the following method but couldn't get the desired
> result..

Please define more precisely what you mean with "equivalent ascii
string". Strictly speaking, b2a_uu produces an equivalent string in the
sense that running a2b_uu gives you the original string back, but this
is obviously not what you want. In other words, there is 1:1 mapping
between arbitrary binary data and their "UU" representation.

If you want to get the "P3" format: Use something like

intvals = [ord(i) for i in d]

(where d is the string with the binary image data read from the
P6-format file) and create an ASCII representation for the elements of
the list intvals.

> import binascii
> from binascii import b2a_uu
> infile=open("C:\\Documents and Settings\\Desktop\\lena.ppm")
> a=infile.readline()
> b=infile.readline()
> c=infile.readline()
> d=infile.readline()
> z=b2a_uu(d)
> print z
> This script gave me some random absurd data as output.

As Ned already wrote, you should open the file in binary mode on
Windows. And as Karsten wrote, you should use infile.read() to get the
image data. readline() is not useful to read binary data: You will get
the data up to the first byte with the value 10 (ASCII meaning: "line
feed"), or perhaps for Windows up to the first byte with the value 13
(ASCII meaning "carriage return"). But these values have for P6 files a
different "meaning", when they appear after the leading "255" line: They
simply give the value of the red, blue or green component of a pixel.


More information about the Image-SIG mailing list