|
8 | 8 | from matplotlib import pyplot as plt
|
9 | 9 | from torch.utils.tensorboard import SummaryWriter
|
10 | 10 |
|
| 11 | +import shutil |
| 12 | +import numpy as np |
| 13 | + |
| 14 | +from PIL import Image |
| 15 | +from tqdm import tqdm |
| 16 | +from .utils import cvtColor, preprocess_input, resize_image |
| 17 | +from .utils_bbox import DecodeBox |
| 18 | +from .utils_map import get_coco_map, get_map |
| 19 | + |
11 | 20 |
|
12 | 21 | class LossHistory():
|
13 | 22 | def __init__(self, log_dir, model, input_shape):
|
14 |
| - time_str = datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d_%H_%M_%S') |
15 |
| - self.log_dir = os.path.join(log_dir, "loss_" + str(time_str)) |
| 23 | + self.log_dir = log_dir |
16 | 24 | self.losses = []
|
17 | 25 | self.val_loss = []
|
18 | 26 |
|
@@ -68,3 +76,157 @@ def loss_plot(self):
|
68 | 76 |
|
69 | 77 | plt.cla()
|
70 | 78 | plt.close("all")
|
| 79 | + |
| 80 | +class EvalCallback(): |
| 81 | + def __init__(self, net, input_shape, anchors, anchors_mask, class_names, num_classes, val_lines, log_dir, cuda, \ |
| 82 | + map_out_path=".temp_map_out", max_boxes=100, confidence=0.05, nms_iou=0.5, letterbox_image=True, MINOVERLAP=0.5, eval_flag=True, period=1): |
| 83 | + super(EvalCallback, self).__init__() |
| 84 | + |
| 85 | + self.net = net |
| 86 | + self.input_shape = input_shape |
| 87 | + self.anchors = anchors |
| 88 | + self.anchors_mask = anchors_mask |
| 89 | + self.class_names = class_names |
| 90 | + self.num_classes = num_classes |
| 91 | + self.val_lines = val_lines |
| 92 | + self.log_dir = log_dir |
| 93 | + self.cuda = cuda |
| 94 | + self.map_out_path = map_out_path |
| 95 | + self.max_boxes = max_boxes |
| 96 | + self.confidence = confidence |
| 97 | + self.nms_iou = nms_iou |
| 98 | + self.letterbox_image = letterbox_image |
| 99 | + self.MINOVERLAP = MINOVERLAP |
| 100 | + self.eval_flag = eval_flag |
| 101 | + self.period = period |
| 102 | + |
| 103 | + self.bbox_util = DecodeBox(self.anchors, self.num_classes, (self.input_shape[0], self.input_shape[1]), self.anchors_mask) |
| 104 | + |
| 105 | + self.maps = [0] |
| 106 | + self.epoches = [0] |
| 107 | + if self.eval_flag: |
| 108 | + with open(os.path.join(self.log_dir, "epoch_map.txt"), 'a') as f: |
| 109 | + f.write(str(0)) |
| 110 | + f.write("\n") |
| 111 | + |
| 112 | + def get_map_txt(self, image_id, image, class_names, map_out_path): |
| 113 | + f = open(os.path.join(map_out_path, "detection-results/"+image_id+".txt"), "w", encoding='utf-8') |
| 114 | + image_shape = np.array(np.shape(image)[0:2]) |
| 115 | + #---------------------------------------------------------# |
| 116 | + # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。 |
| 117 | + # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB |
| 118 | + #---------------------------------------------------------# |
| 119 | + image = cvtColor(image) |
| 120 | + #---------------------------------------------------------# |
| 121 | + # 给图像增加灰条,实现不失真的resize |
| 122 | + # 也可以直接resize进行识别 |
| 123 | + #---------------------------------------------------------# |
| 124 | + image_data = resize_image(image, (self.input_shape[1], self.input_shape[0]), self.letterbox_image) |
| 125 | + #---------------------------------------------------------# |
| 126 | + # 添加上batch_size维度 |
| 127 | + #---------------------------------------------------------# |
| 128 | + image_data = np.expand_dims(np.transpose(preprocess_input(np.array(image_data, dtype='float32')), (2, 0, 1)), 0) |
| 129 | + |
| 130 | + with torch.no_grad(): |
| 131 | + images = torch.from_numpy(image_data) |
| 132 | + if self.cuda: |
| 133 | + images = images.cuda() |
| 134 | + #---------------------------------------------------------# |
| 135 | + # 将图像输入网络当中进行预测! |
| 136 | + #---------------------------------------------------------# |
| 137 | + outputs = self.net(images) |
| 138 | + outputs = self.bbox_util.decode_box(outputs) |
| 139 | + #---------------------------------------------------------# |
| 140 | + # 将预测框进行堆叠,然后进行非极大抑制 |
| 141 | + #---------------------------------------------------------# |
| 142 | + results = self.bbox_util.non_max_suppression(torch.cat(outputs, 1), self.num_classes, self.input_shape, |
| 143 | + image_shape, self.letterbox_image, conf_thres = self.confidence, nms_thres = self.nms_iou) |
| 144 | + |
| 145 | + if results[0] is None: |
| 146 | + return |
| 147 | + |
| 148 | + top_label = np.array(results[0][:, 6], dtype = 'int32') |
| 149 | + top_conf = results[0][:, 4] * results[0][:, 5] |
| 150 | + top_boxes = results[0][:, :4] |
| 151 | + |
| 152 | + top_100 = np.argsort(top_label)[::-1][:self.max_boxes] |
| 153 | + top_boxes = top_boxes[top_100] |
| 154 | + top_conf = top_conf[top_100] |
| 155 | + top_label = top_label[top_100] |
| 156 | + |
| 157 | + for i, c in list(enumerate(top_label)): |
| 158 | + predicted_class = self.class_names[int(c)] |
| 159 | + box = top_boxes[i] |
| 160 | + score = str(top_conf[i]) |
| 161 | + |
| 162 | + top, left, bottom, right = box |
| 163 | + if predicted_class not in class_names: |
| 164 | + continue |
| 165 | + |
| 166 | + f.write("%s %s %s %s %s %s\n" % (predicted_class, score[:6], str(int(left)), str(int(top)), str(int(right)),str(int(bottom)))) |
| 167 | + |
| 168 | + f.close() |
| 169 | + return |
| 170 | + |
| 171 | + def on_epoch_end(self, epoch, model_eval): |
| 172 | + if epoch % self.period == 0 and self.eval_flag: |
| 173 | + self.net = model_eval |
| 174 | + if not os.path.exists(self.map_out_path): |
| 175 | + os.makedirs(self.map_out_path) |
| 176 | + if not os.path.exists(os.path.join(self.map_out_path, "ground-truth")): |
| 177 | + os.makedirs(os.path.join(self.map_out_path, "ground-truth")) |
| 178 | + if not os.path.exists(os.path.join(self.map_out_path, "detection-results")): |
| 179 | + os.makedirs(os.path.join(self.map_out_path, "detection-results")) |
| 180 | + print("Get map.") |
| 181 | + for annotation_line in tqdm(self.val_lines): |
| 182 | + line = annotation_line.split() |
| 183 | + image_id = os.path.basename(line[0]).split('.')[0] |
| 184 | + #------------------------------# |
| 185 | + # 读取图像并转换成RGB图像 |
| 186 | + #------------------------------# |
| 187 | + image = Image.open(line[0]) |
| 188 | + #------------------------------# |
| 189 | + # 获得预测框 |
| 190 | + #------------------------------# |
| 191 | + gt_boxes = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) |
| 192 | + #------------------------------# |
| 193 | + # 获得预测txt |
| 194 | + #------------------------------# |
| 195 | + self.get_map_txt(image_id, image, self.class_names, self.map_out_path) |
| 196 | + |
| 197 | + #------------------------------# |
| 198 | + # 获得真实框txt |
| 199 | + #------------------------------# |
| 200 | + with open(os.path.join(self.map_out_path, "ground-truth/"+image_id+".txt"), "w") as new_f: |
| 201 | + for box in gt_boxes: |
| 202 | + left, top, right, bottom, obj = box |
| 203 | + obj_name = self.class_names[obj] |
| 204 | + new_f.write("%s %s %s %s %s\n" % (obj_name, left, top, right, bottom)) |
| 205 | + |
| 206 | + print("Calculate Map.") |
| 207 | + try: |
| 208 | + temp_map = get_coco_map(class_names = self.class_names, path = self.map_out_path)[1] |
| 209 | + except: |
| 210 | + temp_map = get_map(self.MINOVERLAP, False, path = self.map_out_path) |
| 211 | + self.maps.append(temp_map) |
| 212 | + self.epoches.append(epoch) |
| 213 | + |
| 214 | + with open(os.path.join(self.log_dir, "epoch_map.txt"), 'a') as f: |
| 215 | + f.write(str(temp_map)) |
| 216 | + f.write("\n") |
| 217 | + |
| 218 | + plt.figure() |
| 219 | + plt.plot(self.epoches, self.maps, 'red', linewidth = 2, label='train map') |
| 220 | + |
| 221 | + plt.grid(True) |
| 222 | + plt.xlabel('Epoch') |
| 223 | + plt.ylabel('Map %s'%str(self.MINOVERLAP)) |
| 224 | + plt.title('A Map Curve') |
| 225 | + plt.legend(loc="upper right") |
| 226 | + |
| 227 | + plt.savefig(os.path.join(self.log_dir, "epoch_map.png")) |
| 228 | + plt.cla() |
| 229 | + plt.close("all") |
| 230 | + |
| 231 | + print("Get map done.") |
| 232 | + shutil.rmtree(self.map_out_path) |
0 commit comments