M
M
maryaturova2021-07-10 21:15:01
Python
maryaturova, 2021-07-10 21:15:01

Keras: how to properly send numpy?

Dear! What am I doing wrong?
At the input I get a picture in base64.

If I save to disk using PIL, then everything works

im = Image.open(io.BytesIO(base64.b64decode(data_obj['link'].split(',')[1])))
im.save('img.png')
im.close()

image = tf.keras.preprocessing.image.load_img(
    'img.png', target_size=(obj['size'], obj['size'])
)
input_arr = tf.keras.preprocessing.image.img_to_array(image)
input_arr = np.array([input_arr])
predictions = obj['main'].predict(input_arr)

result = obj['classes'][np.argmax(predictions[0])]

But if send a numpy array:
nparr = np.fromstring(base64.b64decode(data_obj['link'].split(',')[1]), np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_UNCHANGED)

predictions = obj['main'].predict(np.array([img]))
    
result = obj['classes'][np.argmax(predictions[0])]

I am getting an error:
ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 3 but received input with shape [None, 116, 116, 4]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-07-11
@maryaturova

The error says that you have 4 channels in the picture instead of 3.
I think it's cv2.IMREAD_UNCHANGED. Often RGB images have an unused 4th byte per pixel to align pixel addresses in memory. IMREAD_UNCHANGED means that this byte is loaded as is, so 4 channels are obtained.
Try replacing it with IMREAD_COLOR.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question