首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python创建.pgm文件

python创建.pgm文件
EN

Stack Overflow用户
提问于 2016-10-17 16:56:13
回答 1查看 5.4K关注 0票数 2

好吧,首先我必须提到,我阅读了这个页面上的材料,包括:Create binary PBM/PGM/PPM

我还阅读了解释.pgm文件格式.pgm file format的页面。我知道.pgm“原始”格式和.pgm“普通”格式是有区别的。我还知道这些文件被创建为8位(允许0-65535之间的整数值)或16位(允许0-255之间的整数值)二进制文件。

这些信息都不能帮助我编写一段干净的代码,创建一个8位或16位格式的普通.pgm文件。

在这里我附加了我的python脚本。此代码会导致文件的值失真(整型)!

代码语言:javascript
复制
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)范围内一样),如果您对此代码有任何意见或更正,我将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2016-10-17 18:02:34

首先,您的代码在语句pgmHeader = 'P5' + ...中缺少\n'的打开'。第二,没有fout = open(filename, 'wb')。主要的问题是你使用ASCII格式来编码像素数据,你应该使用binary格式来编码它们(因为你使用了神奇的数字'P5'):

代码语言:javascript
复制
for j in range(height):
    bnd = list(img[j,:])
    fout.write(bytearray(bnd)) # for 8-bit data only
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40082165

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档