CraigDroke commited on
Commit
5b73392
·
1 Parent(s): d5f61b2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -0
app.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torchvision
4
+ from torchvision import models, transforms, utils
5
+ from torch.autograd import Variable
6
+ import numpy as np
7
+ import matplotlib.pyplot as plt
8
+ #import scipy.misc
9
+ from PIL import Image
10
+ import json
11
+ import gradio as gr
12
+ import os
13
+
14
+ transform = transforms.Compose([
15
+ transforms.Resize((224, 224)),
16
+ transforms.ToTensor(),
17
+ transforms.Normalize(mean=0., std=1.)
18
+ ])
19
+
20
+ def generate_feature_maps(im):
21
+ image = Image.fromarray(im, 'RGB')
22
+ plt.imshow(image)
23
+
24
+ model = models.resnet18(pretrained=True)
25
+ print(model)
26
+
27
+ # we will save the conv layer weights in this list
28
+ model_weights =[]
29
+ #we will save the 49 conv layers in this list
30
+ conv_layers = []
31
+ # get all the model children as list
32
+ model_children = list(model.children())
33
+ #counter to keep count of the conv layers
34
+ counter = 0
35
+ #append all the conv layers and their respective wights to the list
36
+ for i in range(len(model_children)):
37
+ if type(model_children[i]) == nn.Conv2d:
38
+ counter+=1
39
+ model_weights.append(model_children[i].weight)
40
+ conv_layers.append(model_children[i])
41
+ elif type(model_children[i]) == nn.Sequential:
42
+ for j in range(len(model_children[i])):
43
+ for child in model_children[i][j].children():
44
+ if type(child) == nn.Conv2d:
45
+ counter+=1
46
+ model_weights.append(child.weight)
47
+ conv_layers.append(child)
48
+ print(f"Total convolution layers: {counter}")
49
+ print("conv_layers")
50
+
51
+ device = torch.device('cpu')
52
+ model = model.to(device)
53
+
54
+ image = transform(image)
55
+ print(f"Image shape before: {image.shape}")
56
+ image = image.unsqueeze(0)
57
+ print(f"Image shape after: {image.shape}")
58
+ image = image.to(device)
59
+
60
+ outputs = []
61
+ names = []
62
+ for layer in conv_layers[0:]:
63
+ image = layer(image)
64
+ outputs.append(image)
65
+ names.append(str(layer))
66
+ print(len(outputs))
67
+ #print feature_maps
68
+ for feature_map in outputs:
69
+ print(feature_map.shape)
70
+
71
+ processed = []
72
+ for feature_map in outputs:
73
+ feature_map = feature_map.squeeze(0)
74
+ gray_scale = torch.sum(feature_map,0)
75
+ gray_scale = gray_scale / feature_map.shape[0]
76
+ processed.append(gray_scale.data.cpu().numpy())
77
+ for fm in processed:
78
+ print(fm.shape)
79
+
80
+ # Plot and save feature maps for each layer
81
+ for i, (fm, name) in enumerate(zip(processed, names)):
82
+ fig = plt.figure(figsize=(10, 10))
83
+ a = fig.add_subplot(1, 1, 1) # You should adjust the layout as needed
84
+ imgplot = plt.imshow(fm, cmap='viridis') # Adjust the colormap if needed
85
+ a.axis("off")
86
+ filename = f'layor{i}.jpg'
87
+ plt.savefig('C:\\Users\\cdrok\\Documents\\JuniorClinic\\AiMl\\layors\\' + filename, bbox_inches='tight')
88
+ plt.close(fig) # Close the figure after saving
89
+
90
+ # Gradio interface
91
+ with gr.Blocks() as demo:
92
+
93
+ layorNumber = gr.Slider(0, 16, value=4, label="Layor Number", info="Choose between 0 and 16", step=1)
94
+
95
+ with gr.Row():
96
+ im = gr.Image()
97
+ im2 = gr.Image(type= 'filepath',)
98
+
99
+ def show_feature_maps(im, layorNumber):
100
+ # Future if check for if all layors exist to run faster
101
+ generate_feature_maps(im)
102
+ this_path = 'C:\\Users\\cdrok\\Documents\\JuniorClinic\\AiMl\\layors\\layor' + str(int(layorNumber)) + '.jpg'
103
+ return this_path
104
+
105
+ btn = gr.Button(value="Generate Feature Maps")
106
+ btn.click(show_feature_maps, inputs=[im, layorNumber], outputs=[im2])
107
+
108
+ if __name__ == "__main__":
109
+ demo.launch()