taesiri commited on
Commit
c6252e6
1 Parent(s): c9e954c

gradio plot

Browse files
Files changed (1) hide show
  1. app.py +88 -67
app.py CHANGED
@@ -10,89 +10,110 @@ import gradio as gr
10
 
11
 
12
  def compute_spatial_similarity(conv1, conv2):
13
- """
14
- Takes in the last convolutional layer from two images, computes the pooled output
15
- feature, and then generates the spatial similarity map for both images.
16
- """
17
- conv1 = conv1.reshape(-1, 7*7).T
18
- conv2 = conv2.reshape(-1, 7*7).T
19
-
20
- pool1 = np.mean(conv1, axis=0)
21
- pool2 = np.mean(conv2, axis=0)
22
- out_sz = (int(np.sqrt(conv1.shape[0])),int(np.sqrt(conv1.shape[0])))
23
- conv1_normed = conv1 / np.linalg.norm(pool1) / conv1.shape[0]
24
- conv2_normed = conv2 / np.linalg.norm(pool2) / conv2.shape[0]
25
- im_similarity = np.zeros((conv1_normed.shape[0], conv1_normed.shape[0]))
26
-
27
- for zz in range(conv1_normed.shape[0]):
28
- repPx = mb.repmat(conv1_normed[zz,:],conv1_normed.shape[0],1)
29
- im_similarity[zz,:] = np.multiply(repPx,conv2_normed).sum(axis=1)
30
- similarity1 = np.reshape(np.sum(im_similarity,axis=1),out_sz)
31
- similarity2 = np.reshape(np.sum(im_similarity,axis=0),out_sz)
32
- return similarity1, similarity2
 
33
 
34
  # Get Layer 4
35
 
36
- display_transform = transforms.Compose([transforms.Resize(256), transforms.CenterCrop((224, 224))])
 
 
37
 
