PIL中的图像转换,pgm文件错误

时间:2012-10-06 10:35:52

标签: python image-processing python-imaging-library

尝试在PIL python库中执行以下操作时:

Image.open('Apple.gif').save('Apple.pgm')

代码失败了:

  Traceback (most recent call last):
  File "/home/eran/.eclipse/org.eclipse.platform_3.7.0_155965261/plugins/org.python.pydev_2.6.0.2012062818/pysrc/pydevd_comm.py", line 765, in doIt
    result = pydevd_vars.evaluateExpression(self.thread_id, self.frame_id, self.expression, self.doExec)
  File "/home/eran/.eclipse/org.eclipse.platform_3.7.0_155965261/plugins/org.python.pydev_2.6.0.2012062818/pysrc/pydevd_vars.py", line 376, in evaluateExpression
    result = eval(compiled, updated_globals, frame.f_locals)
  File "<string>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1439, in save
    save_handler(self, fp, filename)
  File "/usr/lib/python2.7/dist-packages/PIL/PpmImagePlugin.py", line 114, in _save
    raise IOError, "cannot write mode %s as PPM" % im.mode
IOError: cannot write mode P as PPM

代码可以正常转换为BMP,但JPG也失败了。 奇怪的是,一个不同的文件(JPG到PGM),工作正常。

其他格式转换。那就是:

Image.open('Apple.gif').save('Apple.bmp')

作品。

知道为什么吗?

1 个答案:

答案 0 :(得分:11)

您需要将图片转换为RGB模式才能使其正常工作。

im = Image.open('Apple.gif')
im = im.convert('RGB')
im.save('Apple.pgm')