如何读取 Python 中的 PGM 图像

How to read PGM image in Python

如何在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

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

如果你想将其转换为 P2,你可以使用 ImageMagick,它安装在大多数 Linux 扭曲上,适用于 macOS 和 Windows.

convert YourP5Image.pgm -compress none ActualP2Image.pgm

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