如何在 Python 中读取 PGM P2 图像

How to read PGM P2 image in Python

所以首先,我在 AI 的大学小组执行任务。我有一个 PGM P2(ASCII) 格式的多面数据集。在开始神经网络处理之前,我需要从图像中提取像素数组,但我无法在 Python 中找到读取这些图像的方法。

我已经尝试过 PIL,但它不适用于 PGM P2。

我可以在 Python 中执行此操作吗? 任何帮助将不胜感激。

我知道现在回答有点晚了,但我 运行 遇到了同样的问题,我认为它可能对 post 我的解决方案有用。 Python.

上似乎不存在读取基于 ASCII 的 PGM (P2) 的库

这是我的函数,它接收文件名和 returns 一个元组,其中包含:(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('/location/of/file.pgm')

plt.imshow(np.reshape(data[0],data[1])) # Usage example