Wallaroo Edge Computer Vision For Health Care Imaging Publication and Deployment

A demonstration on publishing a CV model based Wallaroo pipeline to Edge devices.

The following tutorial is available on the Wallaroo Tutorials repository.

Computer Vision Healthcare Images Edge Deployment Tutorial

The following tutorial demonstrates how to use Wallaroo to detect mitochondria from high resolution images, publish the Wallaroo pipeline to an Open Container Initiative (OCI) Registry, and deploy it in an edge system. For this example we will be using a high resolution 1536x2048 image that is broken down into “patches” of 256x256 images that can be quickly analyzed.

Mitochondria are known as the “powerhouse” of the cell, and having a healthy amount of mitochondria indicates that a patient has enough energy to live a healthy life, or may have underling issues that a doctor can check for.

Scanning high resolution images of patient cells can be used to count how many mitochondria a patient has, but the process is laborious. The following ML Model is trained to examine an image of cells, then detect which structures are mitochondria. This is used to speed up the process of testing patients and determining next steps.

Tutorial Goals

This tutorial will perform the following:

  1. As a Data Scientist in the Wallaroo Ops instance:
    1. Upload and deploy the mitochondria_epochs_15.onnx model to a Wallaroo pipeline.
    2. Randomly select from from a selection of 256x256 images that were originally part of a larger 1536x2048 image.
    3. Convert the images into a numpy array inserted into a pandas DataFrame.
    4. Submit the DataFrame to the Wallaroo pipeline and use the results to create a mask image of where the model detects mitochondria.
    5. Compare the original image against a map of “ground truth” and the model’s mask image.
    6. Undeploy the pipeline and return the resources back to the Wallaroo instance.
    7. Publish the pipeline to an Edge deployment registry.
    8. Display different pipeline publishes functions.
  2. As a DevOps Engineer in a remote aka edge device:
    1. Deploy the published pipeline as a Wallaroo Inference Server through a Docker based deployment.
    2. Perform inference requests using the same data samples as in the Wallaroo deployed pipeline.
    3. Display the results.

References

Prerequisites

Complete the steps from Mitochondria Detection Computer Vision Tutorial Part 00: Prerequisites.

Mitochondria Computer Vision Detection Steps

Import Libraries

The first step is to import the necessary libraries. Included with this tutorial are the following custom modules:

  • tiff_utils: Organizes the tiff images to perform random image selections and other tasks.

Note that tensorflow may return warnings depending on the environment.

import json
import IPython.display as display
import time
import matplotlib.pyplot as plt
from IPython.display import clear_output, display
import tifffile as tiff
import requests

import pandas as pd

import wallaroo
from wallaroo.object import EntityNotFoundError
from wallaroo.framework import Framework

import numpy as np
from matplotlib import pyplot as plt
import cv2
#from tensorflow.keras.utils import normalize

#from lib.TiffImageUtils import TiffUtils
#tiff_utils = TiffUtils()

# ignoring warnings for demonstration
import warnings
warnings.filterwarnings('ignore')

Open a Connection to Wallaroo

The next step is 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 details on logging in through Wallaroo, see the Wallaroo SDK Essentials Guide: Client Connection.

wl = wallaroo.Client()

Create Workspace and Pipeline

We will create a workspace to manage our pipeline and models. The following variables will set the name of our sample workspace then set it as the current workspace.

Workspace, pipeline, and model names should be unique to each Wallaroo instance, so we’ll add in a randomly generated suffix so multiple people can run this tutorial in a Wallaroo instance without affecting each other.

workspace_name = f'edgebiolabsworkspace'
pipeline_name = f'edgebiolabspipeline'
model_name = f'edgebiolabsmodel'
model_file_name = 'models/mitochondria_epochs_15.onnx'
workspace = wl.get_workspace(name=workspace_name, create_if_not_exist=True)

wl.set_current_workspace(workspace)

