pythondata-sciencepgm

How to read PGM P2 image in Python


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.


Solution

  • I know it's a little late to answer but I ran into the same issue and I thought it might be useful to post my solution. There does not seem to exist a library that reads ASCII based PGM (P2) on Python.

    Here is my function, it 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()
    
        # 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