DenseNet-121 / app.py
akhaliq's picture
akhaliq HF Staff
Update app.py
4866e2c
raw
history blame
1.76 kB
import onnx
import numpy as np
import onnxruntime as ort
from PIL import Image
import cv2
os.system("wget https://s3.amazonaws.com/onnx-model-zoo/synset.txt")
with open('synset.txt', 'r') as f:
labels = [l.rstrip() for l in f]
os.system("wget https://github.com/AK391/models/raw/main/vision/classification/densenet-121/model/densenet-9.onnx")
os.system("wget https://s3.amazonaws.com/model-server/inputs/kitten.jpg")
model_path = 'resnet50-v1-12.onnx'
model = onnx.load(model_path)
session = ort.InferenceSession(model.SerializeToString())
def get_image(path, show=False):
with Image.open(path) as img:
img = np.array(img.convert('RGB'))
if show:
plt.imshow(img)
plt.axis('off')
return img
def preprocess(img):
img = img / 255.
img = cv2.resize(img, (256, 256))
h, w = img.shape[0], img.shape[1]
y0 = (h - 224) // 2
x0 = (w - 224) // 2
img = img[y0 : y0+224, x0 : x0+224, :]
img = (img - [0.485, 0.456, 0.406]) / [0.229, 0.224, 0.225]
img = np.transpose(img, axes=[2, 0, 1])
img = img.astype(np.float32)
img = np.expand_dims(img, axis=0)
return img
def predict(path):
img = get_image(path, show=True)
img = preprocess(img)
ort_inputs = {session.get_inputs()[0].name: img}
preds = session.run(None, ort_inputs)[0]
preds = np.squeeze(preds)
a = np.argsort(preds)[::-1]
results = {}
results[labels[a[0]]] = preds[a[0]]
return results
title="DenseNet-121"
description="DenseNet-121 is a convolutional neural network for classification."
examples=[['apple.jpg']]
gr.Interface(predict,gr.inputs.Image(type='pil'),"label",title=title,description=description,examples=examples).launch(enable_queue=True,debug=True)