|
| 1 | +# coding: utf-8 |
| 2 | +__author__ = 'ZFTurbo: https://kaggle.com/zfturbo' |
| 3 | + |
| 4 | + |
| 5 | +import warnings |
| 6 | +import numpy as np |
| 7 | +from numba import jit |
| 8 | + |
| 9 | + |
| 10 | +@jit(nopython=True) |
| 11 | +def bb_intersection_over_union_3d(A, B) -> float: |
| 12 | + xA = max(A[0], B[0]) |
| 13 | + yA = max(A[1], B[1]) |
| 14 | + zA = max(A[2], B[2]) |
| 15 | + xB = min(A[3], B[3]) |
| 16 | + yB = min(A[4], B[4]) |
| 17 | + zB = min(A[5], B[5]) |
| 18 | + |
| 19 | + interVol = max(0, xB - xA) * max(0, yB - yA) * max(0, zB - zA) |
| 20 | + if interVol == 0: |
| 21 | + return 0.0 |
| 22 | + |
| 23 | + # compute the volume of both the prediction and ground-truth rectangular boxes |
| 24 | + boxAVol = (A[3] - A[0]) * (A[4] - A[1]) * (A[5] - A[2]) |
| 25 | + boxBVol = (B[3] - B[0]) * (B[4] - B[1]) * (B[5] - B[2]) |
| 26 | + |
| 27 | + iou = interVol / float(boxAVol + boxBVol - interVol) |
| 28 | + return iou |
| 29 | + |
| 30 | + |
| 31 | +def prefilter_boxes(boxes, scores, labels, weights, thr): |
| 32 | + # Create dict with boxes stored by its label |
| 33 | + new_boxes = dict() |
| 34 | + |
| 35 | + for t in range(len(boxes)): |
| 36 | + |
| 37 | + if len(boxes[t]) != len(scores[t]): |
| 38 | + print('Error. Length of boxes arrays not equal to length of scores array: {} != {}'.format(len(boxes[t]), len(scores[t]))) |
| 39 | + exit() |
| 40 | + |
| 41 | + if len(boxes[t]) != len(labels[t]): |
| 42 | + print('Error. Length of boxes arrays not equal to length of labels array: {} != {}'.format(len(boxes[t]), len(labels[t]))) |
| 43 | + exit() |
| 44 | + |
| 45 | + for j in range(len(boxes[t])): |
| 46 | + score = scores[t][j] |
| 47 | + if score < thr: |
| 48 | + continue |
| 49 | + label = int(labels[t][j]) |
| 50 | + box_part = boxes[t][j] |
| 51 | + x1 = float(box_part[0]) |
| 52 | + y1 = float(box_part[1]) |
| 53 | + z1 = float(box_part[2]) |
| 54 | + x2 = float(box_part[3]) |
| 55 | + y2 = float(box_part[4]) |
| 56 | + z2 = float(box_part[5]) |
| 57 | + |
| 58 | + # Box data checks |
| 59 | + if x2 < x1: |
| 60 | + warnings.warn('X2 < X1 value in box. Swap them.') |
| 61 | + x1, x2 = x2, x1 |
| 62 | + if y2 < y1: |
| 63 | + warnings.warn('Y2 < Y1 value in box. Swap them.') |
| 64 | + y1, y2 = y2, y1 |
| 65 | + if z2 < z1: |
| 66 | + warnings.warn('Z2 < Z1 value in box. Swap them.') |
| 67 | + z1, z2 = z2, z1 |
| 68 | + if x1 < 0: |
| 69 | + warnings.warn('X1 < 0 in box. Set it to 0.') |
| 70 | + x1 = 0 |
| 71 | + if x1 > 1: |
| 72 | + warnings.warn('X1 > 1 in box. Set it to 1. Check that you normalize boxes in [0, 1] range.') |
| 73 | + x1 = 1 |
| 74 | + if x2 < 0: |
| 75 | + warnings.warn('X2 < 0 in box. Set it to 0.') |
| 76 | + x2 = 0 |
| 77 | + if x2 > 1: |
| 78 | + warnings.warn('X2 > 1 in box. Set it to 1. Check that you normalize boxes in [0, 1] range.') |
| 79 | + x2 = 1 |
| 80 | + if y1 < 0: |
| 81 | + warnings.warn('Y1 < 0 in box. Set it to 0.') |
| 82 | + y1 = 0 |
| 83 | + if y1 > 1: |
| 84 | + warnings.warn('Y1 > 1 in box. Set it to 1. Check that you normalize boxes in [0, 1] range.') |
| 85 | + y1 = 1 |
| 86 | + if y2 < 0: |
| 87 | + warnings.warn('Y2 < 0 in box. Set it to 0.') |
| 88 | + y2 = 0 |
| 89 | + if y2 > 1: |
| 90 | + warnings.warn('Y2 > 1 in box. Set it to 1. Check that you normalize boxes in [0, 1] range.') |
| 91 | + y2 = 1 |
| 92 | + if z1 < 0: |
| 93 | + warnings.warn('Z1 < 0 in box. Set it to 0.') |
| 94 | + z1 = 0 |
| 95 | + if z1 > 1: |
| 96 | + warnings.warn('Z1 > 1 in box. Set it to 1. Check that you normalize boxes in [0, 1] range.') |
| 97 | + z1 = 1 |
| 98 | + if z2 < 0: |
| 99 | + warnings.warn('Z2 < 0 in box. Set it to 0.') |
| 100 | + z2 = 0 |
| 101 | + if z2 > 1: |
| 102 | + warnings.warn('Z2 > 1 in box. Set it to 1. Check that you normalize boxes in [0, 1] range.') |
| 103 | + z2 = 1 |
| 104 | + if (x2 - x1) * (y2 - y1) * (z2 - z1) == 0.0: |
| 105 | + warnings.warn("Zero volume box skipped: {}.".format(box_part)) |
| 106 | + continue |
| 107 | + |
| 108 | + b = [int(label), float(score) * weights[t], x1, y1, z1, x2, y2, z2] |
| 109 | + if label not in new_boxes: |
| 110 | + new_boxes[label] = [] |
| 111 | + new_boxes[label].append(b) |
| 112 | + |
| 113 | + # Sort each list in dict by score and transform it to numpy array |
| 114 | + for k in new_boxes: |
| 115 | + current_boxes = np.array(new_boxes[k]) |
| 116 | + new_boxes[k] = current_boxes[current_boxes[:, 1].argsort()[::-1]] |
| 117 | + |
| 118 | + return new_boxes |
| 119 | + |
| 120 | + |
| 121 | +def get_weighted_box(boxes, conf_type='avg'): |
| 122 | + """ |
| 123 | + Create weighted box for set of boxes |
| 124 | + :param boxes: set of boxes to fuse |
| 125 | + :param conf_type: type of confidence one of 'avg' or 'max' |
| 126 | + :return: weighted box |
| 127 | + """ |
| 128 | + |
| 129 | + box = np.zeros(8, dtype=np.float32) |
| 130 | + conf = 0 |
| 131 | + conf_list = [] |
| 132 | + for b in boxes: |
| 133 | + box[2:] += (b[1] * b[2:]) |
| 134 | + conf += b[1] |
| 135 | + conf_list.append(b[1]) |
| 136 | + box[0] = boxes[0][0] |
| 137 | + if conf_type == 'avg': |
| 138 | + box[1] = conf / len(boxes) |
| 139 | + elif conf_type == 'max': |
| 140 | + box[1] = np.array(conf_list).max() |
| 141 | + box[2:] /= conf |
| 142 | + return box |
| 143 | + |
| 144 | + |
| 145 | +def find_matching_box(boxes_list, new_box, match_iou): |
| 146 | + best_iou = match_iou |
| 147 | + best_index = -1 |
| 148 | + for i in range(len(boxes_list)): |
| 149 | + box = boxes_list[i] |
| 150 | + if box[0] != new_box[0]: |
| 151 | + continue |
| 152 | + iou = bb_intersection_over_union_3d(box[2:], new_box[2:]) |
| 153 | + if iou > best_iou: |
| 154 | + best_index = i |
| 155 | + best_iou = iou |
| 156 | + |
| 157 | + return best_index, best_iou |
| 158 | + |
| 159 | + |
| 160 | +def weighted_boxes_fusion_3d(boxes_list, scores_list, labels_list, weights=None, iou_thr=0.55, skip_box_thr=0.0, conf_type='avg', allows_overflow=False): |
| 161 | + ''' |
| 162 | + :param boxes_list: list of boxes predictions from each model, each box is 6 numbers. |
| 163 | + It has 3 dimensions (models_number, model_preds, 6) |
| 164 | + Order of boxes: x1, y1, z1, x2, y2 z2. We expect float normalized coordinates [0; 1] |
| 165 | + :param scores_list: list of scores for each model |
| 166 | + :param labels_list: list of labels for each model |
| 167 | + :param weights: list of weights for each model. Default: None, which means weight == 1 for each model |
| 168 | + :param iou_thr: IoU value for boxes to be a match |
| 169 | + :param skip_box_thr: exclude boxes with score lower than this variable |
| 170 | + :param conf_type: how to calculate confidence in weighted boxes. 'avg': average value, 'max': maximum value |
| 171 | + :param allows_overflow: false if we want confidence score not exceed 1.0 |
| 172 | +
|
| 173 | + :return: boxes: boxes coordinates (Order of boxes: x1, y1, z1, x2, y2, z2). |
| 174 | + :return: scores: confidence scores |
| 175 | + :return: labels: boxes labels |
| 176 | + ''' |
| 177 | + |
| 178 | + if weights is None: |
| 179 | + weights = np.ones(len(boxes_list)) |
| 180 | + if len(weights) != len(boxes_list): |
| 181 | + print('Warning: incorrect number of weights {}. Must be: {}. Set weights equal to 1.'.format(len(weights), len(boxes_list))) |
| 182 | + weights = np.ones(len(boxes_list)) |
| 183 | + weights = np.array(weights) |
| 184 | + |
| 185 | + if conf_type not in ['avg', 'max']: |
| 186 | + print('Error. Unknown conf_type: {}. Must be "avg" or "max". Use "avg"'.format(conf_type)) |
| 187 | + conf_type = 'avg' |
| 188 | + |
| 189 | + filtered_boxes = prefilter_boxes(boxes_list, scores_list, labels_list, weights, skip_box_thr) |
| 190 | + if len(filtered_boxes) == 0: |
| 191 | + return np.zeros((0, 6)), np.zeros((0,)), np.zeros((0,)) |
| 192 | + |
| 193 | + overall_boxes = [] |
| 194 | + for label in filtered_boxes: |
| 195 | + boxes = filtered_boxes[label] |
| 196 | + new_boxes = [] |
| 197 | + weighted_boxes = [] |
| 198 | + |
| 199 | + # Clusterize boxes |
| 200 | + for j in range(0, len(boxes)): |
| 201 | + index, best_iou = find_matching_box(weighted_boxes, boxes[j], iou_thr) |
| 202 | + if index != -1: |
| 203 | + new_boxes[index].append(boxes[j]) |
| 204 | + weighted_boxes[index] = get_weighted_box(new_boxes[index], conf_type) |
| 205 | + else: |
| 206 | + new_boxes.append([boxes[j].copy()]) |
| 207 | + weighted_boxes.append(boxes[j].copy()) |
| 208 | + |
| 209 | + # Rescale confidence based on number of models and boxes |
| 210 | + for i in range(len(new_boxes)): |
| 211 | + if not allows_overflow: |
| 212 | + weighted_boxes[i][1] = weighted_boxes[i][1] * min(weights.sum(), len(new_boxes[i])) / weights.sum() |
| 213 | + else: |
| 214 | + weighted_boxes[i][1] = weighted_boxes[i][1] * len(new_boxes[i]) / weights.sum() |
| 215 | + overall_boxes.append(np.array(weighted_boxes)) |
| 216 | + |
| 217 | + overall_boxes = np.concatenate(overall_boxes, axis=0) |
| 218 | + overall_boxes = overall_boxes[overall_boxes[:, 1].argsort()[::-1]] |
| 219 | + boxes = overall_boxes[:, 2:] |
| 220 | + scores = overall_boxes[:, 1] |
| 221 | + labels = overall_boxes[:, 0] |
| 222 | + return boxes, scores, labels |
0 commit comments