Step 01: Detecting Objects Using mobilenet

This tutorial and the assets can be downloaded as part of the Wallaroo Tutorials repository.

Step 01: Detecting Objects Using mobilenet

The following tutorial demonstrates how to use a trained mobilenet model deployed in Wallaroo to detect objects. This process will use the following steps:

  1. Create a Wallaroo workspace and pipeline.
  2. Upload a trained mobilenet ML model and add it as a pipeline step.
  3. Deploy the pipeline.
  4. Perform an inference on a sample image.
  5. Draw the detected objects, their bounding boxes, their classifications, and the confidence of the classifications on the provided image.
  6. Review our results.

Steps

Import Libraries

The first step will be to import our libraries. Please check with Step 00: Introduction and Setup and verify that the necessary libraries and applications are added to your environment.

# preload needed libraries 

import wallaroo
from wallaroo.object import EntityNotFoundError
from wallaroo.framework import Framework
from IPython.display import display
from IPython.display import Image
import pandas as pd
import json
import datetime
import time
import cv2
import matplotlib.pyplot as plt
import string
import random
import pyarrow as pa
import sys
import asyncio
pd.set_option('display.max_colwidth', None)

import sys

import utils

Connect to the Wallaroo Instance

The first step is to connect to Wallaroo through the Wallaroo client. The Python library is included in the Wallaroo install and available through the Jupyter Hub interface provided with your Wallaroo environment.

This is accomplished using the wallaroo.Client() command, which provides a URL to grant the SDK permission to your specific Wallaroo environment. When displayed, enter the URL into a browser and confirm permissions. Store the connection into a variable that can be referenced later.

If logging into the Wallaroo instance through the internal JupyterHub service, use wl = wallaroo.Client(). For more information on Wallaroo Client settings, see the Client Connection guide.

# Login through local service

wl = wallaroo.Client()

Set Variables

The following variables and methods are used later to create or connect to an existing workspace, pipeline, and model.

Verify that the workspace name is unique before running.

workspace_name = f'mobilenetworkspacetest'
pipeline_name = f'mobilenetpipeline'
model_name = f'mobilenet'
model_file_name = 'models/mobilenet.pt.onnx'
def get_workspace(name, client):
    workspace = None
    for ws in client.list_workspaces():
        if ws.name() == name:
            workspace= ws
    if(workspace == None):
        workspace = client.create_workspace(name)
    return workspace

# get a pipeline by name in the workspace
def get_pipeline(pipeline_name, workspace):
    plist = workspace.pipelines()
    pipeline = [p for p in plist if p.name() == pipeline_name]
    if len(pipeline) <= 0:
        raise KeyError(f"Pipeline {pipeline_name} not found in this workspace")
        return None
    return pipeline[0]

Create Workspace

The workspace will be created or connected to, and set as the default workspace for this session. Once that is done, then all models and pipelines will be set in that workspace.

workspace = get_workspace(workspace_name, wl)
wl.set_current_workspace(workspace)
wl.get_current_workspace()
{'name': 'mobilenetworkspacetest', 'id': 29, 'archived': False, 'created_by': 'df2b4a6c-b749-466a-95b4-60cf14fc354d', 'created_at': '2024-02-05T15:49:56.55276+00:00', 'models': [], 'pipelines': []}

Create Pipeline and Upload Model

We will now create or connect to an existing pipeline as named in the variables above. Because image size may vary from one image to the next, converting the image to a tensor array may have a different shape from one image to the next. For example, a 640x480 image produces an array of [640][480][3] for 640 rows with 480 columns each, and each pixel has 3 possible color values.

Because the tensor array size may change from image to image, the model upload sets the model’s batch configuration to batch_config="single". See the Wallaroo Data Schema Definitions for more details.

pipeline = wl.build_pipeline(pipeline_name)
mobilenet_model = (wl.upload_model(model_name, 
                                   model_file_name, 
                                   framework=Framework.ONNX)
                                   .configure(batch_config="single", 
                                              tensor_fields=["tensor"]))

Upload Post Processing Module

The following module takes the results from the CV model output, and averages the confidence values from all detected objects. This is used for observability and model drift tracking.

input_schema = pa.schema([
    pa.field('boxes', pa.list_(pa.list_(pa.float32(), list_size=4))),
    pa.field('classes', pa.list_(pa.int64())),
    pa.field('confidences', pa.list_(pa.float32())),])

