类型错误:__array__() 需要 1 个位置参数,但给出了 2 个图像分类 Keras

问题描述

如何解决这个问题?我试过在 image.img_to_array 方法中设置 dtype=None 。任何帮助将不胜感激!

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt
from keras.preprocessing import image

image_size = (180,180)
batch_size = 32


model = keras.models.load_model('best_model.h5')

img = keras.preprocessing.image.load_img(
    "GarnetCreek_7-15-2019.jpeg",target_size=image_size
)

img_array = image.img_to_array(img)
img_array = tf.expand_dims(img_array,0)  # Create batch axis

predictions = model.predict(img_array)
score = predictions[0]

这会引发以下错误

Traceback (most recent call last):
img_array = image.img_to_array(img,dtype=None)
return image.img_to_array(img,data_format=data_format,**kwargs)
x = np.asarray(img,dtype=dtype)
    return array(a,dtype,copy=False,order=order)
TypeError: __array__() takes 1 positional argument but 2 were given

有人见过这个吗?非常感谢!

解决方法

此错误有时是由 Pillow 8.3.0 中的错误造成的,因为它是 here。 (您可能不会在代码中直接使用 import PIL,但某些库(例如 tf.keras.preprocessing.image.load_img)在内部使用 PIL

因此,从 PIL 8.3.0 降级到 8.2.0 可能会奏效。

检查 PIL 版本:

import PIL
print(PIL.__version__)

如果是8.3.0,那么你可以降级到8.2.0:

!pip install pillow==8.2.0