onnx/ShuffleNet_V1
0
1import onnx2import numpy as np3import onnxruntime as ort4from PIL import Image5import cv26import os7import gradio as gr8 9import mxnet10from mxnet.gluon.data.vision import transforms11 12os.system("wget https://s3.amazonaws.com/onnx-model-zoo/synset.txt")13 14 15with open('synset.txt', 'r') as f:16 labels = [l.rstrip() for l in f]17 18os.system("wget https://github.com/AK391/models/raw/main/vision/classification/shufflenet/model/shufflenet-9.onnx")19 20os.system("wget https://s3.amazonaws.com/model-server/inputs/kitten.jpg")21 22 23 24model_path = 'shufflenet-9.onnx'25model = onnx.load(model_path)26session = ort.InferenceSession(model.SerializeToString())27 28def get_image(path):29 with Image.open(path) as img:30 img = np.array(img.convert('RGB'))31 return img32 33 34def preprocess(img):35 '''36 Preprocessing required on the images for inference with mxnet gluon37 The function takes loaded image and returns processed tensor38 '''39 img = np.array(Image.fromarray(img).resize((224, 224))).astype(np.float32)40 img[:, :, 0] -= 123.6841 img[:, :, 1] -= 116.77942 img[:, :, 2] -= 103.93943 img[:,:,[0,1,2]] = img[:,:,[2,1,0]]44 img = img.transpose((2, 0, 1))45 img = np.expand_dims(img, axis=0)46 47 return img48 49def predict(path):50 img = get_image(path)51 img = preprocess(img)52 ort_inputs = {session.get_inputs()[0].name: img}53 preds = session.run(None, ort_inputs)[0]54 preds = np.squeeze(preds)55 a = np.argsort(preds)56 results = {}57 for i in a[0:5]: 58 results[labels[a[i]]] = float(preds[a[i]])59 return results60 61 62title="ShuffleNet-v1"63description="ShuffleNet is a deep convolutional network for image classification. ShuffleNetV2 is an improved architecture that is the state-of-the-art in terms of speed and accuracy tradeoff used for image classification."64 65examples=[['kitten.jpg']]66gr.Interface(predict,gr.inputs.Image(type='filepath'),"label",title=title,description=description,examples=examples).launch(enable_queue=True,debug=True)