在Jupyter Notebook中调用ML模型服务图像标题生成器

说明:写本文的目的主要是验证如何在Jupyter Notebook中通过API调用机器学习模型服务。

1、环境说明

CentOS7(部署在VMware Workstation Pro中的虚拟机)
需要安装有docker


2、前提条件:镜像准备

部署了图形检测服务的镜像:codait/max-image-caption-generator
Github地址:https://github.com/IBM/MAX-Image-Caption-Generator

该模型识别出COCO数据集中80个不同的高级对象类的图像中存在的对象。

    
部署了Jupyter服务的镜像:onnx/onnx-ecosystem
Github地址: https://github.com/onnx/onnx-docker/tree/master/onnx-ecosystem

由于CentOS中未安装jupyter,因此直接使用一个包含jupyter的镜像,在使用该镜像前使用了其它镜像,但是可能存在包安装不成功的问题。

3、启动镜像

docker run -it -p 5000:5000 codait/max-image-caption-generator

该容器提供的图像检测服务的地址为http://宿主机IP:5000/model/predict

docker run -p 8888:8888 onnx/onnx-ecosystem

4、在Notebook中调用图像检测服务

! pip install -q matplotlib Pillow requests

import io
from PIL import Image
import matplotlib
from matplotlib import pyplot as plt
import matplotlib.patches as patches
import requests

def call_model(input_img, local_port=None):
    """
    Takes in input image file path, posts the image to the model and returns face bboxes and emotion predictions
    If local port is not specified, uses the long running instance.
    If local port is specificed, uses the local instance.
    """
    if local_port:
        url = 'http://192.168.64.242:'+ str(local_port)+'/model/predict'
    else:
        url = 'nothing'

    files = {'image': ('image.jpg', open(input_img, 'rb'), 'images/jpeg') }
    r = requests.post(url, files=files).json()
    
    return r


img_path = './dog'
image = Image.open(img_path)
image


model_response = call_model(img_path, 5000)

import json
print(json.dumps(model_response, indent=2))

执行后生成的标题如下所示:

三个最大概率的标题基本含义都是“一只微笑的哈巴狗在滑板上”,可以看出成功检查到了狗狗和狗狗的表情,但是将地板识别为滑板。

{
  "status": "ok",
  "predictions": [
    {
      "caption": "a small pug dog standing on a skateboard .",
      "index": "0",
      "probability": 0.0010022024578866463
    },
    {
      "caption": "a small pug dog standing on top of a skateboard .",
      "index": "1",
      "probability": 0.0006507893851378613
    },
    {
      "caption": "a small pug dog sitting on a skateboard .",
      "index": "2",
      "probability": 0.0005334585197032779
    }
  ]
}

 

代码执行过程截图如下所示:

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汀桦坞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值