pipeline = wl.build_pipeline(pipeline_name)
pipeline
nameedgebiolabspipeline
created2025-05-16 15:57:59.007227+00:00
last_updated2025-05-16 15:57:59.007227+00:00
deployed(none)
workspace_id1669
workspace_nameedgebiolabsworkspace
archNone
accelNone
tags
versions4815e577-a12b-4be0-9cb2-921af0865639
steps
publishedFalse

Upload the Models

Now we will:

  1. Upload our model.
  2. Apply it as a step in our pipeline.
  3. Create a pipeline deployment with enough memory to perform the inferences.
  4. Deploy the pipeline.
model = wl.upload_model(model_name, model_file_name, framework=Framework.ONNX)

Reserve Pipeline Resources

Before deploying an inference engine we need to tell wallaroo what resources it will need.
To do this we will use the wallaroo DeploymentConfigBuilder() and fill in the options listed below to determine what the properties of our inference engine will be.

We will be testing this deployment for an edge scenario, so the resource specifications are kept small – what’s the minimum needed to meet the expected load on the planned hardware.

  • cpus - 4 => allow the engine to use 4 CPU cores when running the neural net
  • memory - 8Gi => each inference engine will have 8 GB of memory, which is plenty for processing a single image at a time.
deployment_config = wallaroo.DeploymentConfigBuilder().replica_count(1).cpus(4).memory("8Gi").build()

pipeline = wl.build_pipeline(pipeline_name) \
            .clear() \
            .add_model_step(model) \
            .deploy(deployment_config = deployment_config, wait_for_status=False)
Deployment initiated for edgebiolabspipeline. Please check pipeline status.
# check the pipeline status before performing an inference

import time

while pipeline.status()['status'] != 'Running':
   time.sleep(15)

pipeline.status()
{'status': 'Running',
 'details': [],
 'engines': [{'ip': '10.4.8.6',
   'name': 'engine-76b687874b-xj2w2',
   'status': 'Running',
   'reason': None,
   'details': [],
   'pipeline_statuses': {'pipelines': [{'id': 'edgebiolabspipeline',
      'status': 'Running',
      'version': '708b33f4-8bb1-4527-a74b-81210d86fa4e'}]},
   'model_statuses': {'models': [{'model_version_id': 698,
      'name': 'edgebiolabsmodel',
      'sha': 'e80fcdaf563a183b0c32c027dcb3890a64e1764d6d7dcd29524cd270dd42e7bd',
      'status': 'Running',
      'version': 'e5cc10cb-b959-48a5-bf69-039193366e64'}]}}],
 'engine_lbs': [{'ip': '10.4.2.55',
   'name': 'engine-lb-5f76cc9c94-pdlmp',
   'status': 'Running',
   'reason': None,
   'details': []}],
 'sidekicks': []}

Retrieve Image and Convert to Data

The next step is to process the image into a numpy array that the model is trained to detect from.

We start by retrieving all the patch images from a recorded time series tiff recorded on one of our microscopes.

For this tutorial, we will be using the path ./patches/condensed, with a more limited number of images to save on local memory.

sample_mitochondria_patches_path = "./patches/condensed"

patches = tiff_utils.get_all_patches(sample_mitochondria_patches_path)

Randomly we will retrieve a 256x256 patch image and use it to do our semantic segmentation prediction.

We’ll then convert it into a numpy array and insert into a DataFrame for a single inference.

The following helper function loadImageAndConvertTiff is used to convert the image into a numpy, then insert that into the DataFrame. This allows a later command to take the randomly grabbed image perform the process on other images.

def loadImageAndConvertTiff(imagePath, width, height):
    img = cv2.imread(imagePath, 0)
    imgNorm = np.expand_dims(normalize(np.array(img), axis=1),2)
    imgNorm=imgNorm[:,:,0][:,:,None]
    imgNorm=np.expand_dims(imgNorm, 0)
    
    resizedImage = None
    #creates a dictionary with the wallaroo "tensor" key and the numpy ndim array representing image as the value.
    dictData = {"tensor":[imgNorm]}
    dataframedata = pd.DataFrame(dictData)
    # display(dataframedata)
    return dataframedata, resizedImage
