|
import numpy as np |
|
import tensorflow as tf |
|
from tensorflow import keras |
|
import matplotlib.cm as cm |
|
|
|
model = tf.keras.models.load_model('./EfficientNetB3') |
|
pred_model = tf.keras.models.load_model('./ConvNeXtTiny') |
|
|
|
|
|
def make_gradcam_heatmap(img_array, model, last_conv_layer_name, pred_index=None): |
|
|
|
|
|
grad_model = keras.models.Model( |
|
model.inputs, [model.get_layer(last_conv_layer_name).output, model.output] |
|
) |
|
|
|
|
|
|
|
with tf.GradientTape() as tape: |
|
last_conv_layer_output, preds = grad_model(img_array) |
|
if pred_index is None: |
|
pred_index = tf.argmax(preds[0]) |
|
class_channel = preds[:, pred_index] |
|
|
|
|
|
|
|
grads = tape.gradient(class_channel, last_conv_layer_output) |
|
|
|
|
|
|
|
pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2)) |
|
|
|
|
|
|
|
|
|
last_conv_layer_output = last_conv_layer_output[0] |
|
heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis] |
|
heatmap = tf.squeeze(heatmap) |
|
|
|
|
|
heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap) |
|
return heatmap.numpy() |
|
|
|
def gradio_img_array(img): |
|
|
|
|
|
|
|
array = keras.utils.img_to_array(img) |
|
|
|
|
|
array = np.expand_dims(array, axis=0) |
|
return array |
|
|
|
|
|
def gradio_display_gradcam(img_path, heatmap, cam_path="cam.jpg", alpha=0.4): |
|
|
|
|
|
img = keras.utils.img_to_array(img_path) |
|
|
|
|
|
heatmap = np.uint8(255 * heatmap) |
|
|
|
|
|
jet = cm.get_cmap("jet") |
|
|
|
|
|
jet_colors = jet(np.arange(256))[:, :3] |
|
jet_heatmap = jet_colors[heatmap] |
|
|
|
|
|
jet_heatmap = keras.utils.array_to_img(jet_heatmap) |
|
jet_heatmap = jet_heatmap.resize((img.shape[1], img.shape[0])) |
|
jet_heatmap = keras.utils.img_to_array(jet_heatmap) |
|
|
|
|
|
superimposed_img = jet_heatmap * alpha + img |
|
superimposed_img = keras.utils.array_to_img(superimposed_img) |
|
return superimposed_img |
|
|
|
import gradio as gr |
|
|
|
def test(img_path): |
|
|
|
img_array = tf.keras.applications.efficientnet.preprocess_input(gradio_img_array(img_path)) |
|
heatmap = make_gradcam_heatmap(img_array, model, "block7b_project_conv") |
|
img = gradio_display_gradcam(img_path, heatmap, cam_path="cam2.jpg") |
|
preds = pred_model.predict(img_array, verbose=0)[0] |
|
preds_dict = {"0": float(preds[0]), "1": float(preds[1]), "2": float(preds[2]), "3": float(preds[3]), "4": float(preds[4])} |
|
return img, preds_dict |
|
|
|
|
|
interf = gr.Interface(fn=test, inputs="image", outputs=["image", "label"]) |
|
|
|
interf.launch() |
|
|