Deploy ONNX model to run in Python code
I’m trying to use the generated ONNX object detection model in my Python code. How can I make predictions on local images and display the predicted objects as box overlays?
My current code is as follows:
import numpy as np
import onnx
import onnxruntime as rt
from PIL import Image
import torchvision.transforms as transforms
# load & check model
model_name = '/content/gdrive/My Drive/Colab Notebooks/data/model2_1280x896.onnx'
onnx_model = onnx.load(model_name)
onnx.checker.check_model(onnx_model)
# pad image with margins
def add_margin(img: Image, top: int, right: int, bottom: int, left: int,
color: tuple[int,int,int] = (0, 0, 0)) -> Image:
width, height = img.size
new_width = width + right + left
new_height = height + top + bottom
result = Image.new(img.mode, (new_width, new_height), color)
result.paste(img, (left, top))
return result
# resize & pad image to fit model input size
def resize_image(img: Image, model_w: int, model_h: int) -> Image:
ratio = img.size[0] / img.size[1]
if img.size[0] != model_w:
img = img.resize((model_w, round(model_w / ratio)), Image.LANCZOS)
if img.size[1] > model_h:
img = img.resize((round(model_h * ratio), model_h), Image.LANCZOS)
ww = model_w - img.size[0]
hh = model_h - img.size[1]
return add_margin(img, hh//2, ww//2, hh//2, ww//2) if (ww > 0 or hh > 0) else img
# convert PIL image to tensor for model input
def image_to_tensor(img: Image):
preprocess = transforms.Compose([transforms.PILToTensor()])
img = preprocess(img)
img = img.unsqueeze(0) # add fake batch dimension
return img
# convert PIL image to Pytorch tensor
def to_numpy(tensor):
n_array = tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
return n_array.astype(np.float32)
# model expects inputs if this size
MODEL_SIZE = (1280, 896)
# open target image
img_path = '/content/gdrive/My Drive/Colab Notebooks/data/out31.png'
image = Image.open(img_path)
# preprocess image & convert to tensor
input_tensor = image_to_tensor(resize_image(image, *MODEL_SIZE))
# create ONNXRuntime predictor
EP_list = ['CUDAExecutionProvider', 'CPUExecutionProvider']
ort_session = rt.InferenceSession(model_name, providers=EP_list)
# make prediction on given tensor
np_image = to_numpy(input_tensor)
ort_inputs = {ort_session.get_inputs()[0].name: np_image}
ort_outs = ort_session.run(None, ort_inputs)
# print results
print(ort_outs)The last line produces results like this:
[array([[[ 9.15571289e+02, 2.85602264e+02, 9.59154602e+02,
3.36435181e+02, 3.54126662e-01],
[ 9.60446350e+02, 3.91394043e+02, 8.60601501e+02,
2.36534363e+02, 2.91460037e-01],
[ 9.13991089e+02, 2.77888947e+02, 9.63370667e+02,
3.38394043e+02, 2.80512393e-01],
...
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
0.00000000e+00, 0.00000000e+00]]], dtype=float32), array([[4, 9, 2, 4, 2, 9, 6, 9, 2, 4, 4, 2, 2, 2, 1, 9, 6, 1, 4, 6, 2, 9,
9, 6, 9, 6, 2, 1, 4, 2, 6, 6, 4, 4, 1, 6, 2, 6, 6, 6, 6, 2, 6, 4,
2, 8, 9, 9, 4, 6, 6, 9, 6, 2, 2, 6, 2, 4, 4, 4, 9, 5, 1, 7, 6, 6,
9, 6, 8, 6, 4, 6, 6, 4, 5, 2, 2, 6, 6, 6, 9, 6, 1, 5, 6, 6, 6, 9,
9, 1, 6, 6, 7, 6, 6, 2, 7, 9, 0]], dtype=int64)]If I understand correctly, the first array here is the bounding boxes of the detected objects and the last one must contain the list of the labels. The labels I can find in the `dm.json` file coming with the downloaded model zip file.
How would I use this result for prediction? And is there a description of the results output?