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
with open(name) as f:
lines = f.readlines()
# This ignores commented lines
for l in list(lines):
if l == '#':
# here,it makes sure it is ASCII format (P2)
assert lines.strip() == 'P2'
# Converts data to a list of integers
data = 
for line in lines[1:]:
data.extend([int(c) for c in line.split()])
data = readpgm('/location/of/file.pgm')
plt.imshow(np.reshape(data,data)) # 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.