pythonimagedata-sciencepgm

How to read PGM image in Python


How to read this PGM image in python? please help

PGM image link

I tried this

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('514516.pgm')

plt.imshow(np.reshape(data[0],data[1])) # Usage example

it gives me this error:

"return codecs.charmap_decode(input,self.errors,decoding_table)[0]

 UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 
 2075: character maps to <undefined>"

what should i do? please help

Solution:

Numpy and 16-bit PGM


Solution

  • Your image isn't P2 (ASCII greyscale), it is P5 (Binary Greyscale).

    If you want to convert it to P2, you can use ImageMagick which is installed on most Linux distort and is available for macOS and Windows.

    convert YourP5Image.pgm -compress none ActualP2Image.pgm
    

    Or, find the Python way of reading binary NetPBM images. It is 16-bit, by the way.