HimankJ commited on
Commit
9cef01c
·
verified ·
1 Parent(s): a3a180b

Added app.py and example images

Browse files
Files changed (11) hide show
  1. app.py.py +98 -0
  2. bird.jpg +0 -0
  3. car.jpg +0 -0
  4. cat.jpg +0 -0
  5. deer.jpg +0 -0
  6. dog.jpg +0 -0
  7. frog.jpg +0 -0
  8. horse.jpg +0 -0
  9. plane.jpg +0 -0
  10. ship.jpg +0 -0
  11. truck.jpg +0 -0
app.py.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """ERAV2-S13-Himank-Gradio.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1HJ6wO2_czxZrJwnyUkJ_XaS5HYUvooMS
8
+ """
9
+
10
+ import sys
11
+ sys.path.append(".")
12
+
13
+ import torch, torchvision
14
+ from torchvision import transforms
15
+ import numpy as np
16
+ import gradio as gr
17
+ from PIL import Image
18
+ from pytorch_grad_cam import GradCAM
19
+ from pytorch_grad_cam.utils.image import show_cam_on_image
20
+ from model import ResNet18
21
+
22
+ model = ResNet18()
23
+ model.load_state_dict(torch.load("model.pth", map_location=torch.device('cpu')), strict=False)
24
+
25
+ inv_normalize = transforms.Normalize(
26
+ mean=[-0.50/0.23, -0.50/0.23, -0.50/0.23],
27
+ std=[1/0.23, 1/0.23, 1/0.23]
28
+ )
29
+ classes = ('plane', 'car', 'bird', 'cat', 'deer',
30
+ 'dog', 'frog', 'horse', 'ship', 'truck')
31
+
32
+ def resize_image_pil(image, new_width, new_height):
33
+
34
+ img = Image.fromarray(np.array(image))
35
+ width, height = img.size
36
+
37
+ width_scale = new_width / width
38
+ height_scale = new_height / height
39
+ scale = min(width_scale, height_scale)
40
+ resized = img.resize((int(width*scale), int(height*scale)), Image.NEAREST)
41
+ resized = resized.crop((0, 0, new_width, new_height))
42
+
43
+ return resized
44
+
45
+ def inference(input_img,enable_grad_cam,transparency=0.5,target_layer_number=-1,num_top_classes=2):
46
+ input_img = resize_image_pil(input_img, 32, 32)
47
+
48
+ input_img = np.array(input_img)
49
+ org_img = input_img
50
+ input_img = input_img.reshape((32, 32, 3))
51
+ transform = transforms.ToTensor()
52
+ input_img = transform(input_img)
53
+ input_img = input_img
54
+ input_img = input_img.unsqueeze(0)
55
+ outputs = model(input_img)
56
+ softmax = torch.nn.Softmax(dim=0)
57
+ o = softmax(outputs.flatten())
58
+ confidences = {classes[i]: float(o[i]) for i in range(10)}
59
+ _, prediction = torch.max(outputs, 1)
60
+ target_layers = [model.layer2[target_layer_number]]
61
+ cam = GradCAM(model=model, target_layers=target_layers)
62
+ grayscale_cam = cam(input_tensor=input_img, targets=None)
63
+ grayscale_cam = grayscale_cam[0, :]
64
+ img = input_img.squeeze(0)
65
+ img = inv_normalize(img)
66
+ if enable_grad_cam:
67
+ visualization = show_cam_on_image(org_img/255, grayscale_cam, use_rgb=True, image_weight=transparency)
68
+ else:
69
+ visualization = None
70
+
71
+ confidences = sorted(confidences.items(), key=lambda x: x[1], reverse=True)
72
+ return classes[prediction[0].item()], visualization, dict(confidences[:num_top_classes])
73
+
74
+ title = "CIFAR10 trained on ResNet18 Model with GradCAM"
75
+ description = "A simple Gradio interface to infer on ResNet model, and get GradCAM results"
76
+ examples = [
77
+ ["cat.jpg", True, 0.5, -1, 2], ["dog.jpg", True, 0.5, -1, 3], ["bird.jpg", True, 0.5, -1, 4], ["car.jpg", False, 0.5, -1, 5], ["deer.jpg", True, 0.5, -1, 6],
78
+ ["frog.jpg", False, 0.5, -1, 7], ["horse.jpg", False, 0.45, -1, 8], ["plane.jpg", True, 0.30, -2, 9], ["ship.jpg", False, 0.25, -2, 10], ["truck.jpg", True ,0.75, -2, 1]
79
+ ]
80
+ demo = gr.Interface(
81
+ inference,
82
+ inputs = [
83
+ gr.Image(width=256, height=256, label="Input Image"),
84
+ gr.Checkbox(value=False, label="Enable grad-cam image"),
85
+ gr.Slider(0, 1, value = 0.5, label="Overall Opacity of Image"),
86
+ gr.Slider(-2, -1, value = -2, step=1, label="Select Layer"),
87
+ gr.Number(value=2, label="Number of Top Classes to Show", minimum=1, maximum=10),
88
+ ],
89
+ outputs = [
90
+ gr.Textbox(label="Predicted Category"),
91
+ gr.Image(width=256, height=256, label="Output"),
92
+ gr.Label()
93
+ ],
94
+ title = title,
95
+ description = description,
96
+ examples = examples,
97
+ )
98
+ demo.launch()
bird.jpg ADDED
car.jpg ADDED
cat.jpg ADDED
deer.jpg ADDED
dog.jpg ADDED
frog.jpg ADDED
horse.jpg ADDED
plane.jpg ADDED
ship.jpg ADDED
truck.jpg ADDED