3

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!

4
  • What is the type and shape of img? Please tell me the version of PIL. import PIL then PIL.__version__. And try to replace from keras.preprocessing import image by from tensorflow.keras.preprocessing import image
    – Kaveh
    Jul 3, 2021 at 16:33
  • Image shape is (686, 1140, 3). PIL version is 8.3.0. I did try to replace the import as suggested but the issue persisted. Thank you! Jul 3, 2021 at 17:17
  • Downgrade pillow from 8.3.0 to 8.2 sometimes works. Try it. Downgrade PIL to 8.2.0.
    – Kaveh
    Jul 3, 2021 at 17:28
  • Wow that worked! Can't thank you enough Jul 3, 2021 at 17:45

1 Answer 1

8

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
1
  • 1
    I've tried to downgrade,but without effect. The platform tf2.5,py3.7
    – Qiqin Zhan
    Aug 15, 2021 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.