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

求助:Keras调用load_img函数出现AttributeError的原因及解决方法

解决AttributeError: module 'keras.preprocessing.image' has no attribute 'load_img'

错误原因

从Keras 2.9.0版本开始,load_img这类图像预处理函数被从keras.preprocessing.image模块迁移到了keras.utils.image_utils模块,旧的导入路径已不再有效。如果使用的是TensorFlow集成的Keras(即tf.keras),官方也已弃用keras.preprocessing.image下的相关API。

解决办法

情况1:使用纯Keras环境

修改导入路径,从新模块中调用load_img:

# 方式1:直接导入函数
from keras.utils.image_utils import load_img
test_image = load_img('dataset/single_prediction/cat_or_dog_3.jpg', target_size=(64, 64))

# 方式2:导入模块后调用
from keras.utils import image_utils
test_image = image_utils.load_img('dataset/single_prediction/cat_or_dog_3.jpg', target_size=(64, 64))

情况2:使用TensorFlow集成的Keras(推荐)

改用tf.keras官方推荐的API路径:

import tensorflow as tf
test_image = tf.keras.utils.load_img('dataset/single_prediction/cat_or_dog_3.jpg', target_size=(64, 64))

补充:如果后续需要将图片转换为数组,原img_to_array函数也同步迁移,对应keras.utils.image_utils.img_to_array或tf.keras.utils.img_to_array。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 22:25:19