我有16位的PGM图像,我正在尝试用Python读取这些图像。看起来(?)像PIL不支持这种格式吗?
import Image
im = Image.open('test.pgm')
im.show()粗略地显示了图像,但它并不正确。到处都是暗带,据报道img有mode=L。我想这与我之前关于16-bit TIFF files的一个问题有关。16位是不是很罕见,以至于PIL不支持它?有什么建议可以让我用PIL或其他标准库,或自己编写的代码,在Python中读取16位PGM文件吗?
发布于 2011-09-09 23:44:30
您需要一个"L;16"模式;但是,在加载PGM时,PIL看起来有一个硬编码到File.c中的"L"模式。如果你想阅读一个16位的PGM,你必须使用write your own decoder。
然而,16位图像支持似乎仍然不稳定:
>>> im = Image.fromstring('I;16', (16, 16), '\xCA\xFE' * 256, 'raw', 'I;16')
>>> im.getcolors()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/dist-packages/PIL/Image.py", line 866, in getcolors
return self.im.getcolors(maxcolors)
ValueError: image has wrong mode我认为PIL能够读取16位的图像,但实际上存储和操作它们仍处于实验阶段。
>>> im = Image.fromstring('L', (16, 16), '\xCA\xFE' * 256, 'raw', 'L;16')
>>> im
<Image.Image image mode=L size=16x16 at 0x27B4440>
>>> im.getcolors()
[(256, 254)]看,它只是将0xCAFE值解释为0xFE,这并不完全正确。
发布于 2013-02-03 09:33:35
这是一个基于NumPy的通用PNM/PAM阅读器,以及一个用PyPNG编写的未公开的函数。
def read_pnm( filename, endian='>' ):
fd = open(filename,'rb')
format, width, height, samples, maxval = png.read_pnm_header( fd )
pixels = numpy.fromfile( fd, dtype='u1' if maxval < 256 else endian+'u2' )
return pixels.reshape(height,width,samples)当然,编写这种图像格式通常不需要库的帮助……
https://stackoverflow.com/questions/7363735
复制相似问题