TypeError: 'Image' object is not subscriptable using PIL

TypeError: 'Image' object is not subscriptable using PIL

我正在尝试在 google colab 上开发网络应用程序。我想在此 Web 应用程序中使用我之前训练过的模型制作图像分类器。当我 select 在 Web 应用程序中从浏览器分类图像时,出现以下错误:

TypeError: 'Image' object is not subscriptable.

我的代码块:

file = st.file_uploader("Please upload an image(png) file", type=["png"])
def import_and_predict(_image_data, model):
    size = (299,299)
    _image = ImageOps.fit(_image_data , size , Image.ANTIALIAS)
    img = np.asarray(_image)
    img_reshape = _image[np.newaxis,...]
    prediction = model.predict(img_reshape)
    # image = image.convert('RGB')
    # st.image(image, channels='RGB')
    return prediction
if file is None:
    st.text("Please upload an image file !")
else:
    _image = Image.open(file)
    st.image(_image , use_column_width=True)
    prediction = import_and_predict(_image, model)
    class_names=['Cat','Dog']
    string="predict:" +class_names[np.argmax(predictions)]
    st.success(string)

您试图对原始 Image 对象执行重塑操作,而您本应对图像数组执行此操作。更改此行:

img_reshape = _image[np.newaxis,...]

至:

img_reshape = img[np.newaxis,...]

你应该很好。