模型导出与部署tensorflowclient对接模型服务(代码片段)

ZSYL ZSYL     2022-12-22     661

关键词:

  • 应用TensorFlow Serving Client完成对接模型服务编写以及运行

1. Tensorflow Client代码编写对接Web

  • main.py当中调用
# 获取用户上传图片
image = request.files.get('image')
if not image:
abort(400)
# 预测标记
result_img = make_prediction(image.read())
data = result_img.read()
result_img.close()

1.1 Client端代码

需要用到tensorflow_serving.apis中的两个模块

from tensorflow_serving.apis import prediction_service_pb2_grpc
from tensorflow_serving.apis import predict_pb2
  1. prediction_service_pb2_grpc

  2. predict_pb2

  • prediction.py文件当中,定义make_prediction函数进行预测代码逻辑
    • 步骤分析
      • 1、获取读取后台读取的图片
      • 2、图片大小处理,转换数组
      • 3、打开通道channel,构建stub,预测结果
      • 4、predict_pb2进行预测请求创建

2. 步骤过程

  • 1、获取读取后台读取的图片,图片大小处理,转换数组
def make_prediction(image):
    """
    """
    def resize_img(image, target_size):
        img = io.BytesIO()
        img.write(image)
        img = Image.open(img).convert("RGB")
        if target_size:
            img = img.resize((target_size[1], target_size[0]))
        return img

    image = resize_img(image, (300, 300))
    image_array = img_to_array(image)

    feature = []
    feature.append(image_array)
    img_tensor = preprocess_input(np.array(feature))
    print(img_tensor.shape)
  • 2、打开通道channel,构建stub,预测结果,predict_pb2进行预测请求创建
 # 打开到tensorflow server的通道
    with grpc.insecure_channel('127.0.0.1:8500') as channel:
        stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)

        # 创建预测请求
        request = predict_pb2.PredictRequest()
        request.model_spec.name = 'commodity'
        request.model_spec.signature_name = signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
        request.inputs['images'].CopyFrom(tf.contrib.util.make_tensor_proto(img_tensor, shape=[1, 300, 300, 3]))

        # 进行预测
        result = stub.Predict(request)
'concat_3:0': <tf.Tensor 'concat_3:0' shape=(?, 7308, 21) dtype=float32>
  • 3、预测结果过滤并且解析,图片标记
with tf.Session() as sess:
            _res = sess.run(tf.convert_to_tensor(result.outputs['concat_3:0']))
        # 3、测试阶段 进行NMS 过滤
        butil = BBoxUtility(9)

        outputs = butil.detection_out(_res)

    return tag_picture(image_array, outputs)
  • tag_picture的逻辑
import matplotlib.pyplot as plt
import numpy as np
from io import BytesIO

classes_name = ['clothes', 'pants', 'shoes', 'watch', 'phone',
                             'audio', 'computer', 'books']


def tag_picture(img, outputs):
    """
    对图片预测物体进行画图显示
    :param images_data: N个测试图片数据
    :param outputs: 每一个图片的预测结果
    :return:
    """
    # 1、先获取每张图片6列中的结果

    # 通过i获取图片label, location, xmin, ymin, xmax, ymax
    pre_label = outputs[0][:, 0]
    pre_conf = outputs[0][:, 1]
    pre_xmin = outputs[0][:, 2]
    pre_ymin = outputs[0][:, 3]
    pre_xmax = outputs[0][:, 4]
    pre_ymax = outputs[0][:, 5]

    top_indices = [i for i, conf in enumerate(pre_conf) if conf >= 0.3]
    top_conf = pre_conf[top_indices]
    top_label_indices = pre_label[top_indices].tolist()
    top_xmin = pre_xmin[top_indices]
    top_ymin = pre_ymin[top_indices]
    top_xmax = pre_xmax[top_indices]
    top_ymax = pre_ymax[top_indices]

    # print("pre_label:, pre_loc:, pre_xmin:, pre_ymin:,pre_xmax:,pre_ymax:".
    #       format(tag_label, tag_loc, tag_xmin, tag_ymin, tag_xmax, tag_ymax))

    # 对于每张图片的结果进行标记
    colors = plt.cm.hsv(np.linspace(0, 1, 21)).tolist()
    plt.imshow(img / 255.)
    currentAxis = plt.gca()

    for i in range(top_conf.shape[0]):
        xmin = int(round(top_xmin[i] * img.shape[1]))
        ymin = int(round(top_ymin[i] * img.shape[0]))
        xmax = int(round(top_xmax[i] * img.shape[1]))
        ymax = int(round(top_ymax[i] * img.shape[0]))

        # 获取该图片预测概率,名称,定义显示颜色
        score = top_conf[i]
        label = int(top_label_indices[i])
        label_name = classes_name[label - 1]
        display_txt = ':0.2f, '.format(score, label_name)
        coords = (xmin, ymin), xmax - xmin + 1, ymax - ymin + 1
        color = colors[label]
        # 显示方框
        currentAxis.add_patch(plt.Rectangle(*coords, fill=False, edgecolor=color, linewidth=2))
        # 左上角显示概率以及名称
        currentAxis.text(xmin, ymin, display_txt, bbox='facecolor': color, 'alpha': 0.5)

        # plt.show()
    image_io = BytesIO()
    plt.savefig(image_io, format='png')
    image_io.seek(0)
    return image_io

