2016-10-17 67 views
0

那麼首先我不得不提,我讀材料這個頁面上,包括: Create binary PBM/PGM/PPM蟒蛇創建.PGM文件

我也看了解釋.PGM文件格式.pgm file format的頁面。我知道.pgm「raw」格式和.pgm「普通」格式之間存在差異。我也知道這些文件被創建爲8位(允許0-255之間的整數值)或16位(允許0-65535之間的整數值)二進制文件。

這些信息中的任何一個都不能幫助我編寫一段清晰的代碼,以8位16位格式創建普通的.pgm文件。

這裏附上我的python腳本。這段代碼會導致一個扭曲(整數)值的文件!

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

作爲該代碼正在創建.PGM文件,其中數據被完全改變(如如果擠進(10-50)範圍)的結果 我想知道關於該代碼的任何評論/校正。

回答

0

首先您的代碼在pgmHeader = 'P5' + ...聲明中缺少開放'\n'。第二個沒有fout = open(filename, 'wb')。主要的問題是,你使用ASCII格式編碼的像素數據,你應該使用binary格式編碼它們(因爲你使用的幻數「P5」):

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

謝謝你的評論。我確實犯了你在上面寫的代碼中提到的兩個錯誤。但是,這個修正版本也並沒有給出更好的結果!請考慮下面的代碼: – Sinooshka

+0

將'P5'更改爲'P2'或在我的最新評論中遵循我的建議。 – acw1668