gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:07:10 25 4
gpt4 key购买 nike

我正在运行一个 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 模块出现运行时错误。

谁能帮我弄清楚:

  1. 此行为的原因是什么?
  2. 解决方法是什么?

感谢您的帮助。

<小时/>

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

作为matplotlib.image documentation说,函数 imread() 可以接受作为输入

a string path or a Python file-like object. If format is provided, will try to read file of that type, otherwise the format is deduced from the filename. If nothing can be deduced, PNG is tried.

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

最佳答案

只需输入文件名即可:

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 的第一个元素始终位于右上角。然而,某些文件类型的起源位于左下角。因此,它们作为数组进行翻转。此信息位于您发布的链接中。

关于python - Matplotlib 未检测到正确的文件类型运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26665283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com