python - Numpy 和 16 位 PGM

标签 python numpy 16-bit pgm

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

我无法使用 PIL 加载 16 位 PGM 图像 due to a PIL bug .我可以使用以下代码读取 header :

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 和 y(在本例中为 640x480)的以下数据。

编辑:添加图像

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

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

看起来像这样:

enter image description here

最佳答案

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()

关于python - Numpy 和 16 位 PGM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7368739/

相关文章:

python - CTR 中的 AES 如何与 PyCrypto 一起用于 Python?

python - 如何跟踪 Redis 中某个用户完成的 Celery 请求数?

python - 为什么 ThreadPoolExecutor 比 for 循环慢?

c++ - 将两个字节转换为 16 位值的最有效方法?

c++ - 如何将 C/C++ 编译为 CP/M-86 可执行文件 (CMD)

python - Lookahead 更新字典列表

python - 如何从两个的交集制作矩形?

Python:查找 3D 数组(图像堆栈)中邻域的最高值

python - 如何在 numba.njit 中进行离散傅立叶变换 (FFT)?

c++ - 为什么没有 2 字节 float 并且已经存在实现?