Numpy和16位PGM

man*_*off 15 python numpy pgm 16-bit

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

由于PIL错误,我无法使用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
Run Code Online (Sandbox Code Playgroud)

这打印出正确的数据:('P5', ' ', '640', ' ', '480', ' ', '65535')但我感觉这不是最好的方式.除此之外,我无法弄清楚如何在x的y(在这种情况下为640x480)中读取以下数据,读取偏移量为16位size(header).

编辑:图像添加

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

I = imread('foo.pgm'); 
imagesc(I);
Run Code Online (Sandbox Code Playgroud)

看起来像这样:

在此输入图像描述

cgo*_*lke 22

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()
Run Code Online (Sandbox Code Playgroud)

  • 我刚刚解决了一些问题,但找不到一个好的解决方案.您可以尝试请求最后一条评论不能有多行,但这对我来说也不起作用.我认为最强大的是在最后一个标题值(maxval)之后禁止评论.然后你可以使用这个正则表达式(借口可怕的格式):`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)",缓冲区).groups()` (2认同)