Zeyadd-Mostaffa commited on
Commit
87d09d2
·
verified ·
1 Parent(s): eb801fa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +10 -7
app.py CHANGED
@@ -39,23 +39,26 @@ def grad_cam(model, img, size, preprocess_func):
39
  conv_outputs, predictions = grad_model(x_tensor)
40
  loss = predictions[:, 0]
41
  grads = tape.gradient(loss, conv_outputs)
42
- cam = tf.reduce_mean(grads, axis=-1).numpy()
43
- cam = np.squeeze(cam)
44
 
45
- cam = np.maximum(cam, 0)
46
- cam = cam / cam.max() if cam.max() != 0 else cam
47
- heatmap = cv2.resize(cam, size)
48
- heatmap = np.uint8(255 * heatmap)
 
 
 
49
  heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
50
 
51
  img_np = np.array(img_resized)
52
- if img_np.shape[-1] == 4:
53
  img_np = img_np[:, :, :3]
 
54
  superimposed = cv2.addWeighted(img_np, 0.6, heatmap, 0.4, 0)
55
  return Image.fromarray(cv2.cvtColor(superimposed, cv2.COLOR_BGR2RGB))
56
 
57
 
58
 
 
59
  # Preprocessing helper
60
  def preprocess(img, size, func):
61
  img = img.resize(size)
 
39
  conv_outputs, predictions = grad_model(x_tensor)
40
  loss = predictions[:, 0]
41
  grads = tape.gradient(loss, conv_outputs)
 
 
42
 
43
+ cam = tf.reduce_mean(grads, axis=-1)[0] # (H, W)
44
+ cam = tf.maximum(cam, 0)
45
+ cam = cam / tf.reduce_max(cam + tf.keras.backend.epsilon())
46
+ cam = cam.numpy() # convert to numpy before resizing
47
+
48
+ cam = cv2.resize(cam, size)
49
+ heatmap = np.uint8(255 * cam)
50
  heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
51
 
52
  img_np = np.array(img_resized)
53
+ if img_np.shape[-1] == 4: # remove alpha if present
54
  img_np = img_np[:, :, :3]
55
+
56
  superimposed = cv2.addWeighted(img_np, 0.6, heatmap, 0.4, 0)
57
  return Image.fromarray(cv2.cvtColor(superimposed, cv2.COLOR_BGR2RGB))
58
 
59
 
60
 
61
+
62
  # Preprocessing helper
63
  def preprocess(img, size, func):
64
  img = img.resize(size)