首先我必须提到我阅读了此页面上的 Material ,包括: Create binary PBM/PGM/PPM
我还阅读了解释 .pgm 文件格式的页面 .pgm file format 。我知道 .pgm“原始”格式和 .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) 范围内一样) 我将不胜感激对此代码的任何评论/更正。
最佳答案
首先,您的代码在语句 pgmHeader = 'P5' + ...
中缺少 \n'
的 open '
。第二个没有fout = open(filename, 'wb')
。主要问题是您使用 ASCII
格式对像素数据进行编码,您应该使用 binary
格式对其进行编码(因为您使用了魔数(Magic Number)“P5”):
for j in range(height):
bnd = list(img[j,:])
fout.write(bytearray(bnd)) # for 8-bit data only
关于python 创建 .pgm 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40082165/