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

Keras中使用preprocess_input作为ImageDataGenerator预处理函数报错

解决‘JpegImageFile’ object is not subscriptable错误

这个问题我之前也碰到过,本质是Keras 2.1.5版本中ImageDataGenerator的preprocessing_function参数接收的输入类型,和resnet系列的preprocess_input函数期望的输入类型不匹配导致的:

  • 在Keras 2.1.5里,ImageDataGenerator会直接把PIL格式的图像对象(比如JpegImageFile)传给预处理函数;
  • 而keras.applications.resnet里的preprocess_input,是专门用来处理numpy数组格式图像数据的,它内部会尝试对输入做数组下标操作,自然就会抛出“‘JpegImageFile’ object is not subscriptable”的错误。

两种可行的解决方案:

1. 自定义包装函数,手动转换图像格式

自己写一个中间函数,先把PIL图像转成numpy数组,再调用官方的preprocess_input:

from keras.applications.resnet import preprocess_input
import numpy as np

def custom_preprocess(img):
    # 将PIL图像转换为numpy数组
    img_np = np.array(img)
    # 调用官方预处理函数处理数组
    return preprocess_input(img_np)

然后把这个自定义函数传入ImageDataGenerator:

datagen = ImageDataGenerator(preprocessing_function=custom_preprocess)

2. 升级Keras版本(如果项目允许)

后续版本的Keras(比如2.2及以上)已经修复了这个问题,ImageDataGenerator会自动将PIL图像转换为numpy数组后,再传给预处理函数。升级后你就可以直接使用原来的写法:

datagen = ImageDataGenerator(preprocessing_function=preprocess_input)

不过升级前要注意检查项目中其他代码的兼容性,避免引入新问题。

内容的提问来源于stack exchange,提问作者Michał Gacka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:59:46