如何在Python中阅读PGM图像

时间:2018-01-18 14:27:14

标签: python image data-science pgm

如何在python中阅读此PGM图像?请帮忙

PGM image link

我试过这个

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

它给了我这个错误:

"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>"

我该怎么办?请帮忙

解决方案:

Numpy and 16-bit PGM

1 个答案:

答案 0 :(得分:2)

您的图片不是P2(ASCII灰度),而是P5(二进制灰度)。

如果您想将其转换为P2,您可以使用大多数Linux扭曲中安装的 ImageMagick ,并且可用于macOS和Windows。

convert YourP5Image.pgm -compress none ActualP2Image.pgm

或者,找到Python阅读二进制NetPBM图像的方法。顺便说一句,这是16位。