Tensorflow Image Shape Error

2k views Asked by At

I have trained a classifier and I now want to pass any single image through.

I'm using the keras library with Tensorflow as the backend.

I'm getting an error I can't seem to get past

img_path = '/path/to/my/image.jpg'

import numpy as np
from keras.preprocessing import image
x = image.load_img(img_path, target_size=(250, 250))

x = image.img_to_array(x)
x = np.expand_dims(x, axis=0)

preds = model.predict(x) 

Do I need to reshape my data to have None as the first dimension? I'm confused why Tensorflow would expect None as the first dimension?

Error when checking : expected convolution2d_input_1 to have shape (None, 250, 250, 3) but got array with shape (1, 3, 250, 250)

I'm wondering if there has been an issue with the architecture of my trained model?

edit: if i call model.summary() give convolution2d_input_1 as...

enter image description here

Edit: I did play around with the suggestion below but used numpy to transpose instead of tf - still seem to be hitting the same issue!

enter image description here

2

There are 2 answers

2
sygi On BEST ANSWER

None matches any number. Usually, when you pass some data to a model, it is expected that you pass tensor of dimensions: None x data_size, meaning the first dimension is any dimension and denotes batch size. In your case, the problem is that you pass 250 x 250 x 3, and it is expected 3 x 250 x 250. Try:

x = image.load_img(img_path, target_size=(250, 250))
x_trans = tf.transpose(x, perm=[2, 0, 1])
x_expanded = np.expand_dims(x_trans, axis=0)
preds = model.predict(x_expanded) 
0
YesIndeedy On

enter image description here

Ok so using feedback rom Sygi i think i have half solved it,

The error was actually telling me i needed to pass in my dimensions as [1, 250, 250, 3] so that was an easy fix; i must say im not sure why TF is expecting the dimensions in this order as looking at the docs it doesnt seem right so more research required here.

Moving ahead im not sure transpose is the way to go as if i use a different input image the dimensions may not be in the same order meaning the transpose doesnt work properly,

Instead of transpose I'm probably trying to t call x_reshape = img.reshape((1, 250, 250, 3)) depending on what i find out about dimension order in reshaping for TS

thanks for the hints Sygi :)