You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决AttributeError: 'JpegImageFile' object has no attribute 'load_img'报错

代码报错修复方案
  • 变量引用错误:你将img.load_img()加载的图像结果存储到了image变量中,但调用plt.imshow()时错误传入了img(此处img是你导入的图像处理模块,不是加载后的图像对象),需要改为传入image。
  • 方法未调用:plt.show是matplotlib的渲染方法,必须加括号plt.show()才会实际执行图像显示操作。
  • 路径拼接不规范:使用//拼接路径属于不规范写法,不同操作系统的路径分隔符存在差异,建议使用os.path.join()方法做路径拼接,适配性更强,也能避免你路径中存在空格导致的读取错误。
  • 缺少文件类型校验:直接遍历os.listdir()的结果可能会读取到子目录、系统隐藏文件等非图像内容,触发加载报错,建议增加文件类型判断。

修正后的完整代码示例:

# 提前导入所需依赖,未安装对应库需先执行安装
import os
import matplotlib.pyplot as plt
# 此处根据你实际使用的图像处理库调整导入,以下是TensorFlow/Keras的load_img导入示例
from tensorflow.keras.preprocessing import image as img

dir_path = "/content/drive/MyDrive/darth_vader_Bing_images/test 1"

for file_name in os.listdir(dir_path):
    # 跳过非文件项
    file_full_path = os.path.join(dir_path, file_name)
    if not os.path.isfile(file_full_path):
        continue
    # 加载并展示图像
    image = img.load_img(file_full_path)
    plt.imshow(image)
    plt.show()

内容的提问来源于stack exchange,提问作者Stewie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 07:27:03