tensorflow 预期形状=(无,256,256,3),找到的形状=(无,256,256,4)

juzqafwq  于 2022-11-16  发布在  其他
关注(0)|答案(2)|浏览(267)

我正在使用以下代码解码base64图像:

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

我们的目标是从请求主体接收一个图像,对其进行解码,使用tensorflow调整其大小,使用模型对其进行预测,并返回一个响应,说明该图像是什么:

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))

但是,我得到错误ValueError: Input 0 of layer "sequential_2" is incompatible with the layer: expected shape=(None, 256, 256, 3), found shape=(None, 256, 256, 4)
我不知道如何将Shape值从“4”更改为“3”。
我尝试了以下方法:

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

但我得到了'size' must be a 1-D Tensor of 2 elements: new_height, new_width
我也试探着:

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

但是我得到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
请帮助:(

3npbholx

3npbholx1#

你可以在重新调整Tensor后使用tf.squeeze重新调整数组的形状。根据文档,tf.squeeze将删除维数为1的轴。

image_resized = tf.reshape(decoded_image, (-1, 256, 256, 3, 1))
image_resized = tf.squeeze(image_resized)
lzfw57am

lzfw57am2#

通过 vijayachandran mariappan comment和 AndreaYolo answer,我想出了一个解决方案。首先,改变图像的通道,然后调整其尺寸:

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

我的模型能够完美地预测!

相关问题