Convert .pgm file to csv file in python,

1.3k views Asked by At

I need to find out how to convert .pgm file to .csv file in python. I have been learning python for 2 1/2 weeks so if anyone helps could you please keep my lack of knowledge in mind. I am using Pycharm on Windows 10.

Here is my code that I'm stuck with. I'm trying to open a pgm file and save it to an empty array print it out to check it has correct values then save it as a csv file with the intention of using it on a neural network. Here it the contents of the file.

 P2
 # Created by GIMP version 2.10.6 PNM plug-in
 20 20
 2552552552552552552550255........255 or 0 black and white hand drawn


import numpy


with open('pgmDataSet/40157883_11_2.pgm', 'r') as input_pgm:
    list_test = [input_pgm]
    list_test = numpy.empty([20, 20], dtype=int, order='C')
    for row in list_test:
        for col in row:
            #What am i missing???????????
            print(row)
numpy.savetxt('csvDataSet/40157883_11_2.csv', list_test, delimiter=',', 
fmt='%s')

with open('csvDataSet/40157883_11_2.csv') as converted:
    list_converted = [converted]
    for line1 in list_converted:
        print(line1.read())

        # np.savetxt('csvDataSet/40157883_11_2.csv', input_pgm, 
delimiter=',', fmt='%s')
    # break;

    # list_test[list_test >= 128] = 1
    # list_test[list_test < 128] = 0
2

There are 2 answers

4
Mark Setchell On BEST ANSWER

Don't reinvent the wheel, use Pillow to load the image, then convert it to a numpy array:

import numpy as np
from PIL import Image

im = np.array(Image.open('pgmDataSet/40157883_11_2.pgm'))

Now print im.shape and off you go...

2
J-L On

Your PGM file doesn't look correct to me. You show it as:

P2
# Created by GIMP version 2.10.6 PNM plug-in
20 20
2552552552552552552550255........255 or 0 black and white hand drawn

but that isn't a valid PGM/P2 file. In addition to specifying a width and height (which I assume are 20,20 here), you also need to give a maximum gray value (which appears to be 255).

Not only that, but according to http://netpbm.sourceforge.net/doc/pgm.html , each pixel value must have whitespace before and after it. The whitespace is not optional.

Therefore, your PGM file should look something like:

P2
# Created by ...
20 20 255
255 255 255 255 255 255 255 0 255 ........ 255

Until you fix this issue (of the badly-formatted PGM file), I doubt there'll be many libraries that will open and read your .pgm file.

So fix your .pgm issue, and see if that doesn't help you with the rest of your problem.