tensorflow - 如何使用 base64 图像发送 POST 请求
问题描述
问题
我一直无法找到描述通过 POST 请求发送(base64)图像的方法的来源。我尝试编辑签名,使其接受 base64 图像作为输入,但没有成功。是否可以更改模型以使其接受(base64)图像作为输入?如果不是,我可以在我的客户端上将我创建的图像转换为正确的格式吗?源代码/日志
我目前正在使用标准签名保存我的 keras 模型:
tf.saved_model.save(model, "path")
获取请求结果表明模型已部署:
{ "version": "4", "state": "AVAILABLE", "status": { "error_code": "OK", "error_message": "" } }
我正在使用“react-native-image-base64”库将我的图像转换为 base64,并使用格式正确的发布请求发送它。但是,正如错误代码所说,它需要一个浮点数
"error": "Failed to process element: 0 of \'instances\' list. Error: Invalid argument: JSON Value: {"Base64 image string here"} Type: Object is not of expected type: float"
有以下要求:
curl --request POST \
--url http://192.168.1.75:8501/v1/models/saved_model:predict \
--header 'content-type: application/json' \
--data '
{
"instances":
[
{
"b64": "HBwcIiIiIiIiHh4eGhoaGBgYExMTEBAQERERERERDw8PCQkJBQ.."
}
]
}'
当前签名定义
signature_def['serving_default']:
The given SavedModel SignatureDef contains the following input(s):
inputs['conv2d_input'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 102, 136, 3)
name: serving_default_conv2d_input:0
The given SavedModel SignatureDef contains the following output(s):
outputs['dense'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 2)
name: StatefulPartitionedCall:0
Method name is: tensorflow/serving/predict
解决方案
您SignatureDef
表示输入的数据类型是Float
。
因此,您可以直接将Float
Value 作为 Input 传递,无需将其转换为,Base64 Encoded Format
因为我们Base64 Encoding
在Data Type
Input 为时使用String
。
POST
通过请求发送图像以进行推理的代码grpc
如下所示:
import grpc
import requests
import tensorflow as tf
import cv2
import os
import numpy as np
IMG_SIZE = 224
def main():
img_array = cv2.imread('/content/daisy.jpg')
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
new_array = new_array / 255
import json
data = json.dumps(
{"signature_name": "serving_default", "instances": new_array.reshape(-1, 224, 224, 3).tolist()})
print('Data: {} ... {}'.format(data[:50], data[len(data) - 52:]))
headers = {"content-type": "application/json"}
json_response = requests.post('http://35.226.32.128/v1/models/test0221/versions/1:predict', data=data, headers=headers)
predictions = json.loads(json_response.text)['predictions']
np.argmax(predictions[0])
dicti
for flower, label in dicti.items():
if label == np.argmax(predictions[0]):
print('Predicted Class is {}'.format(flower))
if __name__ == '__main__':
main()
上述代码的输出如下所示:
Data: {"signature_name": "serving_default", "instances": ... 6862745, 0.5019607843137255, 0.5176470588235295]]]]}
Predicted Class is Daisy
推荐阅读
- node.js - 当有人加入服务器时,我无法看到其他人的视频
- sql - 编写查询以查找登录用户
- android - 在 iOS 模拟器上启动 Flutter 应用程序时出错,应用程序崩溃
- wordpress - 将产品图库图像大小从 300*300 更改为实际图像的钩子是什么?
- c# - 如何根据所述数组的长度重命名数组中的元素?(在 Unity 检查器中)
- c# - 如何检查字符串是否包含变音符号并保留变音符号
- c - 仅使用宏查找三个数字中的最大值
- sql - Firebird 存储过程中可变数量的参数
- angular - 迁移到 Angular 11(自定义 webpack)后 SCSS 编译中的“TypeError: node.getIterator is not a function”
- javascript - 使用 lodash _.flow 过滤、减少、映射