|
| 1 | +import cv2 |
| 2 | +import numpy as np |
| 3 | +import os |
| 4 | +import pandas as pd |
| 5 | +from configparser import ConfigParser |
| 6 | +from generator import AugmentedImageSequence |
| 7 | +from models.keras import ModelFactory |
| 8 | +from keras import backend as kb |
| 9 | + |
| 10 | + |
| 11 | +def get_output_layer(model, layer_name): |
| 12 | + # get the symbolic outputs of each "key" layer (we gave them unique names). |
| 13 | + layer_dict = dict([(layer.name, layer) for layer in model.layers]) |
| 14 | + layer = layer_dict[layer_name] |
| 15 | + return layer |
| 16 | + |
| 17 | + |
| 18 | +def create_cam(df_g, output_dir, image_source_dir, model, generator, class_names): |
| 19 | + """ |
| 20 | + Create a CAM overlay image for the input image |
| 21 | +
|
| 22 | + :param df_g: pandas.DataFrame, bboxes on the same image |
| 23 | + :param output_dir: str |
| 24 | + :param image_source_dir: str |
| 25 | + :param model: keras model |
| 26 | + :param generator: generator.AugmentedImageSequence |
| 27 | + :param class_names: list of str |
| 28 | + """ |
| 29 | + file_name = df_g["file_name"] |
| 30 | + print(f"process image: {file_name}") |
| 31 | + |
| 32 | + # draw bbox with labels |
| 33 | + img_ori = cv2.imread(filename=os.path.join(image_source_dir, file_name)) |
| 34 | + |
| 35 | + label = df_g["label"] |
| 36 | + if label == "Infiltrate": |
| 37 | + label = "Infiltration" |
| 38 | + index = class_names.index(label) |
| 39 | + |
| 40 | + output_path = os.path.join(output_dir, f"{label}.{file_name}") |
| 41 | + |
| 42 | + img_transformed = generator.load_image(file_name) |
| 43 | + |
| 44 | + # CAM overlay |
| 45 | + # Get the 512 input weights to the softmax. |
| 46 | + class_weights = model.layers[-1].get_weights()[0] |
| 47 | + final_conv_layer = get_output_layer(model, "bn") |
| 48 | + get_output = kb.function([model.layers[0].input], [final_conv_layer.output, model.layers[-1].output]) |
| 49 | + [conv_outputs, predictions] = get_output([np.array([img_transformed])]) |
| 50 | + conv_outputs = conv_outputs[0, :, :, :] |
| 51 | + |
| 52 | + # Create the class activation map. |
| 53 | + cam = np.zeros(dtype=np.float32, shape=(conv_outputs.shape[:2])) |
| 54 | + for i, w in enumerate(class_weights[index]): |
| 55 | + cam += w * conv_outputs[:, :, i] |
| 56 | + # print(f"predictions: {predictions}") |
| 57 | + cam /= np.max(cam) |
| 58 | + cam = cv2.resize(cam, img_ori.shape[:2]) |
| 59 | + heatmap = cv2.applyColorMap(np.uint8(255 * cam), cv2.COLORMAP_JET) |
| 60 | + heatmap[np.where(cam < 0.2)] = 0 |
| 61 | + img = heatmap * 0.5 + img_ori |
| 62 | + |
| 63 | + # add label & rectangle |
| 64 | + # ratio = output dimension / 1024 |
| 65 | + ratio = 1 |
| 66 | + x1 = int(df_g["x"] * ratio) |
| 67 | + y1 = int(df_g["y"] * ratio) |
| 68 | + x2 = int((df_g["x"] + df_g["w"]) * ratio) |
| 69 | + y2 = int((df_g["y"] + df_g["h"]) * ratio) |
| 70 | + cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), 2) |
| 71 | + cv2.putText(img, text=label, org=(5, 20), fontFace=cv2.FONT_HERSHEY_SIMPLEX, |
| 72 | + fontScale=0.8, color=(0, 0, 255), thickness=1) |
| 73 | + cv2.imwrite(output_path, img) |
| 74 | + |
| 75 | + |
| 76 | +def main(): |
| 77 | + # parser config |
| 78 | + config_file = "./config.ini" |
| 79 | + cp = ConfigParser() |
| 80 | + cp.read(config_file) |
| 81 | + |
| 82 | + # default config |
| 83 | + output_dir = cp["DEFAULT"].get("output_dir") |
| 84 | + base_model_name = cp["DEFAULT"].get("base_model_name") |
| 85 | + class_names = cp["DEFAULT"].get("class_names").split(",") |
| 86 | + image_source_dir = cp["DEFAULT"].get("image_source_dir") |
| 87 | + image_dimension = cp["TRAIN"].getint("image_dimension") |
| 88 | + |
| 89 | + # parse weights file path |
| 90 | + output_weights_name = cp["TRAIN"].get("output_weights_name") |
| 91 | + weights_path = os.path.join(output_dir, output_weights_name) |
| 92 | + best_weights_path = os.path.join(output_dir, f"best_{output_weights_name}") |
| 93 | + |
| 94 | + # CAM config |
| 95 | + bbox_list_file = cp["CAM"].get("bbox_list_file") |
| 96 | + use_best_weights = cp["CAM"].getboolean("use_best_weights") |
| 97 | + |
| 98 | + print("** load model **") |
| 99 | + if use_best_weights: |
| 100 | + print("** use best weights **") |
| 101 | + model_weights_path = best_weights_path |
| 102 | + else: |
| 103 | + print("** use last weights **") |
| 104 | + model_weights_path = weights_path |
| 105 | + model_factory = ModelFactory() |
| 106 | + model = model_factory.get_model( |
| 107 | + class_names, |
| 108 | + model_name=base_model_name, |
| 109 | + use_base_weights=False, |
| 110 | + weights_path=model_weights_path) |
| 111 | + |
| 112 | + print("read bbox list file") |
| 113 | + df_images = pd.read_csv(bbox_list_file, header=None, skiprows=1) |
| 114 | + df_images.columns = ["file_name", "label", "x", "y", "w", "h"] |
| 115 | + |
| 116 | + print("create a generator for loading transformed images") |
| 117 | + cam_sequence = AugmentedImageSequence( |
| 118 | + dataset_csv_file=os.path.join(output_dir, "test.csv"), |
| 119 | + class_names=class_names, |
| 120 | + source_image_dir=image_source_dir, |
| 121 | + batch_size=1, |
| 122 | + target_size=(image_dimension, image_dimension), |
| 123 | + augmenter=None, |
| 124 | + steps=1, |
| 125 | + shuffle_on_epoch_end=False, |
| 126 | + ) |
| 127 | + |
| 128 | + image_output_dir = os.path.join(output_dir, "cam") |
| 129 | + if not os.path.isdir(image_output_dir): |
| 130 | + os.makedirs(image_output_dir) |
| 131 | + |
| 132 | + print("create CAM") |
| 133 | + df_images.apply( |
| 134 | + lambda g: create_cam( |
| 135 | + df_g=g, |
| 136 | + output_dir=image_output_dir, |
| 137 | + image_source_dir=image_source_dir, |
| 138 | + model=model, |
| 139 | + generator=cam_sequence, |
| 140 | + class_names=class_names, |
| 141 | + ), |
| 142 | + axis=1, |
| 143 | + ) |
| 144 | + |
| 145 | + |
| 146 | +if __name__ == "__main__": |
| 147 | + main() |
0 commit comments