Python和16位PGM

2024-10-05 14:24:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有16位PGM图像,我正试图在Python中阅读。似乎是(?)就像PIL不支持这种格式一样?

import Image
im = Image.open('test.pgm')
im.show()

大致显示了图像,但不正确。全身有暗带,据报道img有mode=L。我想这和我早期关于16-bit TIFF files的问题有关。16位是不是很罕见,皮尔就是不支持它?有什么建议可以告诉我如何用Python读取16位PGM文件,使用PIL或其他标准库,或者自己开发的代码?


Tags: test图像imageimportimgpil格式show
3条回答

以下操作仅依赖于numpy来加载图像,该图像可以是8位或16位原始PGM/PPM。我还展示了两种不同的方式来查看图像。使用PIL(import Image)的方法要求首先将数据转换为8位。

#!/usr/bin/python2 -u

from __future__ import print_function
import sys, numpy

def read_pnm_from_stream( fd ):
   pnm = type('pnm',(object,),{}) ## create an empty container
   pnm.header = fd.readline()
   pnm.magic = pnm.header.split()[0]
   pnm.maxsample = 1 if ( pnm.magic == 'P4' ) else 0
   while ( len(pnm.header.split()) < 3+(1,0)[pnm.maxsample] ): s = fd.readline() ; pnm.header += s if ( len(s) and s[0] != '#' ) else ''
   pnm.width, pnm.height = [int(item) for item in pnm.header.split()[1:3]]
   pnm.samples = 3 if ( pnm.magic == 'P6' ) else 1
   if ( pnm.maxsample == 0 ): pnm.maxsample = int(pnm.header.split()[3])
   pnm.pixels = numpy.fromfile( fd, count=pnm.width*pnm.height*pnm.samples, dtype='u1' if pnm.maxsample < 256 else '>u2' )
   pnm.pixels = pnm.pixels.reshape(pnm.height,pnm.width) if pnm.samples==1 else pnm.pixels.reshape(pnm.height,pnm.width,pnm.samples)
   return pnm

if __name__ == '__main__':

## read image
 # src = read_pnm_from_stream( open(filename) )
   src = read_pnm_from_stream( sys.stdin )
 # print("src.header="+src.header.strip(), file=sys.stderr )
 # print("src.pixels="+repr(src.pixels), file=sys.stderr )

## write image
   dst=src
   dst.pixels = numpy.array([ dst.maxsample-i for i in src.pixels ],dtype=dst.pixels.dtype) ## example image processing
 # print("dst shape: "+str(dst.pixels.shape), file=sys.stderr )
   sys.stdout.write(("P5" if dst.samples==1 else "P6")+"\n"+str(dst.width)+" "+str(dst.height)+"\n"+str(dst.maxsample)+"\n");
   dst.pixels.tofile( sys.stdout ) ## seems to work, I'm not sure how it decides about endianness

## view using Image
   import Image
   viewable = dst.pixels if dst.pixels.dtype == numpy.dtype('u1') else numpy.array([ x>>8 for x in dst.pixels],dtype='u1')
   Image.fromarray(viewable).show()

## view using scipy
   import scipy.misc
   scipy.misc.toimage(dst.pixels).show()

使用说明

  • 我最终弄明白了“它是如何决定endianness的”——它实际上是将图像作为big endian(而不是原生的)存储在内存中。这个方案可能会减慢任何非平凡的图像处理速度——尽管Python的其他性能问题可能会使这个问题变得微不足道(见下文)。

  • 我问了一个关于持久性的问题。我还遇到了一些与endianness相关的有趣的混淆,因为我是通过使用pnmdepth 65535对图像进行预处理来测试endianness的,这对测试endianness是不好的(就其本身而言),因为低字节和高字节可能最终相同(我没有立即注意到,因为print(array)输出十进制)。我也应该用pnmgamma来拯救我自己。

  • 因为Python太慢了,numpy试图巧妙地应用某些操作(参见broadcasting)。使用numpy提高效率的第一个经验法则是让numpy为您处理迭代(或者换一种方式don't write your own ^{} loops)。上面代码中有趣的一点是,它在执行“示例图像处理”时只部分遵循此规则,因此该行的性能对给定给reshape的参数具有极端依赖性。

  • 下一个大的numpy终结之谜:为什么newbyteorder()看起来像return an array,而documented返回一个dtype。如果要用dst.pixels=dst.pixels.byteswap(True).newbyteorder()转换为本机endian,则这是相关的。

  • 关于移植到Python 3的提示:binary input with an ASCII text header, read from stdin

这是一个基于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)

当然,编写这种图像格式通常不需要库的帮助。。。

您需要一个"L;16"模式;但是在加载PGM时,PIL的模式似乎是"L"硬编码到File.c中。如果你想读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,这并不完全正确。

相关问题 更多 >