pythontensorflowbase64image-resizing

Expected shape=(None, 256, 256, 3), found shape=(None, 256, 256, 4)


I'm decoding a base64 image with the following code:

def string_to_image(base64_string):
    decoded = base64.b64decode(base64_string)
    np_data = np.frombuffer(decoded, np.uint8)
    img = cv2.imdecode(np_data, cv2.IMREAD_UNCHANGED)
    return img

The goal is to receive an image from the request body, decode it, resize it with tensorflow, predict it with a model, and return a response saying what is that image:

image_base64 = request.json['image']
decoded_image = string_to_image(image_base64)
image_resized = tf.image.resize(decoded_image, (256, 256))
model = load_model('src/models/mymodel.h5')
result = model.predict(np.expand_dims(image_resized/255, 0))

However, I'm getting the error ValueError: Input 0 of layer "sequential_2" is incompatible with the layer: expected shape=(None, 256, 256, 3), found shape=(None, 256, 256, 4).

I don't know how to change the Shape value from '4' to '3'.

I tried the following:

image_resized = tf.image.resize(decoded_image, (256, 256, 3))

But I get 'size' must be a 1-D Tensor of 2 elements: new_height, new_width.

I also tried:

image_resized = cv2.resize(decoded_image, (256,256,3))

But I get OpenCV(4.6.0) :-1: error: (-5:Bad argument) in function 'resize'

Overload resolution failed:

- Can't parse 'dsize'. Expected sequence length 2, got 3

- Can't parse 'dsize'. Expected sequence length 2, got 3

Please help :(


Solution

  • With vijayachandran mariappan comment and AndreaYolo answer I figured out a solution. First, change the channels of the image and then resize its dimensions:

    decoded_image = string_to_image(image_base64)
    decoded_image = decoded_image[:,:,:3]
    image_resized = tf.image.resize(decoded_image, (256, 256))
    

    My model then was able to predict perfectly!