python 创建 .pgm 文件

标签 python image format pgm

首先我必须提到我阅读了此页面上的 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/

相关文章:

python - 使用 scikit 学习的离散分类器的 ROC 曲线

python - 如何在给定步骤中使用 django-behave 登录用户

python - 识别 Pandas 数据框列是否包含列表中的元素

javascript - 移至顶部功能在 kineticJs 中不起作用

python - 解析具有 2 个 ip 地址的 apache 日志

html - Swift:如何显示来自 html 源的图像

javascript - 尝试创建交替图像横幅,但它无法正常工作

string - 如何在 autohotkey 中将字符串转换为数字?

python - printf 样式格式字符串的解析器

java - 转换 EEE MMM dd HH :mm:ss ZZZ yyyy to YYYY-MM-dd JAVA