python create .pgm file
<p>Well first I have to mention that I read the material on this page including :
<a href="http://stackoverflow.com/questions/12374937/create-binary-pbm-pgm-ppm">Create binary PBM/PGM/PPM</a></p>

<p>I also read the page explaining the .pgm file format<a href="http://netpbm.sourceforge.net/doc/pgm.html" rel="nofollow">.pgm file format</a>. I know that there is a difference between .pgm "raw" format and .pgm "plain" format. I also know that these files are being created as 8-bit (allowing integer values between 0-255) or 16-bit (allowing integer values between 0-65535) binary files.</p>

<p>Non of these information could yet help me to write a clean piece of code that creates a plain .pgm file in either 8-bit of 16-bit formats.</p>

<p>Here I attach my python script. This code results in a file with distorted (integer) values! </p>

<pre><code>import numpy as np

# define the width  (columns) and height (rows) of your image
width = 20
height = 40

p_num = width * height
arr = np.random.randint(0,255,p_num)

# open file for writing 
filename = 'test.pgm'
fout=open(filename, 'wb')

# define PGM Header
pgmHeader = 'P5' + ' ' + str(width) + ' ' + str(height) + ' ' + str(255) +  '\n'

pgmHeader_byte = bytearray(pgmHeader,'utf-8')

# write the header to the file
fout.write(pgmHeader_byte)

# write the data to the file 
img = np.reshape(arr,(height,width))

for j in range(height):
    bnd = list(img[j,:])
    bnd_str = np.char.mod('%d',bnd)
    bnd_str = np.append(bnd_str,'\n')
    bnd_str = [' '.join(bnd_str)][0]    
    bnd_byte = bytearray(bnd_str,'utf-8')        
    fout.write(bnd_byte)

fout.close()
</code></pre>

<p>As the result of this code a .pgm file is being created where data are completely changed (as if squeezed into the (10-50) range)
I would appreciate any comment / corrections on this code. </p>

<p>First your code has missing open <code>'</code> for <code>\n'</code> in statement <code>pgmHeader = 'P5' + ...</code>. Second no <code>fout = open(filename, 'wb')</code>.  The main problem is that you use <code>ASCII</code> format to encode the pixel data, you should use <code>binary</code> format to encode them (because you used magic number 'P5'):</p>

<pre><code>for j in range(height):
    bnd = list(img[j,:])
    fout.write(bytearray(bnd)) # for 8-bit data only
</code></pre>

python image format pgm