def run_semantic_segmentation_inference(pipeline, input_tiff_image, width, height, threshold):
    
    tensor, resizedImage = loadImageAndConvertTiff(input_tiff_image, width, height)
    # print(tensor)

    # #
    # # run inference on the 256x256 patch image get the predicted mitochandria mask
    # #
    output = pipeline.infer(tensor)
    # print(output)

    # # Obtain the flattened predicted mitochandria mask result
    list1d = output.loc[0]["out.conv2d_37"]
    np1d = np.array(list1d)
    
    # # unflatten it
    predicted_mask = np1d.reshape(1,width,height,1)
    
    # # perform the element-wise comaprison operation using the threshold provided
    predicted_mask = (predicted_mask[0,:,:,0] > threshold).astype(np.uint8)
    
    # return predicted_mask
    return predicted_mask

Infer and Display Results

We will now perform our inferences and display the results. This results in a predicted mask showing us where the mitochondria cells are located.

  1. The first image is the input image.
  2. The 2nd image is the ground truth. The mask was created by a human who identified the mitochondria cells in the input image
  3. The 3rd image is the predicted mask after running inference on the Wallaroo pipeline.

We’ll perform this 10 times to show how quickly the inferences can be submitted.

random_patches = []

for x in range(10):
    random_patches.append(tiff_utils.get_random_patch_sample(patches))

for random_patch in random_patches:     
    # get a sample 256x256 mitochondria image
    # random_patch = tiff_utils.get_random_patch_sample(patches)

    # build the path to the image
    patch_image_path = sample_mitochondria_patches_path + "/images/" + random_patch['patch_image_file']

    # run inference in order to get the predicted 256x256 mask
    predicted_mask = run_semantic_segmentation_inference(pipeline, patch_image_path, 256,256, 0.2)

    # # plot the results
    test_image = random_patch['patch_image'][:,:,0]
    test_image_title = f"Testing Image - {random_patch['index']}"

    ground_truth_image = random_patch['patch_mask'][:,:,0]
    ground_truth_image_title = "Ground Truth Mask"

    predicted_mask_title = 'Predicted Mask'

    tiff_utils.plot_test_results(test_image, test_image_title, \
                            ground_truth_image, ground_truth_image_title, \
                            predicted_mask, predicted_mask_title)

Undeploy Pipeline

With the experiment complete, we will undeploy the pipeline.

pipeline.undeploy()
Waiting for undeployment - this will take up to 45s .................................... ok
nameedgebiolabspipeline
created2025-05-16 15:57:59.007227+00:00
last_updated2025-05-16 16:01:34.857687+00:00
deployedFalse
workspace_id1669
workspace_nameedgebiolabsworkspace
archx86
accelnone
tags
versions708b33f4-8bb1-4527-a74b-81210d86fa4e, 609999d2-c1bf-4e3f-ab8d-33508d9364d9, b660902e-fe59-4be3-b6a6-5354140c847e, f5d6d952-faf4-46ea-ab40-4032a20d7bb7, 4815e577-a12b-4be0-9cb2-921af0865639
stepsedgebiolabsmodel
publishedFalse

Publish the Pipeline for Edge Deployment

It worked! For a demo, we’ll take working once as “tested”. So now that we’ve tested our pipeline, we are ready to publish it for edge deployment.

Publishing it means assembling all of the configuration files and model assets and pushing them to an Open Container Initiative (OCI) repository set in the Wallaroo instance as the Edge Registry service. DevOps engineers then retrieve that image and deploy it through Docker, Kubernetes, or similar deployments.

See Edge Deployment Registry Guide for details on adding an OCI Registry Service to Wallaroo as the Edge Deployment Registry.

