import numpy as np
import matplotlib.pyplot as plt
def readpgm(name):
with open(name) as f:
lines = f.readlines()
# Ignores commented lines
for l in list(lines):
if l[0] == '#':
lines.remove(l)
# Makes sure it is ASCII format (P2)
assert lines[0].strip() == 'P2'
# Converts data to a list of integers
data = []
for line in lines[1:]:
data.extend([int(c) for c in line.split()])
return (np.array(data[3:]),(data[1],data[0]),data[2])
data = readpgm('/location/of/file.pgm')
plt.imshow(np.reshape(data[0],data[1])) # Usage example
我知道现在回答有点晚了,但我遇到了同样的问题,我想把我的解决方案贴出来可能会有用。似乎不存在在Python上读取基于ASCII的PGM(P2)的库。在
这是我的函数,它接受文件名并返回一个元组:(1)包含数据的1xn numpy数组,(2)包含长度和宽度的元组,(3)灰色阴影的数量。在
相关问题 更多 >
编程相关推荐