Zeyadd-Mostaffa commited on
Commit
0786c74
·
verified ·
1 Parent(s): e73e2a2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -17
app.py CHANGED
@@ -29,33 +29,49 @@ def extract_face(image):
29
  x, y = max(0, x), max(0, y)
30
  return image[y:y+h, x:x+w]
31
 
32
- def grad_cam(model, image, size, preprocess_fn):
33
- img = cv2.resize(image, size)
34
- input_tensor = preprocess_fn(img.astype(np.float32))[np.newaxis, ...]
35
-
 
 
 
 
 
 
 
 
 
36
  grad_model = tf.keras.models.Model(
37
- [model.inputs], [model.get_layer(index=-1).output, model.output]
38
  )
39
 
40
  with tf.GradientTape() as tape:
41
- conv_outputs, predictions = grad_model(input_tensor)
42
  loss = predictions[:, 0] # Assuming binary classification
43
 
44
- grads = tape.gradient(loss, conv_outputs)[0]
45
- conv_outputs = conv_outputs[0]
 
 
 
46
 
47
- weights = tf.reduce_mean(grads, axis=(0, 1))
48
- cam = np.zeros(conv_outputs.shape[:2], dtype=np.float32)
49
- for i, w in enumerate(weights):
50
- cam += w * conv_outputs[:, :, i]
51
 
52
- cam = np.maximum(cam, 0)
53
- cam = cam / (cam.max() + 1e-8)
54
- heatmap = cv2.resize(cam, size)
55
  heatmap = np.uint8(255 * heatmap)
56
  heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
57
- superimposed_img = cv2.addWeighted(cv2.resize(img, size), 0.6, heatmap, 0.4, 0)
58
- return superimposed_img
 
 
 
 
 
59
 
60
  def predict(image):
61
  face = extract_face(image)
 
29
  x, y = max(0, x), max(0, y)
30
  return image[y:y+h, x:x+w]
31
 
32
+ def grad_cam(model, image, size, preprocess):
33
+ img_input = tf.expand_dims(image, axis=0) # Shape: (1, H, W, 3)
34
+
35
+ last_conv_layer_name = None
36
+ # Auto-detect last conv layer
37
+ for layer in reversed(model.layers):
38
+ if isinstance(layer, tf.keras.layers.Conv2D):
39
+ last_conv_layer_name = layer.name
40
+ break
41
+
42
+ if not last_conv_layer_name:
43
+ raise ValueError("No Conv2D layer found in the model.")
44
+
45
  grad_model = tf.keras.models.Model(
46
+ [model.inputs], [model.get_layer(last_conv_layer_name).output, model.output]
47
  )
48
 
49
  with tf.GradientTape() as tape:
50
+ conv_outputs, predictions = grad_model(img_input)
51
  loss = predictions[:, 0] # Assuming binary classification
52
 
53
+ grads = tape.gradient(loss, conv_outputs)
54
+
55
+ # Ensure correct shape
56
+ if len(grads.shape) != 4:
57
+ raise ValueError(f"Expected 4D tensor for grads, got shape: {grads.shape}")
58
 
59
+ pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2)) # (C,)
60
+ conv_outputs = conv_outputs[0] # (H, W, C)
61
+ cam = tf.reduce_sum(conv_outputs * pooled_grads, axis=-1)
 
62
 
63
+ heatmap = np.maximum(cam, 0)
64
+ heatmap = heatmap / (tf.reduce_max(heatmap) + 1e-6)
65
+ heatmap = cv2.resize(heatmap.numpy(), size)
66
  heatmap = np.uint8(255 * heatmap)
67
  heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
68
+
69
+ face_rgb = (image.numpy() * 255).astype(np.uint8)
70
+ face_rgb = cv2.resize(face_rgb, size)
71
+
72
+ overlaid = cv2.addWeighted(face_rgb, 0.6, heatmap, 0.4, 0)
73
+ return overlaid
74
+
75
 
76
  def predict(image):
77
  face = extract_face(image)