【发布时间】:2014-11-01 00:10:00
【问题描述】:
我正在运行一个 python 演示,旨在打开图像并可视化图像上的对象分割。该脚本有一个名为loadImage() 的例程,用于加载图像:
def loadImage(self, im_id):
"""
Load images with image objects.
:param im: a image object in input json file
:return:
"""
im = self.images[im_id]
return mpimg.imread(open('%s/%s/%s'%(self.image_folder, im['file_path'], im['file_name']), 'r'))
注意mpimg 代表matplotlib(因为import matplotlib.image as mpimg 位于脚本开头)。
但是,一旦脚本执行此函数,我将返回以下错误:
File "script.py", line 148, in callerFunction
im = self.loadImage(im_id)
File "script.py", line 176, in loadImage
return mpimg.imread(open('%s/%s/%s'%(self.image_folder, im['file_path'], im['file_name']), 'r'))
File "/usr/lib/pymodules/python2.7/matplotlib/image.py", line 1192, in imread
return handler(fname)
RuntimeError: _image_module::readpng: file not recognized as a PNG file
我已经完成了一些research 操作,但由于某种原因,当使用打开的文件句柄时,imread 似乎无法正确检测文件类型。因此,由于我要加载的图像是 jpg,readpng 模块存在运行时错误。
谁能帮我解答一下:
- 这种行为是由什么引起的?
- 修复方法是什么?
感谢您的帮助。
@Paul 回答后的一些澄清和进一步调查。
正如matplotlib.image documentation 所说,函数imread() 可以接受作为输入
字符串路径或 Python 文件类对象。如果提供了格式,将尝试读取该类型的文件,否则从文件名中推断出格式。如果什么都不能推导出来,则尝试 PNG。
所以我想我的问题应该扩展到为什么在这种特定情况下使用文件句柄作为输入会导致运行时错误?
【问题讨论】:
标签: python matplotlib png runtime-error jpeg