首先,我在AI的大学小组中承担任务。我有一个包含许多PGM P2(ASCII)格式人脸图像的数据集。在开始神经网络处理之前,我需要从图像中提取像素数组,但我找不到一种在Python中读取这些图像的方法。
我已经尝试过PIL,但它不能处理PGM P2格式。
我能在Python中做到这点吗? 非常感谢任何帮助。
首先,我在AI的大学小组中承担任务。我有一个包含许多PGM P2(ASCII)格式人脸图像的数据集。在开始神经网络处理之前,我需要从图像中提取像素数组,但我找不到一种在Python中读取这些图像的方法。
我已经尝试过PIL,但它不能处理PGM P2格式。
我能在Python中做到这点吗? 非常感谢任何帮助。
这是我的函数,它接受文件名并返回一个元组,其中包含:(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