Matplotlib未检测到正确的文件类型运行时错误

1 投票
1 回答
1711 浏览
提问于 2025-04-30 18:24

我正在运行一个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'))

需要注意的是,mpimgmatplotlib 的缩写(因为在脚本开头有一行 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

我做了一些 研究,发现似乎是因为在使用打开的文件句柄时,imread 没有正确识别文件类型。因此,由于我尝试加载的图片是 jpg 格式,readpng 模块出现了运行时错误。

有没有人能帮我弄清楚:

  1. 这种行为是由于什么原因造成的?
  2. 该如何解决?

谢谢你的帮助。


在 @Paul 的回答和进一步调查后的一些澄清。

根据 matplotlib.image 文档,函数 imread() 可以接受以下输入:

一个字符串路径或一个类似文件的Python对象。如果提供了格式,它会尝试读取该类型的文件,否则会根据文件名推断格式。如果无法推断,则会尝试PNG格式。

所以我想我的问题应该扩展到,为什么在这个特定情况下使用文件句柄作为输入会导致这个运行时错误?

暂无标签

1 个回答

1

只需要把文件名给它就行:

import os
import matplotlib.image as mpimg

class imageThingy(object):
    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]
        imgpath = os.path.join(self.image_folder, im['file_path'], im['file_name'])
        return mpimg.imread(imgpath)

    def plotImage(self, im_id):
        fig, ax = plt.subplots()
        ax.imshow(img, origin='lower')
        return fig

根据文件类型,你可能需要用 origin="lower" 来绘制你的图像。这是因为图像解析器会把所有文件类型都当作一个numpy数组来读取。numpy数组的第一个元素总是位于右上角。但是,有些文件类型的原点是在左下角。因此,它们在数组中是翻转过来的。这个信息在你发的链接里有说明。

撰写回答