38
  imagenet_transform = transforms.Compose(
39
- [transforms.Resize(256),
40
- transforms.CenterCrop((224, 224)),
41
- transforms.ToTensor(),
42
- transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
 
 
 
43
 
44
 
45
  class Wrapper(torch.nn.Module):
46
- def __init__(self, model):
47
- super(Wrapper, self).__init__()
48
- self.model = model
49
- self.layer4_ouputs = None
50
- def fw_hook(module, input, output):
51
- self.layer4_ouputs = output
52
- self.model.layer4.register_forward_hook(fw_hook)
53
-
54
- def forward(self, input):
55
- _ = self.model(input)
56
- return self.layer4_ouputs
57
-
58
- def __repr__(self):
59
- return "Wrapper"
60
-
 
 
 
61
  def get_layer4(input_image):
62
- l4_model = models.resnet50(pretrained=True)
63
- # l4_model = l4_model.cuda()
64
- l4_model.eval();
65
- wrapped_model = Wrapper(l4_model)
66
 
67
- with torch.no_grad():
68
- data = imagenet_transform(input_image).unsqueeze(0)
69
- # data = data.cuda()
70
- reference_layer4 = wrapped_model(data)
 
 
71
 
72
- return reference_layer4.data.to('cpu').numpy()
73
 
74
  # Visualization
75
  def visualize_similarities(image1, image2):
76
- a = get_layer4(image1).squeeze()
77
- b = get_layer4(image2).squeeze()
78
- sim1, sim2 = compute_spatial_similarity(a, b)
 
 
 
 
 
 
 
79
 
80
- fig, axes = plt.subplots(1, 2, figsize=(12, 5))
81
- axes[0].imshow(display_transform(image1))
82
- im1=axes[0].imshow(skimage.transform.resize(sim1, (224, 224)), alpha=0.6, cmap='jet')
83
- # axes[0].colorbar()
 
84
 
85
- axes[1].imshow(display_transform(image2))
86
- im2=axes[1].imshow(skimage.transform.resize(sim2, (224, 224)), alpha=0.6, cmap='jet')
87
- # axes[1].colorbar()
 
88
 
89
- fig.colorbar(im1, ax=axes[0])
90
- fig.colorbar(im2, ax=axes[1])
91
- plt.tight_layout()
92
- return fig
93
 
94
  # GRADIO APP
95
- iface = gr.Interface(fn=visualize_similarities,
96
- inputs=[gr.inputs.Image(shape=(300, 300), type='pil'),
97
- gr.inputs.Image(shape=(300, 300), type='pil')], outputs="plot")
98
- iface.launch()
 
 
 
 
 
 
10
 
11
 
12
  def compute_spatial_similarity(conv1, conv2):
13
+ """
14
+ Takes in the last convolutional layer from two images, computes the pooled output
15
+ feature, and then generates the spatial similarity map for both images.
16
+ """
17
+ conv1 = conv1.reshape(-1, 7 * 7).T
18
+ conv2 = conv2.reshape(-1, 7 * 7).T
19
+
20
+ pool1 = np.mean(conv1, axis=0)
21
+ pool2 = np.mean(conv2, axis=0)
22
+ out_sz = (int(np.sqrt(conv1.shape[0])), int(np.sqrt(conv1.shape[0])))
23
+ conv1_normed = conv1 / np.linalg.norm(pool1) / conv1.shape[0]
24
+ conv2_normed = conv2 / np.linalg.norm(pool2) / conv2.shape[0]
25
+ im_similarity = np.zeros((conv1_normed.shape[0], conv1_normed.shape[0]))
26
+
27
+ for zz in range(conv1_normed.shape[0]):
28
+ repPx = mb.repmat(conv1_normed[zz, :], conv1_normed.shape[0], 1)
29
+ im_similarity[zz, :] = np.multiply(repPx, conv2_normed).sum(axis=1)
30
+ similarity1 = np.reshape(np.sum(im_similarity, axis=1), out_sz)
31
+ similarity2 = np.reshape(np.sum(im_similarity, axis=0), out_sz)
32
+ return similarity1, similarity2
33
+
34
 
35
  # Get Layer 4
36
 
37
+ display_transform = transforms.Compose(
38
+ [transforms.Resize(256), transforms.CenterCrop((224, 224))]
39
+ )
40
 
41
  imagenet_transform = transforms.Compose(
42
+ [
43
+ transforms.Resize(256),
44
+ transforms.CenterCrop((224, 224)),
45
+ transforms.ToTensor(),
46
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
47
+ ]
48
+ )
49
 
50
 
51
  class Wrapper(torch.nn.Module):
52
+ def __init__(self, model):
53
+ super(Wrapper, self).__init__()
54
+ self.model = model
55
+ self.layer4_ouputs = None
56
+
57
+ def fw_hook(module, input, output):
58
+ self.layer4_ouputs = output
59
+
60
+ self.model.layer4.register_forward_hook(fw_hook)
61
+
62
+ def forward(self, input):
63
+ _ = self.model(input)
64
+ return self.layer4_ouputs
65
+
66
+ def __repr__(self):
67
+ return "Wrapper"
68
+
69
+
70
  def get_layer4(input_image):
71
+ l4_model = models.resnet50(pretrained=True)
72
+ # l4_model = l4_model.cuda()
73
+ l4_model.eval()
74
+ wrapped_model = Wrapper(l4_model)
75
 
76
+ with torch.no_grad():
77
+ data = imagenet_transform(input_image).unsqueeze(0)
78
+ # data = data.cuda()
79
+ reference_layer4 = wrapped_model(data)
80
+
81
+ return reference_layer4.data.to("cpu").numpy()
82
 
 
83
 
84
  # Visualization
85
  def visualize_similarities(image1, image2):
86
+ a = get_layer4(image1).squeeze()
87
+ b = get_layer4(image2).squeeze()
88
+ sim1, sim2 = compute_spatial_similarity(a, b)
89
+
90
+ fig, axes = plt.subplots(1, 2, figsize=(12, 5))
91
+ axes[0].imshow(display_transform(image1))
92
+ im1 = axes[0].imshow(
93
+ skimage.transform.resize(sim1, (224, 224)), alpha=0.6, cmap="jet"
94
+ )
95
+ # axes[0].colorbar()
96
 
97
+ axes[1].imshow(display_transform(image2))
98
+ im2 = axes[1].imshow(
99
+ skimage.transform.resize(sim2, (224, 224)), alpha=0.6, cmap="jet"
100
+ )
101
+ # axes[1].colorbar()
102
 
103
+ fig.colorbar(im1, ax=axes[0])
104
+ fig.colorbar(im2, ax=axes[1])
105
+ plt.tight_layout()
106
+ return fig
107
 
 
 
 
 
108
 
109
  # GRADIO APP
110
+ iface = gr.Interface(
111
+ fn=visualize_similarities,
112
+ inputs=[
113
+ gr.inputs.Image(shape=(300, 300), type="pil"),
114
+ gr.inputs.Image(shape=(300, 300), type="pil"),
115
+ ],
116
+ outputs=[gr.outputs.Plot(type="matplotlib")],
117
+ )
118
+
119
+ iface.launch()