This is done through the SDK command wallaroo.pipeline.publish(deployment_config).

Publish Example

We will now publish the pipeline to our Edge Deployment Registry with the pipeline.publish(deployment_config) command. deployment_config is an optional field that specifies the pipeline deployment. This can be overridden by the DevOps engineer during deployment.

pub=pipeline.publish(deployment_config)
pub
Waiting for pipeline publish... It may take up to 600 sec.
... Published.blishing.
ID51
Pipeline Nameedgebiolabspipeline
Pipeline Versiona770d6dd-f06d-4d5f-83f5-139bdd3d6fa7
StatusPublished
Workspace Id1669
Workspace Nameedgebiolabsworkspace
Edges
Engine URLsample.registry.example.com/uat/engines/proxy/wallaroo/ghcr.io/wallaroolabs/fitzroy-mini:v2025.1.0-main-6139
Pipeline URLsample.registry.example.com/uat/pipelines/edgebiolabspipeline:a770d6dd-f06d-4d5f-83f5-139bdd3d6fa7
Helm Chart URLoci://sample.registry.example.com/uat/charts/edgebiolabspipeline
Helm Chart Referencesample.registry.example.com/uat/charts@sha256:e3b9f31019c88c47a84fdf80f04fd45024fb349d161510cc2cca793b3796009d
Helm Chart Version0.0.1-a770d6dd-f06d-4d5f-83f5-139bdd3d6fa7
Engine Config{'engine': {'resources': {'limits': {'cpu': 4.0, 'memory': '8Gi'}, 'requests': {'cpu': 4.0, 'memory': '8Gi'}, 'accel': 'none', 'arch': 'x86', 'gpu': False}}, 'engineAux': {'autoscale': {'type': 'none', 'cpu_utilization': 50.0}, 'images': {}}}
User Images[]
Created Byjohn.hummel@wallaroo.ai
Created At2025-05-16 16:02:31.284993+00:00
Updated At2025-05-16 16:02:31.284993+00:00
Replaces
Docker Run Command
docker run \
    -p $EDGE_PORT:8080 \
    -e OCI_USERNAME=$OCI_USERNAME \
    -e OCI_PASSWORD=$OCI_PASSWORD \
    -e PIPELINE_URL=sample.registry.example.com/uat/pipelines/edgebiolabspipeline:a770d6dd-f06d-4d5f-83f5-139bdd3d6fa7 \
    -e CONFIG_CPUS=4 --cpus=4.0 --memory=8g \
    sample.registry.example.com/uat/engines/proxy/wallaroo/ghcr.io/wallaroolabs/fitzroy-mini:v2025.1.0-main-6139

Note: Please set the EDGE_PORT, OCI_USERNAME, and OCI_PASSWORD environment variables.
Helm Install Command
helm install --atomic $HELM_INSTALL_NAME \
    oci://sample.registry.example.com/uat/charts/edgebiolabspipeline \
    --namespace $HELM_INSTALL_NAMESPACE \
    --version 0.0.1-a770d6dd-f06d-4d5f-83f5-139bdd3d6fa7 \
    --set ociRegistry.username=$OCI_USERNAME \
    --set ociRegistry.password=$OCI_PASSWORD

Note: Please set the HELM_INSTALL_NAME, HELM_INSTALL_NAMESPACE, OCI_USERNAME, and OCI_PASSWORD environment variables.

List Published Pipeline

The method wallaroo.client.list_pipelines() shows a list of all pipelines in the Wallaroo instance, and includes the published field that indicates whether the pipeline was published to the registry (True), or has not yet been published (False).

