hp733 commited on
Commit
f72975d
·
verified ·
1 Parent(s): d3f4433

Update gradcam_utils.py

Browse files
Files changed (1) hide show
  1. gradcam_utils.py +144 -71
gradcam_utils.py CHANGED
@@ -1,71 +1,144 @@
1
- import numpy as np
2
- import cv2
3
- import tensorflow as tf
4
- from tensorflow.keras.preprocessing.image import img_to_array, load_img
5
- import matplotlib.pyplot as plt
6
- from matplotlib.colors import LinearSegmentedColormap
7
-
8
- def preprocess_image(img_path, target_size):
9
- img = load_img(img_path, target_size=target_size)
10
- img = img_to_array(img)
11
- img = np.expand_dims(img, axis=0)
12
- img = img / 255.0 # Normalize
13
- return img
14
-
15
- def make_gradcam_heatmap(model, img_tensor, last_conv_layer_name, classifier_layer_names):
16
- grad_model = tf.keras.models.Model(
17
- [model.inputs], [model.get_layer(last_conv_layer_name).output, model.output]
18
- )
19
- with tf.GradientTape() as tape:
20
- conv_outputs, predictions = grad_model(img_tensor)
21
- loss = predictions[:, 1] # Targeting class 1 for pneumonia
22
-
23
- grads = tape.gradient(loss, conv_outputs)
24
- pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
25
-
26
- conv_outputs = conv_outputs[0]
27
- heatmap = conv_outputs @ pooled_grads[..., tf.newaxis]
28
- heatmap = tf.squeeze(heatmap)
29
- heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)
30
- heatmap = tf.where(tf.math.is_nan(heatmap), tf.zeros_like(heatmap), heatmap)
31
- return heatmap.numpy()
32
-
33
- def create_custom_colormap():
34
- colors = ['blue', 'green', 'yellow', 'red']
35
- n_bins = 256
36
- cmap = LinearSegmentedColormap.from_list('custom', colors, N=n_bins)
37
- return cmap
38
-
39
- def apply_custom_colormap(heatmap, cmap):
40
- colored_heatmap = cmap(heatmap)
41
- colored_heatmap = np.uint8(colored_heatmap * 255)
42
- return colored_heatmap
43
-
44
- def enhance_heatmap(heatmap, gamma=0.7, percentile=99):
45
- heatmap = np.power(heatmap, gamma)
46
- heatmap = heatmap / np.percentile(heatmap, percentile)
47
- heatmap = np.clip(heatmap, 0, 1)
48
- return heatmap
49
-
50
- def generate_and_merge_heatmaps(img_path, vgg_model, efficientnet_model, densenet_model, img_size=(224, 224), output_size=(5, 5)):
51
- img_tensor = preprocess_image(img_path, img_size)
52
-
53
- vgg_heatmap = make_gradcam_heatmap(vgg_model, img_tensor, 'block5_conv4', ['flatten', 'dense'])
54
- efficientnet_heatmap = make_gradcam_heatmap(efficientnet_model, img_tensor, 'top_conv', ['flatten', 'dense'])
55
- densenet_heatmap = make_gradcam_heatmap(densenet_model, img_tensor, 'conv5_block16_concat', ['flatten', 'dense'])
56
-
57
- vgg_heatmap_resized = cv2.resize(vgg_heatmap, img_size)
58
- efficientnet_heatmap_resized = cv2.resize(efficientnet_heatmap, img_size)
59
- densenet_heatmap_resized = cv2.resize(densenet_heatmap, img_size)
60
-
61
- merged_heatmap = (vgg_heatmap_resized + efficientnet_heatmap_resized + densenet_heatmap_resized) / 3.0
62
- enhanced_heatmap = enhance_heatmap(merged_heatmap)
63
- custom_cmap = create_custom_colormap()
64
- colored_heatmap = apply_custom_colormap(enhanced_heatmap, custom_cmap)
65
-
66
- img = cv2.imread(img_path)
67
- img = cv2.resize(img, img_size)
68
- img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
69
-
70
- superimposed_img = cv2.addWeighted(img, 0.6, colored_heatmap[:, :, :3], 0.4, 0)
71
- return superimposed_img
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import numpy as np
2
+ # import cv2
3
+ # import tensorflow as tf
4
+ # from tensorflow.keras.preprocessing.image import img_to_array, load_img
5
+ # import matplotlib.pyplot as plt
6
+ # from matplotlib.colors import LinearSegmentedColormap
7
+
8
+ # def preprocess_image(img_path, target_size):
9
+ # img = load_img(img_path, target_size=target_size)
10
+ # img = img_to_array(img)
11
+ # img = np.expand_dims(img, axis=0)
12
+ # img = img / 255.0 # Normalize
13
+ # return img
14
+
15
+ # def make_gradcam_heatmap(model, img_tensor, last_conv_layer_name, classifier_layer_names):
16
+ # grad_model = tf.keras.models.Model(
17
+ # [model.inputs], [model.get_layer(last_conv_layer_name).output, model.output]
18
+ # )
19
+ # with tf.GradientTape() as tape:
20
+ # conv_outputs, predictions = grad_model(img_tensor)
21
+ # loss = predictions[:, 1] # Targeting class 1 for pneumonia
22
+
23
+ # grads = tape.gradient(loss, conv_outputs)
24
+ # pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
25
+
26
+ # conv_outputs = conv_outputs[0]
27
+ # heatmap = conv_outputs @ pooled_grads[..., tf.newaxis]
28
+ # heatmap = tf.squeeze(heatmap)
29
+ # heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)
30
+ # heatmap = tf.where(tf.math.is_nan(heatmap), tf.zeros_like(heatmap), heatmap)
31
+ # return heatmap.numpy()
32
+
33
+ # def create_custom_colormap():
34
+ # colors = ['blue', 'green', 'yellow', 'red']
35
+ # n_bins = 256
36
+ # cmap = LinearSegmentedColormap.from_list('custom', colors, N=n_bins)
37
+ # return cmap
38
+
39
+ # def apply_custom_colormap(heatmap, cmap):
40
+ # colored_heatmap = cmap(heatmap)
41
+ # colored_heatmap = np.uint8(colored_heatmap * 255)
42
+ # return colored_heatmap
43
+
44
+ # def enhance_heatmap(heatmap, gamma=0.7, percentile=99):
45
+ # heatmap = np.power(heatmap, gamma)
46
+ # heatmap = heatmap / np.percentile(heatmap, percentile)
47
+ # heatmap = np.clip(heatmap, 0, 1)
48
+ # return heatmap
49
+
50
+ # def generate_and_merge_heatmaps(img_path, vgg_model, efficientnet_model, densenet_model, img_size=(224, 224), output_size=(5, 5)):
51
+ # img_tensor = preprocess_image(img_path, img_size)
52
+
53
+ # vgg_heatmap = make_gradcam_heatmap(vgg_model, img_tensor, 'block5_conv4', ['flatten', 'dense'])
54
+ # efficientnet_heatmap = make_gradcam_heatmap(efficientnet_model, img_tensor, 'top_conv', ['flatten', 'dense'])
55
+ # densenet_heatmap = make_gradcam_heatmap(densenet_model, img_tensor, 'conv5_block16_concat', ['flatten', 'dense'])
56
+
57
+ # vgg_heatmap_resized = cv2.resize(vgg_heatmap, img_size)
58
+ # efficientnet_heatmap_resized = cv2.resize(efficientnet_heatmap, img_size)
59
+ # densenet_heatmap_resized = cv2.resize(densenet_heatmap, img_size)
60
+
61
+ # merged_heatmap = (vgg_heatmap_resized + efficientnet_heatmap_resized + densenet_heatmap_resized) / 3.0
62
+ # enhanced_heatmap = enhance_heatmap(merged_heatmap)
63
+ # custom_cmap = create_custom_colormap()
64
+ # colored_heatmap = apply_custom_colormap(enhanced_heatmap, custom_cmap)
65
+
66
+ # img = cv2.imread(img_path)
67
+ # img = cv2.resize(img, img_size)
68
+ # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
69
+
70
+ # superimposed_img = cv2.addWeighted(img, 0.6, colored_heatmap[:, :, :3], 0.4, 0)
71
+ # return superimposed_img
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+ import numpy as np
81
+ import cv2
82
+ import tensorflow as tf
83
+ from tensorflow.keras.preprocessing.image import img_to_array, load_img
84
+ from matplotlib.colors import LinearSegmentedColormap
85
+
86
+ def preprocess_image(img_path, target_size):
87
+ img = load_img(img_path, target_size=target_size)
88
+ img = img_to_array(img)
89
+ img = np.expand_dims(img, axis=0)
90
+ img = img / 255.0
91
+ return img
92
+
93
+ def make_gradcam_heatmap(model, img_tensor):
94
+ grad_model = tf.keras.models.Model([model.input], [model.output])
95
+
96
+ with tf.GradientTape() as tape:
97
+ conv_outputs = model(img_tensor)
98
+ loss = conv_outputs[:, 1] # class index 1 = pneumonia
99
+
100
+ grads = tape.gradient(loss, conv_outputs)
101
+ pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
102
+
103
+ conv_outputs = conv_outputs[0]
104
+ heatmap = conv_outputs @ pooled_grads[..., tf.newaxis]
105
+ heatmap = tf.squeeze(heatmap)
106
+ heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)
107
+ heatmap = tf.where(tf.math.is_nan(heatmap), tf.zeros_like(heatmap), heatmap)
108
+ return heatmap.numpy()
109
+
110
+ def create_custom_colormap():
111
+ colors = ['blue', 'green', 'yellow', 'red']
112
+ cmap = LinearSegmentedColormap.from_list('custom', colors, N=256)
113
+ return cmap
114
+
115
+ def apply_custom_colormap(heatmap, cmap):
116
+ colored_heatmap = cmap(heatmap)
117
+ return np.uint8(colored_heatmap * 255)
118
+
119
+ def enhance_heatmap(heatmap, gamma=0.7, percentile=99):
120
+ heatmap = np.power(heatmap, gamma)
121
+ heatmap = heatmap / np.percentile(heatmap, percentile)
122
+ return np.clip(heatmap, 0, 1)
123
+
124
+ def generate_and_merge_heatmaps(img_path, vgg_model, efficientnet_model, densenet_model, img_size=(224, 224)):
125
+ img_tensor = preprocess_image(img_path, img_size)
126
+
127
+ vgg_heatmap = make_gradcam_heatmap(vgg_model, img_tensor)
128
+ efficientnet_heatmap = make_gradcam_heatmap(efficientnet_model, img_tensor)
129
+ densenet_heatmap = make_gradcam_heatmap(densenet_model, img_tensor)
130
+
131
+ vgg_heatmap = cv2.resize(vgg_heatmap, img_size)
132
+ efficientnet_heatmap = cv2.resize(efficientnet_heatmap, img_size)
133
+ densenet_heatmap = cv2.resize(densenet_heatmap, img_size)
134
+
135
+ merged = (vgg_heatmap + efficientnet_heatmap + densenet_heatmap) / 3.0
136
+ enhanced = enhance_heatmap(merged)
137
+ colored = apply_custom_colormap(enhanced, create_custom_colormap())
138
+
139
+ original = cv2.imread(img_path)
140
+ original = cv2.resize(original, img_size)
141
+ original = cv2.cvtColor(original, cv2.COLOR_BGR2RGB)
142
+
143
+ superimposed_img = cv2.addWeighted(original, 0.6, colored[:, :, :3], 0.4, 0)
144
+ return superimposed_img