私はそれが少し遅れていることは知っていますが、私は同じ問題に遭遇し、私は私のソリューションを投稿することが有用かもしれないと思った。 Python上でASCIIベースのPGM(P2)を読み込むライブラリは存在しないようです。
これは私の関数です。ファイルの名前を取り、次のようなタプルを返します。(1)データを持つ1xnのnumpy配列、(2)長さと幅を含むタプル、(3)灰色の陰影の
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('./faces/an2i/an2i_right_sad_sunglasses.pgm')
plt.imshow(np.reshape(data[0],data[1])) # Usage example
の
可能性のある重複した[無地PGM形式のPILの画像フィルタを作成する方法?](https://stackoverflow.com/questions/4270700/how-to-write-pil-image-filter-for-plain -pgm-format) – Reti43