wl.list_pipelines(workspace_name=workspace_name)
namecreatedlast_updateddeployedworkspace_idworkspace_namearchacceltagsversionsstepspublished
edgebiolabspipeline2025-16-May 15:57:592025-16-May 16:02:31False1669edgebiolabsworkspacex86nonea770d6dd-f06d-4d5f-83f5-139bdd3d6fa7, 708b33f4-8bb1-4527-a74b-81210d86fa4e, 609999d2-c1bf-4e3f-ab8d-33508d9364d9, b660902e-fe59-4be3-b6a6-5354140c847e, f5d6d952-faf4-46ea-ab40-4032a20d7bb7, 4815e577-a12b-4be0-9cb2-921af0865639edgebiolabsmodelTrue

List Publishes from a Pipeline

All publishes created from a pipeline are displayed with the wallaroo.pipeline.publishes method. The pipeline_version_id is used to know what version of the pipeline was used in that specific publish. This allows for pipelines to be updated over time, and newer versions to be sent and tracked to the Edge Deployment Registry service.

List Publishes Parameters

N/A

List Publishes Returns

A List of the following fields:

FieldTypeDescription
idintegerNumerical Wallaroo id of the published pipeline.
pipeline_version_idintegerNumerical Wallaroo id of the pipeline version published.
engine_urlstringThe URL of the published pipeline engine in the edge registry.
pipeline_urlstringThe URL of the published pipeline in the edge registry.
created_bystringThe email address of the user that published the pipeline.
Created AtDateTimeWhen the published pipeline was created.
Updated AtDateTimeWhen the published pipeline was updated.
pipeline.publishes()
idPipeline NamePipeline VersionWorkspace IdWorkspace NameEdgesEngine URLPipeline URLCreated ByCreated AtUpdated At
51edgebiolabspipelinea770d6dd-f06d-4d5f-83f5-139bdd3d6fa71669edgebiolabsworkspacesample.registry.example.com/uat/engines/proxy/wallaroo/ghcr.io/wallaroolabs/fitzroy-mini:v2025.1.0-main-6139sample.registry.example.com/uat/pipelines/edgebiolabspipeline:a770d6dd-f06d-4d5f-83f5-139bdd3d6fa7john.hummel@wallaroo.ai2025-16-May 16:02:312025-16-May 16:02:31

DevOps - Pipeline Edge Deployment

Once a pipeline is deployed to the Edge Registry service, it can be deployed in environments such as Docker, Kubernetes, or similar container running services by a DevOps engineer. For our example, we will use the docker run command output during the pipeline publish.

Edge Deployed Pipeline API Endpoints

Once deployed, we can check the pipelines and models available. We’ll use a curl command, but any HTTP based request will work the same way.

The endpoint /pipelines returns:

  • id (String): The name of the pipeline.
  • status (String): The status as either Running, or Error if there are any issues.

For this example, the deployment is made on a machine called testboy.local. Replace this URL with the URL of you edge deployment.

!curl testboy.local:8080/pipelines
{"pipelines":[{"id":"edgebiolabspipeline","status":"Running"}]}

The endpoint /models returns a List of models with the following fields:

  • name (String): The model name.
  • sha (String): The sha hash value of the ML model.
  • status (String): The status of either Running or Error if there are any issues.
  • version (String): The model version. This matches the version designation used by Wallaroo to track model versions in UUID format.
!curl testboy.local:8080/models
{"models":[{"name":"edgebiolabsmodel","sha":"e80fcdaf563a183b0c32c027dcb3890a64e1764d6d7dcd29524cd270dd42e7bd","status":"Running","version":"37b76f7a-cef3-4dfb-8bed-c0779c0e668c"}]}

Edge Inference Endpoint

The inference endpoint takes the following pattern:

  • /pipelines/infer

Wallaroo inference endpoint URLs accept the following data inputs through the Content-Type header:

  • Content-Type: application/vnd.apache.arrow.file: For Apache Arrow tables.
  • Content-Type: application/json; format=pandas-records: For pandas DataFrame in record format.

Once deployed, we can perform an inference through the deployment URL.

