pytorch/HardNet
0
1import torch2from PIL import Image3from torchvision import transforms4import gradio as gr5import os6 7# Download ImageNet labels8os.system("wget https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt")9 10model = torch.hub.load('AK391/Pytorch-HarDNet', 'hardnet68', pretrained=True)11# or any of these variants12# model = torch.hub.load('PingoLH/Pytorch-HarDNet', 'hardnet85', pretrained=True)13# model = torch.hub.load('PingoLH/Pytorch-HarDNet', 'hardnet68ds', pretrained=True)14# model = torch.hub.load('PingoLH/Pytorch-HarDNet', 'hardnet39ds', pretrained=True)15model.eval()16torch.hub.download_url_to_file("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")17 18 19 20# sample execution (requires torchvision)21def inference(input_image):22 preprocess = transforms.Compose([23 transforms.Resize(256),24 transforms.CenterCrop(224),25 transforms.ToTensor(),26 transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),27 ])28 input_tensor = preprocess(input_image)29 input_batch = input_tensor.unsqueeze(0) # create a mini-batch as expected by the model30 31 # move the input and model to GPU for speed if available32 if torch.cuda.is_available():33 input_batch = input_batch.to('cuda')34 model.to('cuda')35 36 with torch.no_grad():37 output = model(input_batch)38 # The output has unnormalized scores. To get probabilities, you can run a softmax on it.39 probabilities = torch.nn.functional.softmax(output[0], dim=0)40 41 # Read the categories42 with open("imagenet_classes.txt", "r") as f:43 categories = [s.strip() for s in f.readlines()]44 # Show top categories per image45 top5_prob, top5_catid = torch.topk(probabilities, 5)46 result = {}47 for i in range(top5_prob.size(0)):48 result[categories[top5_catid[i]]] = top5_prob[i].item()49 return result50 51inputs = gr.inputs.Image(type='pil')52outputs = gr.outputs.Label(type="confidences",num_top_classes=5)53 54title = "HARDNET"55description = "Gradio demo for HARDNET, Harmonic DenseNet pre-trained on ImageNet. To use it, simply upload your image, or click one of the examples to load them. Read more at the links below."56article = "<p style='text-align: center'><a href='https://arxiv.org/abs/1909.00948'>HarDNet: A Low Memory Traffic Network</a> | <a href='https://github.com/PingoLH/Pytorch-HarDNet'>Github Repo</a></p>"57 58examples = [59 ['dog.jpg']60]61gr.Interface(inference, inputs, outputs, title=title, description=description, article=article, examples=examples, analytics_enabled=False).launch()