好吧,首先我必须提到,我阅读了这个页面上的材料,包括:Create binary PBM/PGM/PPM
我还阅读了解释.pgm文件格式.pgm file format的页面。我知道.pgm“原始”格式和.pgm“普通”格式是有区别的。我还知道这些文件被创建为8位(允许0-65535之间的整数值)或16位(允许0-255之间的整数值)二进制文件。
这些信息都不能帮助我编写一段干净的代码,创建一个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)范围内一样),如果您对此代码有任何意见或更正,我将不胜感激。
发布于 2016-10-17 18:02:34
首先,您的代码在语句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 onlyhttps://stackoverflow.com/questions/40082165
复制相似问题