完整代码:

import tensorflow as tf
import grpc
from tensorflow_serving.apis import prediction_service_pb2_grpc
from tensorflow_serving.apis import predict_pb2
from tensorflow.python.saved_model import signature_constants

from keras.preprocessing.image import img_to_array
from keras.applications.imagenet_utils import preprocess_input
from utils.ssd_utils import BBoxUtility
from utils.tag_img import tag_picture
import io
from PIL import Image
import numpy as np


def make_prediction(image):
    """
    """
    def resize_img(image, target_size):
        img = io.BytesIO()
        img.write(image)
        img = Image.open(img).convert("RGB")
        if target_size:
            img = img.resize((target_size[1], target_size[0]))
        return img

    image = resize_img(image, (300, 300))
    image_array = img_to_array(image)

    feature = []
    feature.append(image_array)
    img_tensor = preprocess_input(np.array(feature))
    print(img_tensor.shape)

    # 打开到tensorflow server的通道
    with grpc.insecure_channel('127.0.0.1:8500') as channel:
        stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)

        # 创建预测请求
        request = predict_pb2.PredictRequest()
        request.model_spec.name = 'commodity'
        request.model_spec.signature_name = signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
        request.inputs['images'].CopyFrom(tf.contrib.util.make_tensor_proto(img_tensor, shape=[1, 300, 300, 3]))

        # 进行预测
        result = stub.Predict(request)

        with tf.Session() as sess:
            _res = sess.run(tf.convert_to_tensor(result.outputs['concat_3:0']))
        # 3、测试阶段 进行NMS 过滤
        butil = BBoxUtility(9)

        outputs = butil.detection_out(_res)

    return tag_picture(image_array, outputs)

模型导出与部署项目接口与百度机器人对接(代码片段)

项目接口与百度机器人对接1.百度服务机器人介绍2.接口对接百度修改2.1web对接口1.百度服务机器人介绍开放平台架构机器人后台配置网址:https://console.bce.baidu.com/abcrobot/#/consolePage/extAbility/objIdentify需要企业百度云账号,这里做... 查看详情

模型导出与部署tfserving与web开启服务(代码片段)

TFServing与Web开启服务1.TensorFlowServing1.1安装TensorflowServing2.TensorFlowServingDocker3.案例操作:commodity模型服务运行应用TensorFlowServing完成模型服务运行1.TensorFlowServingTensorFlowServing是一种灵活的高性能服务系统,适用于机 查看详情

模型导出与部署webserver开启(代码片段)

