首页 > 解决方案 > 如何在使用 base64 编码图像的同时使用 tensorflow 部署 keras 模型?

问题描述

将 keras 模型引入生产时,tensorflow 服务通常用作 REST API。它有一些缺点,因为图像数据需要与网络输入层相同的输入格式,例如 json 中形状为 (300,300,3) 的数组。使这项工作的唯一方法似乎是将 tensorflow 服务 API 包装到另一个服务中。

如何让 tensorflow 提供一个接受 base64 编码图像的 keras 模型,而不将其包装在另一个 API 中?

标签: pythontensorflowkerastensorflow-serving

解决方案


我找到了一个解决方案,这里有一个更详细的解释:

import tensorflow as tf
sess = tf.Session() # get the tensorflow session to reuse it in keras

from keras import backend as K
from keras.models import load_model

K.set_session(sess)
K.set_learning_phase(0) # make sure we disable dropout and other training specific layers

string_inp = tf.placeholder(tf.string, shape=(None,)) #string input for the base64 encoded image
imgs_map = tf.map_fn(
    tf.image.decode_image,
    string_inp,
    dtype=tf.uint8
) # decode jpeg
imgs_map.set_shape((None, None, None, 3))
imgs = tf.image.resize_images(imgs_map, [300, 300]) # resize images
imgs = tf.reshape(imgs, (-1, 300, 300, 3)) # reshape them 
img_float = tf.cast(imgs, dtype=tf.float32) / 255 - 0.5 # and make them to floats

model = load_model('keras.h5', compile=False) # load the model
output = model(img_float) # use the image tensor as input for keras
# ...(save to savedModel format and load in tensorflow serve)

推荐阅读