The endpoint returns Content-Type: application/json; format=pandas-records by default with the following fields:

  • check_failures (List[Integer]): Whether any validation checks were triggered. For more information, see Wallaroo SDK Essentials Guide: Pipeline Management: Anomaly Testing.
  • elapsed (List[Integer]): A list of time in nanoseconds for:
    • [0] The time to serialize the input.
    • [1…n] How long each step took.
  • model_name (String): The name of the model used.
  • model_version (String): The version of the model in UUID format.
  • original_data: The original input data. Returns null if the input may be too long for a proper return.
  • outputs (List): The outputs of the inference result separated by data type, where each data type includes:
    • data: The returned values.
    • dim (List[Integer]): The dimension shape returned.
    • v (Integer): The vector shape of the data.
  • pipeline_name (String): The name of the pipeline.
  • shadow_data: Any shadow deployed data inferences in the same format as outputs.
  • time (Integer): The time since UNIX epoch.

We’ll repeat our process above - only this time through the Python requests library to our locally deployed pipeline.

def loadImageAndConvertTiffList(imagePath, width, height):
    img = cv2.imread(imagePath, 0)
    imgNorm = np.expand_dims(normalize(np.array(img), axis=1),2)
    imgNorm=imgNorm[:,:,0][:,:,None]
    imgNorm=np.expand_dims(imgNorm, 0)
    
    resizedImage = None
    #creates a dictionary with the wallaroo "tensor" key and the numpy ndim array representing image as the value.
    dictData = {"tensor":imgNorm.tolist()}
    dataframedata = pd.DataFrame(dictData)
    # display(dataframedata)
    return dataframedata, resizedImage
def run_semantic_segmentation_inference_requests(pipeline_url, input_tiff_image, width, height, threshold):
    
    tensor, resizedImage = loadImageAndConvertTiffList(input_tiff_image, width, height)
    # print(tensor)

    # #
    # # run inference on the 256x256 patch image get the predicted mitochondria mask
    # #

    # set the content type and accept headers
    headers = {
        'Content-Type': 'application/json; format=pandas-records'
    }

    data = tensor.to_json(orient="records")

    # print(data)

    # print(pipeline_url)

    response = requests.post(
                    pipeline_url, 
                    headers=headers, 
                    data=data, 
                    verify=True
                )

    # list1d = response.json()[0]['outputs'][0]['Float']['data']
    output = pd.DataFrame(response.json())
    # display(output)
    list1d = output.loc[0]["outputs"][0]['Float']['data']

    # output = pipeline.infer(tensor)
    # print(output)

    # # Obtain the flattened predicted mitochandria mask result
    # list1d = output.loc[0]["out.conv2d_37"]
    np1d = np.array(list1d)
    
    # # # unflatten it
    predicted_mask = np1d.reshape(1,width,height,1)
    
    # # # perform the element-wise comaprison operation using the threshold provided
    predicted_mask = (predicted_mask[0,:,:,0] > threshold).astype(np.uint8)
    
    # # return predicted_mask
    return predicted_mask
# set this to your deployed pipeline's URL

host = 'http://testboy.local:8080'

deployurl = f'{host}/infer'

for random_patch in random_patches:      

    # build the path to the image
    patch_image_path = sample_mitochondria_patches_path + "/images/" + random_patch['patch_image_file']

    # run inference in order to get the predicted 256x256 mask
    predicted_mask = run_semantic_segmentation_inference_requests(deployurl, patch_image_path, 256,256, 0.2)
    
    # # plot the results
    test_image = random_patch['patch_image'][:,:,0]
    test_image_title = f"Testing Image - {random_patch['index']}"

    ground_truth_image = random_patch['patch_mask'][:,:,0]
    ground_truth_image_title = "Ground Truth Mask"

    predicted_mask_title = 'Predicted Mask'

    tiff_utils.plot_test_results(test_image, test_image_title, \
                            ground_truth_image, ground_truth_image_title, \
                            predicted_mask, predicted_mask_title)