...序(flask程序)的方法应用TensorFlowServingClient完成模型服务调用预测应用Docker完成Web服务的运行1.Docker管理运行Web部分此部份的docker镜像需要自己通过Dockerfile来制作创建名称的Dockerfile的文本文件(没有后缀名&#x 查看详情

openvino+paddlecpu部署新冠肺炎ct图像分类识别与病害分割(代码片段)

...主要是想要在飞桨上通过Cla与Seg(分类和分割)模型对CT图像进行处理,然后将他们导出onnx模型下载到自己的设备上,通过openVINO转化为IR模型后,能够在CPU上就能够实现对新冠肺炎CT图片进行处理。这里我会... 查看详情

tis教程03-导出(代码片段)

简介众所周知,模型部署框架部署的是深度学习模型,因此我们希望TIS只对模型的推理进行处理,故而需要提供给它合适的模型。而对于PyTorch的模型而言,有着主要的两种部署级模型,一种就是通用的ONNX模型... 查看详情

tis教程03-导出(代码片段)

简介众所周知,模型部署框架部署的是深度学习模型,因此我们希望TIS只对模型的推理进行处理,故而需要提供给它合适的模型。而对于PyTorch的模型而言,有着主要的两种部署级模型,一种就是通用的ONNX模型... 查看详情

powerdesigner概念模型与物理模型相互转换及导出数据字典

原文:PowerDesigner概念模型与物理模型相互转换及导出数据字典 最近公司项目竣工,验收完成后,把整体平台的所有文档都写清楚,找包发给甲方,由于本人是维护数据库工作,依上面要求,必须编写《数据库设计说明书》里... 查看详情

自动驾驶感知算法实战14——感知算法模型生产线

...rmve/category_12097938.html目录一、感知算法生产流程二、算法模型部署流程二、各个阶段交付物数据选择(数据采集、数据增强)数据标注模型训练模型量化模型部署测试与验证一、感知算法生产流程二、算法模型部署流程二、各个... 查看详情

导出3dsmax贴图坐标与顶点位置出错

...出错俺是C++程序员,对3dsmax了解不多。设计了一个Maxscript模型导出插件,又编写了一个载入导出的数据并显示模型的程序。发现有的模型数据导出后,贴图坐标能在俺的程序中正确显示,有的模型导出后,在俺的程序中,贴图坐... 查看详情

“共享内存模型”与“消息传递模型”

共享内存模型概述在共享内存模型中,应用程序进程会在其本地地址空间中创建一个RSM导出段。一个或多个远程应用程序进程创建RSM导入段,在导出段与导入段之间建立互连的虚拟连接。所有进程将使用其特定地址空间... 查看详情

自动驾驶感知算法实战14——感知算法模型生产线

...rmve/category_12097938.html目录一、感知算法生产流程二、算法模型部署流程二、各个阶段交付物数据选择(数据采集、数据增强)数据标注模型训练模型量化模型部署测试与验证一、感知算法生产流程二、算法模型部署流程二、各个... 查看详情

自动驾驶感知算法实战14——感知算法模型生产线

...rmve/category_12097938.html目录一、感知算法生产流程二、算法模型部署流程二、各个阶段交付物数据选择(数据采集、数据增强)数据标注模型训练模型量化模型部署测试与验证一、感知算法生产流程二、算法模型部署流程二、各个... 查看详情

powerdesigner概念模型与物理模型相互转换及导出数据字典

...编写《数据库设计说明书》里面格式包含三个部分:概念模型、物理模型、数据字典;平时我使用PowerDesigner工具维护数据库表的结构变化,所有表加起来得200多张表,全部以物理模型存储;转换成概念模型应该没问题,转换成... 查看详情

部署准备1(代码片段)

...备环境。安装好CMake、OpenCV等工具准备PaddleLite推理库准备模型构建并运行程序总结引用柠檬分类范例 两点:模型的输入与输出模型的预处理与后处理 如果你想了解一个陌生模型的输入与输出该怎么做呢?可以使用VisualD... 查看详情

githubshareai开发七巧板,快速训练部署与监控机器学习模型,清晰查看模型的各项统计数据

...#xff0c;一个可帮助AI开发者快速训练、部署与监控机器学习模型的开源工具。通过该项目提供的命令行工具与App,可清晰查看模型的各项统计数据与指标,调整模型并提升性能,跟踪并计算生产环境模型精准度等功能。... 查看详情

模型推理比特大陆se5边缘盒子caffessd量化与转换部署模型(代码片段)

...本教程详细记录了在比特大陆SE5边缘盒子上对caffeSSD检测模型进行量化和转换部署模型的方法。文章目录1、准备ssd模型2、转换fp32bmodel2.1转fp32bmodel2.2、模型精度验证3、Int8量化与模型转换3.1模型转换fp32umodel3.2模型转换int8umodel3.2.1... 查看详情

three.js使用与踩坑(动画制作导出,three.js加载模型与动画)

...AR.js.这里我们重点了解Three.js。Three.js可以加载json类型的模型文件与动画,Three.js提供的方案的是用Blender建模软件来导出json给Three.js加载。这里我尝试了加载json类型的文件,这里我参考了demo里的效果制作。结果也是正确的。但... 查看详情

Tensorflow 服务:导出模型时“没有要保存/写入的资产”

】Tensorflow服务:导出模型时“没有要保存/写入的资产”【英文标题】:Tensorflowserving:"Noassetstosave/writes"whenexportingmodels【发布时间】:2018-04-1204:15:45【问题描述】:最近我正在尝试使用tensorflow服务部署深度学习服务。但... 查看详情