TypeError: __array__() takes 1 positional argument but 2 were given (Image classification Keras)

Issue

How to troubleshoot this? I’ve tried setting dtype=None in the image.img_to_array method.

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]

This raises the following error:

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

Has anyone seen this before? Many thanks!

Solution

This error sometimes is due to a bug in Pillow 8.3.0 as it is here. (You may not use import PIL directly in your code, however some libraries such as tf.keras.preprocessing.image.load_img use PIL internally)

So, downgrading from PIL 8.3.0 to 8.2.0 may work.

Check PIL version:

import PIL
print(PIL.__version__)

If it is 8.3.0, then you may downgrade to 8.2.0:

!pip install pillow==8.2.0

Answered By – Kaveh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published