首页 > 解决方案 > 如何使用 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

标签: tensorflowtensorflow2.0tensorflow-serving

解决方案


SignatureDef表示输入的数据类型是Float

因此,您可以直接将FloatValue 作为 Input 传递,无需将其转换为,Base64 Encoded Format因为我们Base64 EncodingData TypeInput 为时使用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

推荐阅读