python - 如何在使用 base64 编码图像的同时使用 tensorflow 部署 keras 模型?
问题描述
将 keras 模型引入生产时,tensorflow 服务通常用作 REST API。它有一些缺点,因为图像数据需要与网络输入层相同的输入格式,例如 json 中形状为 (300,300,3) 的数组。使这项工作的唯一方法似乎是将 tensorflow 服务 API 包装到另一个服务中。
如何让 tensorflow 提供一个接受 base64 编码图像的 keras 模型,而不将其包装在另一个 API 中?
解决方案
我找到了一个解决方案,这里有一个更详细的解释:
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)
推荐阅读
- spring-boot - 如何在服务启动时使用 cron 表达式启动骆驼石英作业
- typescript - 构建时找不到模块
- r - 如果我退出,Rstudio 服务器会继续运行我的代码吗?
- heroku - Pybind11 模块无法部署到heroku
- visual-studio - 反编译器是否可以访问 app.config 中的字符串
- pine-script - 正确使用 strategy.order
- mongodb - 设置robo3t连接mongodb
- regex - 数据框转换产生空值
- javascript - JavaScript_Truthy 和 Falsy 作业_codecademy
- r - 使用复制按钮时如何从 DT::datatable 中删除标题