Sinooshka
Sinooshka

Reputation: 511

python create .pgm file

Well first I have to mention that I read the material on this page including : Create binary PBM/PGM/PPM

I also read the page explaining the .pgm file format.pgm file format. 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.

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.

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

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()

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.

Upvotes: 2

Views: 7595

Answers (1)

acw1668
acw1668

Reputation: 46811

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

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

Upvotes: 2

Related Questions