balajib197 commited on
Commit
2581e2d
1 Parent(s): e8111f3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -0
app.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch, torchvision
2
+ from torchvision import transforms
3
+ import numpy as np
4
+ import gradio as gr
5
+ from PIL import Image
6
+ from pytorch_grad_cam import GradCAM
7
+ from pytorch_grad_cam.utils.image import show_cam_on_image
8
+ from resnet import LitResnet, BasicBlock
9
+ import gradio as gr
10
+ import matplotlib.pyplot as plt
11
+
12
+ model = LitResnet(BasicBlock, [2, 2, 2, 2], lr=0.05)
13
+ model = LitResnet.load_from_checkpoint("model_60.ckpt")
14
+
15
+ inv_normalize = transforms.Normalize(
16
+ mean=[-0.50/0.23, -0.50/0.23, -0.50/0.23],
17
+ std=[1/0.23, 1/0.23, 1/0.23]
18
+ )
19
+ classes = ('plane', 'car', 'bird', 'cat', 'deer',
20
+ 'dog', 'frog', 'horse', 'ship', 'truck')
21
+
22
+ def resize_image_pil(image, new_width, new_height):
23
+
24
+ # Convert to PIL image
25
+ img = Image.fromarray(np.array(image))
26
+
27
+ # Get original size
28
+ width, height = img.size
29
+
30
+ # Calculate scale
31
+ width_scale = new_width / width
32
+ height_scale = new_height / height
33
+ scale = min(width_scale, height_scale)
34
+
35
+ # Resize
36
+ resized = img.resize((int(width*scale), int(height*scale)), Image.NEAREST)
37
+
38
+ # Crop to exact size
39
+ resized = resized.crop((0, 0, new_width, new_height))
40
+
41
+ return resized
42
+
43
+ def inference(input_img, gradcam_res, top_res, transparency = 0.5, target_layer_number = -1):
44
+ input_img = resize_image_pil(input_img, 32, 32)
45
+
46
+ input_img = np.array(input_img)
47
+ org_img = input_img
48
+ input_img = input_img.reshape((32, 32, 3))
49
+ transform = transforms.ToTensor()
50
+ input_img = transform(input_img)
51
+ input_img = input_img
52
+ input_img = input_img.unsqueeze(0)
53
+ outputs = model(input_img)
54
+ softmax = torch.nn.Softmax(dim=0)
55
+ o = softmax(outputs.flatten())
56
+ confidences = {classes[i]: float(o[i]) for i in range(10)}
57
+ _, prediction = torch.max(outputs, 1)
58
+ target_layers = [model.layer2[target_layer_number]]
59
+ cam = GradCAM(model=model, target_layers=target_layers)
60
+ grayscale_cam = cam(input_tensor=input_img, targets=None)
61
+ grayscale_cam = grayscale_cam[0, :]
62
+
63
+ if gradcam_res:
64
+ visualization = show_cam_on_image(org_img/255, grayscale_cam, use_rgb=True, image_weight=transparency)
65
+ else:
66
+ visualization = org_img
67
+
68
+ confidences_sorted = sorted(confidences.items(), key=lambda x: x[1], reverse=True)
69
+ conf = dict(confidences_sorted[:])
70
+ confidences_filter = {k: conf[k] for k in list(conf)[:top_res]}
71
+
72
+ return classes[prediction[0].item()], visualization, confidences_filter
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 = [["image_01.jpg", True, 3, 0.5, -1], ["image_06.jpg", False, 4, 0.5, -1],
77
+ ["image_02.jpg", True, 5, 0.5, -1], ["image_07.jpg", False,6, 0.65, -1],
78
+ ["image_03.jpg", True, 7, 0.5, -1], ["image_08.jpg", False,8, 0.5, -1],
79
+ ["image_04.jpg", True,3, 0.5, -1], ["image_09.jpg", False,5, 0.5, -1],
80
+ ["image_05.jpg", True,6, 0.77, -1], ["image_10.jpg", False,7, 0.5, -1]]
81
+ demo = gr.Interface(
82
+ inference,
83
+ inputs = [
84
+ gr.Image(width=256, height=256, label="Input Image"),
85
+ gr.Checkbox(label="GradCam", info="Check gradcam result?"),
86
+ gr.Slider(1, 10, value = 3, step=1, label="select number of top predcitions"),
87
+ gr.Slider(0, 1, value = 0.5, label="Overall Opacity of Image"),
88
+ gr.Slider(-2, -1, value = -2, step=1, label="Which Layer?")
89
+ ],
90
+ outputs = [
91
+ "text",
92
+ gr.Image(width=256, height=256, label="Output"),
93
+ gr.Label()
94
+ ],
95
+ title = title,
96
+ description = description,
97
+ examples = examples,
98
+ )
99
+ demo.launch()