I have an image (480,640,3) and I am trying to resize it to (150,150,1). Since my Keras model has been trained on images of shape (150,150,1), unfortunately I cannot seem to resize it using the PIL library. Any suggestions on how to fix this?

This is the code I am using right now:

The error is caused on the line image5.resize()

    data = numpy.fromstring(stream.getvalue() , dtype = numpy.uint8)
    image5 = cv.imdecode(data , 1)
    img = image5.resize((150,150,1 ), Image.ANTIALIAS)
    x = img_to_array(img)
    x = x.reshape((1,) + x.shape)
    x = x/255
    x = numpy.array(x)
    #score = loaded_model.predict(img)
  • $\begingroup$ I think you should specify exactly which line is causing the error. $\endgroup$ Apr 9, 2019 at 11:05
  • $\begingroup$ I'm not much of a Python user but what happens if you change (150,150,1) to (150,150)? I think you might need to change the depth separately. $\endgroup$
    – PeterJ
    Apr 9, 2019 at 12:12
  • $\begingroup$ Initially it was 150,150 . Hence i changed it to 150,150,1 since that was the final shape i needed of the image $\endgroup$ Apr 9, 2019 at 12:19
  • $\begingroup$ Is your image in color? maybe you could try changing the depth by using RGB2Gray conversion $\endgroup$ Apr 9, 2019 at 18:31
  • $\begingroup$ Pillow documentation (which is a fork of PIL) states that "A new PIL.Image.LANCZOS constant was added instead of ANTIALIAS.". You could try to check if this is true to PIL as well. $\endgroup$ Apr 9, 2019 at 18:38

1 Answer 1


The solution to the problem is to resize using openCV instead of using PIL and specifying the appropriate pixel width and height.

img = cv.resize(image5 , (150,150))

Your Answer

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

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