There is no library that reads ASCII based PGM (P2) on Python.
So,here is the function in the below code that takes in the name of the file and returns a tuple with:
(1) A 1xn numpy array with the data
(2) A tuple containing the length and width
(3) The number of shades of gray.
import numpy as np
import matplotlib.pyplot as plt
def readpgm(name):
with open(name) as f:
lines = f.readlines()
# This ignores commented lines
for l in list(lines):
if l[0] == '#':
lines.remove(l)
# here,it 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
If you wish to learn more about how to use python for data science, then go through this data science python course by Intellipaat for more insights.