Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

So first, I'm in a mission on AI's college group. I have a dataset with many faces in PGM P2(ASCII) format. Before starting Neural Network proccess, I need to extract the array of pixels from images, but I can't found a way to read these images in Python.

I've already tried PIL but it doesn't work with PGM P2.

Can I do this in Python? Any help would be much appreciated.

1 Answer

0 votes
by (41.4k points)

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.

Browse Categories

...