如何在Python中读取PGM图像

2024-10-01 09:20:34 发布

您现在位置: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

它给了我一个错误:

^{pr2}$

我该怎么办?请帮忙

解决方案:

Numpy and 16-bit PGM


Tags: namein图像importfordataasnp
1条回答
网友
1楼 · 发布于 2024-10-01 09:20:34

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

如果您想将其转换为P2,可以使用ImageMagick,它安装在大多数linuxtruster上,可用于macOS和Windows。在

convert YourP5Image.pgm -compress none ActualP2Image.pgm

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

相关问题 更多 >