回答问题

使用 numpy 在 Python 中读取 16 位 PGM 图像的有效且清晰的方法是什么?

由于 PIL 错误](https://stackoverflow.com/questions/7363735/python-and-16-bit-pgm),我无法使用 PIL 加载 16 位 PGM 图像[。我可以使用以下代码阅读标题:

dt = np.dtype([('type', 'a2'),
               ('space_0', 'a1', ),
               ('x', 'a3', ),
               ('space_1', 'a1', ),
               ('y', 'a3', ),
               ('space_2', 'a1', ),
               ('maxval', 'a5')])
header = np.fromfile( 'img.pgm', dtype=dt )
print header

这会打印出正确的数据:('P5', ' ', '640', ' ', '480', ' ', '65535')但我感觉这不是最好的方法。除此之外,我很难弄清楚如何以size(header)的偏移量按 16 位读取 x by y(在本例中为 640x480)的以下数据。

编辑:添加图像

读取和显示图像的 MATLAB 代码是:

I = imread('foo.pgm'); 
imagesc(I);

看起来像这样:

在此处输入图像描述

Answers

import re
import numpy

def read_pgm(filename, byteorder='>'):
    """Return image data from a raw PGM file as numpy array.

    Format specification: http://netpbm.sourceforge.net/doc/pgm.html

    """
    with open(filename, 'rb') as f:
        buffer = f.read()
    try:
        header, width, height, maxval = re.search(
            b"(^P5\s(?:\s*#.*[\r\n])*"
            b"(\d+)\s(?:\s*#.*[\r\n])*"
            b"(\d+)\s(?:\s*#.*[\r\n])*"
            b"(\d+)\s(?:\s*#.*[\r\n]\s)*)", buffer).groups()
    except AttributeError:
        raise ValueError("Not a raw PGM file: '%s'" % filename)
    return numpy.frombuffer(buffer,
                            dtype='u1' if int(maxval) < 256 else byteorder+'u2',
                            count=int(width)*int(height),
                            offset=len(header)
                            ).reshape((int(height), int(width)))


if __name__ == "__main__":
    from matplotlib import pyplot
    image = read_pgm("foo.pgm", byteorder='<')
    pyplot.imshow(image, pyplot.cm.gray)
    pyplot.show()
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