如何在使用 base64 编码图像的同时使用 tensorflow serve 部署 keras 模型?
How do deploy a keras model with tensorflow serve, while using base64 encodede images?
将 keras 模型引入生产时,tensorflow serve 通常用作 REST API。它有一些缺点,因为图像数据需要与网络输入层相同的输入格式,例如json 中形状为 (300,300,3) 的数组。使这项工作有效的唯一方法似乎是将 tensorflow 服务 API 包装到另一个服务中。
如何让 tensorflow 服务提供一个 keras 模型,它接受 base64 编码的图像,而不用另一个 API 包装它?
我找到了解决方案,here 是更详细的解释:
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)
将 keras 模型引入生产时,tensorflow serve 通常用作 REST API。它有一些缺点,因为图像数据需要与网络输入层相同的输入格式,例如json 中形状为 (300,300,3) 的数组。使这项工作有效的唯一方法似乎是将 tensorflow 服务 API 包装到另一个服务中。
如何让 tensorflow 服务提供一个 keras 模型,它接受 base64 编码的图像,而不用另一个 API 包装它?
我找到了解决方案,here 是更详细的解释:
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)