在 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);
看起来像这样:
最佳答案
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/