def compute_iou_bb()

in prepare_data/sm-ground_truth_object_detection_example/ground_truth_od.py [0:0]


    def compute_iou_bb(self):
        """Compute the mean intersection over union for a collection of
        bounding boxes.
        """

        # Precompute data for the consolidated boxes if necessary.
        for box in self.consolidated_boxes:
            try:
                box.xmin
            except AttributeError:
                box.compute_bb_data()

        # Make the numpy arrays.
        if self.gt_boxes:
            gts = np.vstack([(box.xmin, box.ymin, box.xmax, box.ymax) for box in self.gt_boxes])
        else:
            gts = []
        if self.consolidated_boxes:
            preds = np.vstack(
                [(box.xmin, box.ymin, box.xmax, box.ymax) for box in self.consolidated_boxes]
            )
        else:
            preds = []
        confs = np.array([box.confidence for box in self.consolidated_boxes])

        if len(preds) == 0 and len(gts) == 0:
            return 1.0
        if len(preds) == 0 or len(gts) == 0:
            return 0.0
        preds = preds[np.argsort(confs.flatten())][::-1]

        is_pred_assigned_to_gt = [False] * len(gts)
        pred_areas = (preds[:, 2] - preds[:, 0]) * (preds[:, 3] - preds[:, 1])
        gt_areas = (gts[:, 2] - gts[:, 0]) * (gts[:, 3] - gts[:, 1])
        all_ious = []
        for pred_id, pred in enumerate(preds):
            best_iou = 0
            best_id = -1
            for gt_id, gt in enumerate(gts):
                if is_pred_assigned_to_gt[gt_id]:
                    continue
                x1 = max(gt[0], pred[0])
                y1 = max(gt[1], pred[1])
                x2 = min(gt[2], pred[2])
                y2 = min(gt[3], pred[3])
                iw = max(0, x2 - x1)
                ih = max(0, y2 - y1)
                inter = iw * ih
                iou = inter / (pred_areas[pred_id] + gt_areas[gt_id] - inter)
                if iou > best_iou:
                    best_iou = iou
                    best_id = gt_id
            if best_id != -1:
                is_pred_assigned_to_gt[best_id] = True
                # True positive! Store the IoU.
                all_ious.append(best_iou)
            else:
                # 0 IoU for each unmatched gt (false-negative).
                all_ious.append(0.0)

        # 0 IoU for each unmatched prediction (false-positive).
        all_ious.extend([0.0] * (len(is_pred_assigned_to_gt) - sum(is_pred_assigned_to_gt)))

        return np.mean(all_ious)