4

I have an image I loaded with the image.load_img() function but when I try to reshape it I get this error:

ValueError: cannot reshape array of size 12288 into shape (64,64)

Here is my code:

test_image = image.load_img('xray_dataset_covid19/test/PNEUMONIA/streptococcus-pneumoniae-pneumonia-temporal-evolution-1-day2.jpg'
                            , target_size = (64, 64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = model.predict(test_image)
if result[0][0] == 1:
    img = Image.fromarray(test_image.reshape(64,64) ,'L')
    img.show() 
Ethan
  • 1,657
  • 9
  • 25
  • 39
Houmes
  • 41
  • 1
  • 1
  • 2

2 Answers2

3

$64\times 64 = 4096$. You're short about $8000$ pixels.

Dave
  • 4,542
  • 1
  • 10
  • 35
0

when I print(test_image.shape) I get (1, 64, 64, 3)

What you probably wanted was:

if result[0][0] == 1:
    img = Image.fromarray(test_image.reshape(64,64,3))
    img.show()

I.e. specify the ,3, because you have RGB data, and drop the ,'L' because that means you have B/W data.

If you actually wanted greyscale or b/w change the last line to one of:

img.convert('L').show()
img.convert('1').show()

Stepping back a bit, you could have used test_image directly, and not needed to reshape it, except it was in a batch of size 1. A better way to deal with it, and not have to explicitly state the image dimensions, is:

if result[0][0] == 1:
    img = Image.fromarray(test_image.squeeze(0))
    img.show()

squeeze() removes any dimensions of size 1; squeeze(0) avoids surprises by being more specific: if the first dimension is of size 1 remove it, otherwise do nothing.

Yet another way to do it, that ties in with how you use result, is:

if result[0][0] == 1:
    img = Image.fromarray(test_image[0])
    img.show()
Darren Cook
  • 1,324
  • 8
  • 16