output_schema = pa.schema([
    pa.field('boxes', pa.list_(pa.list_(pa.float32(), list_size=4))),
    pa.field('classes', pa.list_(pa.int64())),
    pa.field('confidences', pa.list_(pa.float32())),
    pa.field('avg_conf', pa.float32()),
])
module_post_process_model = wl.upload_model("cv-post-process-drift-detection", "./models/post-process-drift-detection-arrow.py",framework=Framework.PYTHON) \
    .configure('python', input_schema=input_schema, output_schema=output_schema)

Deploy Pipeline

With the model uploaded, we can add it is as a step in the pipeline, then deploy it. Once deployed, resources from the Wallaroo instance will be reserved and the pipeline will be ready to use the model to perform inference requests.

pipeline.add_model_step(mobilenet_model)
pipeline.add_model_step(module_post_process_model)

deploy_config = wallaroo.DeploymentConfigBuilder().replica_count(1).cpus(1).memory("1Gi").build()
pipeline.deploy(deployment_config=deploy_config)
namemobilenetpipeline
created2024-02-05 15:49:57.871576+00:00
last_updated2024-02-05 15:50:06.367196+00:00
deployedTrue
archNone
tags
versions9bc5f815-5351-4e2e-bf28-39a8d1d1ac5a, b85b8e67-5623-4f43-8571-ca2e2735d56f
stepsmobilenet
publishedFalse

Prepare input image

Next we will load a sample image and resize it to the width and height required for the object detector. Once complete, it the image will be converted to a numpy ndim array and added to a dictionary.

image = cv2.imread('./data/images/input/example/dairy_bottles.png')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.figure(figsize=(12,8))
plt.grid(False)
plt.imshow(image)
plt.show()
width, height = 640, 480
df_with_numpy, resizedImage = utils.loadImageAndConvertToDataframe('./data/images/input/example/dairy_bottles.png', width, height)
display(df_with_numpy.loc[0, 'tensor'][0][0][0][0:3])
display(df_with_numpy.loc[0, 'tensor'][0][0][1][0:3])
display(df_with_numpy.loc[0, 'tensor'][0][1][0][0:3])
display(df_with_numpy.loc[0, 'tensor'][0][1][1][0:3])
array([0.9372549, 0.9529412, 0.9490196], dtype=float32)

array([0.93333334, 0.9490196 , 0.9490196 ], dtype=float32)

array([0.9372549 , 0.9490196 , 0.94509804], dtype=float32)

array([0.93333334, 0.9490196 , 0.94509804], dtype=float32)

df_with_flattened_array = pd.DataFrame({'tensor': wallaroo.utils.flatten_np_array_columns(df_with_numpy, 'tensor')})
df_with_flattened_array.loc[0, 'tensor'][0:5]
array([0.9372549 , 0.9529412 , 0.9490196 , 0.94509804, 0.94509804],
      dtype=float32)

Run Inference

With that done, we can have the model detect the objects on the image by running an inference through the pipeline, and storing the results for the next step.

startTime = time.time()
infResults = pipeline.infer(dfImage, timeout=300)
endTime = time.time()
infResults.loc[:, ['time', 'out.avg_conf']]
timeout.avg_conf
02023-12-07 19:06:47.04728.95%

Draw the Inference Results

With our inference results, we can take them and use the Wallaroo CVDemo class and draw them onto the original image. The bounding boxes and the confidence value will only be drawn on images where the model returned a 90% confidence rate in the object’s identity.

elapsed = 1.0
results = {
    'model_name' : model_name,
    'pipeline_name' : pipeline_name,
    'width': width,
    'height': height,
    'image' : resizedImage,
    'inf-results' : infResults,
    'confidence-target' : 0.50,
    'inference-time': (endTime-startTime),
    'onnx-time' : int(elapsed) / 1e+9,
    'classes_file': "./models/coco_classes.pickle",                 
    'color': 'BLUE'
}

image = utils.drawDetectedObjectsFromInference(results)

Undeploy the Pipeline

With the inference complete, we can undeploy the pipeline and return the resources back to the Wallaroo instance.

pipeline.undeploy()
namemobilenetpipeline
created2023-12-07 17:47:02.394926+00:00
last_updated2023-12-07 19:05:20.801624+00:00
deployedFalse
archNone
tags
versions9f37ec5a-f8ff-4b2d-bffc-761efb5e5c39, e4535ba2-eefa-4e47-b958-d3b53082b84d, 3f719565-e0a4-4a71-89d5-3be3496d646e, 13ebadd2-dd7e-4881-8e7d-80701930f9cc
stepsmobilenet
publishedFalse