在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
    }
  ]
}

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

发布了227 篇原创文章 · 获赞 94 · 访问量 54万+

猜你喜欢

转载自blog.csdn.net/wiborgite/article/details/95656084