Python get iou

60 Python code examples are found related to " get iou". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: evalMetrics.py    From pytorch-mri-segmentation-3D with MIT License 6 votes vote down vote up
def get_iou(pred, gt, num_labels):
    if pred.shape != gt.shape:
        print('pred shape',pred.shape, 'gt shape', gt.shape)
    assert(pred.shape == gt.shape)
    gt = gt.astype(np.float32)
    pred = pred.astype(np.float32)

    gt = gt.reshape(-1)
    pred = pred.reshape(-1)

    max_label = num_labels-1
    count = np.zeros((max_label+1,))
    for j in range(max_label+1):
        gt_loc = set(np.where(gt == j)[0])
        pred_loc = set(np.where(pred == j)[0])

        intersection = set.intersection(gt_loc, pred_loc)
        union = set.union(gt_loc, pred_loc)

        if len(gt_loc) != 0:
            count[j] = float(len(intersection)) / float(len(union))
    return np.sum(count) / float(num_labels) 
Example 2
Source File: tvqa_dataset.py    From TVQAplus with MIT License 6 votes vote down vote up
def get_iou_data(self, gt_box_data_i, meta_data_i, frm_cnt_i):
        """
        meta_data (dict):  with vid_name as key,
        add iou_data entry, organized similar to bbox_data
        """
        frm_cnt_i = frm_cnt_i + 1  # add extra 1 since img_ids are 1-indexed
        iou_data_i = {}
        img_ids = sorted(gt_box_data_i.keys(), key=lambda x: int(x))
        img_ids = [e for e in img_ids if int(e) < frm_cnt_i]
        for img_id in img_ids:
            iou_data_i[img_id] = []
            cur_detected_boxes = meta_data_i["boxes"][int(img_id) - 1]
            for box in gt_box_data_i[img_id]:
                iou_list = self.get_labels_single_box(box, cur_detected_boxes)
                iou_data_i[img_id].append({
                    "iou": iou_list,
                    "label": box["label"],
                    "img_id": img_id
                })
        return iou_data_i 
Example 3
Source File: model_utils.py    From TVQAplus with MIT License 6 votes vote down vote up
def get_high_iou_sapns(gt_ts_list, pred_ts_list, iou_thd=0.5, add_gt=True):
    """ Note
    Args:
        gt_ts_list: N * (st, ed)
        pred_ts_list: N * [(st_idx, ed_idx, confidence), ...]
        iou_thd (float):
        add_gt (bool):
    Returns:

    """
    spans = []  # container for both pred and gt (st, ed),
    for idx, (gt_ts, pred_ts_sublist) in enumerate(zip(gt_ts_list, pred_ts_list)):
        if add_gt:
            cur_spans = [gt_ts]
        else:
            cur_spans = []
        for pred_ts in pred_ts_sublist:
            pred_ts = pred_ts[:2]  # (st, ed)
            if compute_temporal_iou(pred_ts, gt_ts) >= iou_thd:
                cur_spans.append(pred_ts)
        spans.append(cur_spans)
    return spans  # N * [(st, ed), ...] 
Example 4
Source File: evalPixelLevelSemanticLabeling.py    From fcn8s_tensorflow with GNU General Public License v3.0 6 votes vote down vote up
def getInstanceIouScoreForCategory(category, confMatrix, instStats, args):
    if not category in instStats["categories"]:
        return float('nan')
    labelIds = instStats["categories"][category]["labelIds"]

    tp = instStats["categories"][category]["tpWeighted"]
    fn = instStats["categories"][category]["fnWeighted"]

    # the number of false positive pixels for this category
    # same as above
    notIgnoredAndNotInCategory = [l for l in args.evalLabels if not id2label[l].ignoreInEval and id2label[l].category != category]
    fp = np.longlong(confMatrix[notIgnoredAndNotInCategory,:][:,labelIds].sum())

    # the denominator of the IOU score
    denom = (tp + fp + fn)
    if denom == 0:
        return float('nan')

    # return IOU
    return float(tp) / denom


# create a dictionary containing all relevant results 
Example 5
Source File: evalPixelLevelSemanticLabeling.py    From fcn8s_tensorflow with GNU General Public License v3.0 6 votes vote down vote up
def getInstanceIouScoreForLabel(label, confMatrix, instStats, args):
    if id2label[label].ignoreInEval:
        return float('nan')

    labelName = id2label[label].name
    if not labelName in instStats["classes"]:
        return float('nan')

    tp = instStats["classes"][labelName]["tpWeighted"]
    fn = instStats["classes"][labelName]["fnWeighted"]
    # false postives computed as above
    notIgnored = [l for l in args.evalLabels if not id2label[l].ignoreInEval and not l==label]
    fp = np.longlong(confMatrix[notIgnored,label].sum())

    # the denominator of the IOU score
    denom = (tp + fp + fn)
    if denom == 0:
        return float('nan')

    # return IOU
    return float(tp) / denom

# Calculate prior for a particular class id. 
Example 6
Source File: bbox_utils.py    From densecap-tensorflow with MIT License 6 votes vote down vote up
def get_bbox_iou_matrix(bboxes):
  region_n = bboxes.shape[0]
  #area, intersection area, union area
  bbox_areas = (bboxes[:,2] - bboxes[:,0]) * \
    (bboxes[:, 3] - bboxes[:, 1])
  
  x_a1 = bboxes[:,0].reshape(region_n,1)
  x_a2 = bboxes[:,2].reshape(region_n,1)
  x_b1 = bboxes[:,0].reshape(1,region_n)
  x_b2 = bboxes[:,2].reshape(1,region_n)
  y_a1 = bboxes[:,1].reshape(region_n,1)
  y_a2 = bboxes[:,3].reshape(region_n,1)
  y_b1 = bboxes[:,1].reshape(1,region_n)
  y_b2 = bboxes[:,3].reshape(1,region_n)
  bbox_pair_x_diff = np.maximum(0, np.minimum(x_a2, x_b2) - np.maximum(x_a1, x_b1))
  bbox_pair_y_diff = np.maximum(0, np.minimum(y_a2, y_b2) - np.maximum(y_a1, y_b1))
  inter_areas = bbox_pair_x_diff * bbox_pair_y_diff
  
  #IoU
  union_areas = bbox_areas.reshape(region_n,1) + bbox_areas.reshape(1,region_n)
 
  bbox_iou = inter_areas / (union_areas - inter_areas)
  return bbox_iou 
Example 7
Source File: tracking_utils.py    From 3d-vehicle-tracking with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_iou(box_t1, box_t2, thres):
    """
    Input:
        box_t1: (N1, 4)
        box_t2: (N2, 4)
        thres: single value
    Output:
        iou: Float (N1, N2)
        idx: Long (N1, 1)
        valid: Float (N1, 1)
    """
    # Get IOU
    iou_tensor = compute_iou_arr(box_t1, box_t2)  # [x1, y1, x2, y2]

    # Select index
    val = np.max(iou_tensor, axis=1)
    idx = iou_tensor.argmax(axis=1)

    # Matched index
    valid = (val > thres).reshape(-1, 1)

    return iou_tensor, idx, valid 
Example 8
Source File: pymini_yolo.py    From vrequest with MIT License 6 votes vote down vote up
def get_iou(self,box_pred,box_targ,anchor_idx):
        rate = 416/self.S
        pre_xy = box_pred[...,:2] * rate
        pre_wh_half = torch.exp(box_pred[...,2:4])*self.anchors[anchor_idx]/2
        pre_mins = pre_xy - pre_wh_half
        pre_maxs = pre_xy + pre_wh_half
        true_xy = box_targ[...,:2] * rate
        true_wh_half = torch.exp(box_targ[...,2:4])*self.anchors[anchor_idx]/2
        true_mins = true_xy - true_wh_half
        true_maxs = true_xy + true_wh_half

        inter_mins = torch.max(true_mins, pre_mins)
        inter_maxs = torch.min(true_maxs, pre_maxs)
        inter_wh   = torch.max(inter_maxs - inter_mins, torch.FloatTensor([0.]).to(DEVICE))
        inter_area = inter_wh[...,0] * inter_wh[...,1]
        ture_area = torch.exp(box_pred[...,2])*self.anchors[anchor_idx][0] * torch.exp(box_pred[...,3])*self.anchors[anchor_idx][1]
        pred_area = torch.exp(box_targ[...,2])*self.anchors[anchor_idx][0] * torch.exp(box_targ[...,3])*self.anchors[anchor_idx][1]
        ious = inter_area/(ture_area+pred_area-inter_area)
        return ious 
Example 9
Source File: evalpyt2.py    From pytorch-deeplab-resnet with MIT License 6 votes vote down vote up
def get_iou(pred,gt):
    if pred.shape!= gt.shape:
        print 'pred shape',pred.shape, 'gt shape', gt.shape
    assert(pred.shape == gt.shape)    
    gt = gt.astype(np.float32)
    pred = pred.astype(np.float32)

    count = np.zeros((max_label+1,))
    for j in range(max_label+1):
        x = np.where(pred==j)
        p_idx_j = set(zip(x[0].tolist(),x[1].tolist()))
        x = np.where(gt==j)
        GT_idx_j = set(zip(x[0].tolist(),x[1].tolist()))
        #pdb.set_trace()     
        n_jj = set.intersection(p_idx_j,GT_idx_j)
        u_jj = set.union(p_idx_j,GT_idx_j)
    
        
        if len(GT_idx_j)!=0:
            count[j] = float(len(n_jj))/float(len(u_jj))

    result_class = count
    Aiou = np.sum(result_class[:])/float(len(np.unique(gt))) 
    
    return Aiou 
Example 10
Source File: evalPixelLevelSemanticLabeling.py    From rec-attend-public with MIT License 6 votes vote down vote up
def getInstanceIouScoreForCategory(category, confMatrix, instStats, args):
    if not category in instStats["categories"]:
        return float('nan')
    labelIds = instStats["categories"][category]["labelIds"]

    tp = instStats["categories"][category]["tpWeighted"]
    fn = instStats["categories"][category]["fnWeighted"]

    # the number of false positive pixels for this category
    # same as above
    notIgnoredAndNotInCategory = [l for l in args.evalLabels if not id2label[l].ignoreInEval and id2label[l].category != category]
    fp = np.longlong(confMatrix[notIgnoredAndNotInCategory,:][:,labelIds].sum())

    # the denominator of the IOU score
    denom = (tp + fp + fn)
    if denom == 0:
        return float('nan')

    # return IOU
    return float(tp) / denom

# write JSON result file 
Example 11
Source File: EvalOSVOSWorst.py    From MOTSFusion with MIT License 6 votes vote down vote up
def get_fn_with_worst_iou(seq):
  result_fn = None
  result_gt = None
  result_measure = None
  files = glob.glob(seq + "/*.png")
  seq_name = seq.split("/")[-1]
  for file in files:
    fname = file.split("/")[-1]
    img = imread(file)
    img = img / 255

    gt_file = DAVIS_PATH + "/Annotations/480p/" + seq_name + "/" + fname
    gt = imread(gt_file)
    gt = gt / 255
    measure = compute_measures_for_binary_segmentation_single_image(img, gt)
    if measure is None:
      print(fn_file, gt_file, measure)
    if result_measure is None or measure[IOU] < result_measure[IOU]:
      result_measure = measure
      result_fn = DAVIS_PATH + "/JPEGImages/480p/" + seq_name + "/" + fname.replace(".png", ".jpg")
      result_gt = gt_file

  return result_fn, result_gt, result_measure 
Example 12
Source File: funcs.py    From PytorchToCaffe with MIT License 6 votes vote down vote up
def get_iou(box_a, box_b):
    """Compute the jaccard overlap of two sets of boxes.  The jaccard overlap
    is simply the intersection over union of two boxes.
    E.g.:
        A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B)
        The box should be [x1,y1,x2,y2]
    Args:
        box_a: Single numpy bounding box, Shape: [4] or Multiple bounding boxes, Shape: [num_boxes,4]
        box_b: Single numpy bounding box, Shape: [4]
    Return:
        jaccard overlap: Shape: [box_a.shape[0], box_a.shape[1]]
    """
    if box_a.ndim==1:
        box_a=box_a.reshape([1,-1])
    inter = intersect(box_a, box_b)
    area_a = ((box_a[:, 2]-box_a[:, 0]) *
              (box_a[:, 3]-box_a[:, 1]))  # [A,B]
    area_b = ((box_b[2]-box_b[0]) *
              (box_b[3]-box_b[1]))  # [A,B]
    union = area_a + area_b - inter
    return inter / union  # [A,B] 
Example 13
Source File: anchor_filter.py    From avod with MIT License 6 votes vote down vote up
def get_iou_filter(iou_list, iou_range):
    """Returns a boolean filter array that is the output of a given IoU range

    Args:
        iou_list: A numpy array with a list of IoU values
        iou_range: A list of [lower_bound, higher_bound] for IoU range

    Returns:
        iou_filter: A numpy array of booleans that filters for valid range
    """
    # Get bounds
    lower_bound = iou_range[0]
    higher_bound = iou_range[1]

    min_valid_list = lower_bound < iou_list
    max_valid_list = iou_list < higher_bound

    # Get filter for values in between
    iou_filter = np.logical_and(min_valid_list, max_valid_list)

    return iou_filter 
Example 14
Source File: evaluate_msc.py    From Pytorch-Deeplab with MIT License 6 votes vote down vote up
def get_iou(data_list, class_num, save_path=None):
    from multiprocessing import Pool 
    from deeplab.metric import ConfusionMatrix

    ConfM = ConfusionMatrix(class_num)
    f = ConfM.generateM
    pool = Pool() 
    m_list = pool.map(f, data_list)
    pool.close() 
    pool.join() 
    
    for m in m_list:
        ConfM.addM(m)

    aveJ, j_list, M = ConfM.jaccard()
    print('meanIOU: ' + str(aveJ) + '\n')
    if save_path:
        with open(save_path, 'w') as f:
            f.write('meanIOU: ' + str(aveJ) + '\n')
            f.write(str(j_list)+'\n')
            f.write(str(M)+'\n') 
Example 15
Source File: postprocessing.py    From open-solution-mapping-challenge with MIT License 6 votes vote down vote up
def get_iou_matrix(labels, annotations):
    mask_anns = []
    if annotations is None or annotations == []:
        return None
    else:
        for annotation in annotations:
            if not isinstance(annotation['segmentation'], dict):
                annotation['segmentation'] = \
                    cocomask.frPyObjects(annotation['segmentation'], labels.shape[0], labels.shape[1])[0]
        annotations = [annotation['segmentation'] for annotation in annotations]
        for label_nr in range(1, labels.max() + 1):
            mask = labels == label_nr
            mask_ann = rle_from_binary(mask.astype('uint8'))
            mask_anns.append(mask_ann)
        iou_matrix = cocomask.iou(mask_anns, annotations, [0, ] * len(annotations))
        return iou_matrix 
Example 16
Source File: utils.py    From python-dlpy with Apache License 2.0 6 votes vote down vote up
def get_iou_distance(box, centroid):
    '''
    Gets one minus the area intersection over union of two boxes

    Parameters
    ----------
    box : Box
        A Box object containing width and height information
    centroid : Box
        A Box object containing width and height information

    Returns
    -------
    float
        One minus intersection over union
        Smaller the number the closer the boxes

    '''
    w = min(box.w, centroid.w)
    h = min(box.h, centroid.h)
    intersection = w*h
    union = box.w * box.h + centroid.w * centroid.h - intersection
    iou = intersection/union
    return 1-iou 
Example 17
Source File: metrics.py    From TF.Keras-Commonly-used-models with Apache License 2.0 6 votes vote down vote up
def get_iou_score(class_weights=1., smooth=SMOOTH, per_image=True, threshold=None):
    """Change default parameters of IoU/Jaccard score

    Args:
        class_weights: 1. or list of class weights, len(weights) = C
        smooth: value to avoid division by zero
        per_image: if ``True``, metric is calculated as mean over images in batch (B),
            else over whole batch
        threshold: value to round predictions (use ``>`` comparison), if ``None`` prediction prediction will not be round

    Returns:
        ``callable``: IoU/Jaccard score
    """
    def score(gt, pr):
        return iou_score(gt, pr, class_weights=class_weights, smooth=smooth, per_image=per_image, threshold=threshold)

    return score 
Example 18
Source File: eval_det.py    From H3DNet with MIT License 5 votes vote down vote up
def get_iou(bb1, bb2):
    """ Compute IoU of two bounding boxes.
        ** Define your bod IoU function HERE **
    """
    #pass
    iou3d = calc_iou(bb1, bb2)
    return iou3d 
Example 19
Source File: evalPixelLevelSemanticLabeling.py    From fcn8s_tensorflow with GNU General Public License v3.0 5 votes vote down vote up
def getIouScoreForLabel(label, confMatrix, args):
    if id2label[label].ignoreInEval:
        return float('nan')

    # the number of true positive pixels for this label
    # the entry on the diagonal of the confusion matrix
    tp = np.longlong(confMatrix[label,label])

    # the number of false negative pixels for this label
    # the row sum of the matching row in the confusion matrix
    # minus the diagonal entry
    fn = np.longlong(confMatrix[label,:].sum()) - tp

    # the number of false positive pixels for this labels
    # Only pixels that are not on a pixel with ground truth label that is ignored
    # The column sum of the corresponding column in the confusion matrix
    # without the ignored rows and without the actual label of interest
    notIgnored = [l for l in args.evalLabels if not id2label[l].ignoreInEval and not l==label]
    fp = np.longlong(confMatrix[notIgnored,label].sum())

    # the denominator of the IOU score
    denom = (tp + fp + fn)
    if denom == 0:
        return float('nan')

    # return IOU
    return float(tp) / denom

# Calculate and return IOU score for a particular label 
Example 20
Source File: evalPixelLevelSemanticLabeling.py    From fcn8s_tensorflow with GNU General Public License v3.0 5 votes vote down vote up
def getIouScoreForCategory(category, confMatrix, args):
    # All labels in this category
    labels = category2labels[category]
    # The IDs of all valid labels in this category
    labelIds = [label.id for label in labels if not label.ignoreInEval and label.id in args.evalLabels]
    # If there are no valid labels, then return NaN
    if not labelIds:
        return float('nan')

    # the number of true positive pixels for this category
    # this is the sum of all entries in the confusion matrix
    # where row and column belong to a label ID of this category
    tp = np.longlong(confMatrix[labelIds,:][:,labelIds].sum())

    # the number of false negative pixels for this category
    # that is the sum of all rows of labels within this category
    # minus the number of true positive pixels
    fn = np.longlong(confMatrix[labelIds,:].sum()) - tp

    # the number of false positive pixels for this category
    # we count the column sum of all labels within this category
    # while skipping the rows of ignored labels and of labels within this category
    notIgnoredAndNotInCategory = [l for l in args.evalLabels if not id2label[l].ignoreInEval and id2label[l].category != category]
    fp = np.longlong(confMatrix[notIgnoredAndNotInCategory,:][:,labelIds].sum())

    # the denominator of the IOU score
    denom = (tp + fp + fn)
    if denom == 0:
        return float('nan')

    # return IOU
    return float(tp) / denom

# Calculate and return IOU score for a particular category 
Example 21
Source File: metrics.py    From robosat with MIT License 5 votes vote down vote up
def get_fg_iou(self):
        """Retrieves the foreground Intersection over Union score.

        Returns:
          The foreground Intersection over Union score for all observations seen so far.
        """

        try:
            iou = self.tp / (self.tp + self.fn + self.fp)
        except ZeroDivisionError:
            iou = float("NaN")

        return iou 
Example 22
Source File: evalIoU.py    From pytorch-semantic-segmentation with MIT License 5 votes vote down vote up
def getIouScoreForLabel(label, confMatrix, args):
    if id2label[label].ignoreInEval:
        return float('nan')

    # the number of true positive pixels for this label
    # the entry on the diagonal of the confusion matrix
    tp = np.longlong(confMatrix[label,label])

    # the number of false negative pixels for this label
    # the row sum of the matching row in the confusion matrix
    # minus the diagonal entry
    fn = np.longlong(confMatrix[label,:].sum()) - tp

    # the number of false positive pixels for this labels
    # Only pixels that are not on a pixel with ground truth label that is ignored
    # The column sum of the corresponding column in the confusion matrix
    # without the ignored rows and without the actual label of interest
    notIgnored = [l for l in args.evalLabels if not id2label[l].ignoreInEval and not l==label]
    fp = np.longlong(confMatrix[notIgnored,label].sum())

    # the denominator of the IOU score
    denom = (tp + fp + fn)
    if denom == 0:
        return float('nan')

    # return IOU
    return float(tp) / denom 
Example 23
Source File: evalIoU.py    From pytorch-semantic-segmentation with MIT License 5 votes vote down vote up
def getIouScoreForTrainLabel(label, confMatrix, args):
    if trainId2label[label].ignoreInEval:
        return float('nan')

    # the number of true positive pixels for this label
    # the entry on the diagonal of the confusion matrix
    tp = np.longlong(confMatrix[label,label])

    # the number of false negative pixels for this label
    # the row sum of the matching row in the confusion matrix
    # minus the diagonal entry
    fn = np.longlong(confMatrix[label,:].sum()) - tp

    # the number of false positive pixels for this labels
    # Only pixels that are not on a pixel with ground truth label that is ignored
    # The column sum of the corresponding column in the confusion matrix
    # without the ignored rows and without the actual label of interest
    notIgnored = [l for l in args.evalLabels if not trainId2label[l].ignoreInEval and not l==label]
    fp = np.longlong(confMatrix[notIgnored,label].sum())

    # the denominator of the IOU score
    denom = (tp + fp + fn)
    if denom == 0:
        return float('nan')

    # return IOU
    return float(tp) / denom

# Calculate and return IOU score for a particular label 
Example 24
Source File: camshift_object_tracker.py    From automl-video-ondevice with Apache License 2.0 5 votes vote down vote up
def get_iou(bb1, bb2):
  """Calculate the Intersection over Union (IoU) of two bounding boxes.

  Args:
    bb1: dict {'x1', 'x2', 'y1', 'y2'} The (x1, y1) position is at the top left
      corner, the (x2, y2) position is at the bottom right corner
    bb2: dict {'x1', 'x2', 'y1', 'y2'} The (x, y) position is at the top left
      corner, the (x2, y2) position is at the bottom right corner

  Returns:
    float in [0, 1]
  """

  # determine the coordinates of the intersection rectangle
  (bb1_x1, bb1_y1, bb1_x2, bb1_y2) = bb1
  (bb2_x1, bb2_y1, bb2_x2, bb2_y2) = bb2

  x_left = max(bb1_x1, bb2_x1)
  y_top = max(bb1_y1, bb2_y1)
  x_right = min(bb1_x2, bb2_x2)
  y_bottom = min(bb1_y2, bb2_y2)

  if x_right < x_left or y_bottom < y_top:
    return 0.0

  # The intersection of two axis-aligned bounding boxes is always an
  # axis-aligned bounding box
  intersection_area = (x_right - x_left) * (y_bottom - y_top)

  # compute the area of both AABBs
  bb1_area = (bb1_x2 - bb1_x1) * (bb1_y2 - bb1_y1)
  bb2_area = (bb2_x2 - bb2_x1) * (bb2_y2 - bb2_y1)

  # compute the intersection over union by taking the intersection
  # area and dividing it by the sum of prediction + ground-truth
  # areas - the interesection area
  iou = intersection_area / float(bb1_area + bb2_area - intersection_area)
  assert iou >= 0.0
  assert iou <= 1.0
  return iou 
Example 25
Source File: ensemble_landmarks.py    From kaggle-humpback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_iou(box1, box2):
    area1 = (box1[2]-box1[0]) * (box1[3]-box1[1])
    area2 = (box2[2]-box2[0]) * (box2[3]-box2[1])
    x1 = max(box1[0],box2[0])
    y1 = max(box1[1],box2[1])
    x2 = min(box1[2],box2[2])
    y2 = min(box1[3],box2[3])
    intersection = (x2-x1) * (y2-y1)
    iou = intersection / (area1 + area2 - intersection)
    return iou 
Example 26
Source File: eval.py    From Single-Human-Parsing-LIP with MIT License 5 votes vote down vote up
def get_mean_IoU(pred, gt, numClass):
    imPred = pred.copy()
    imLabel = gt.copy()

    imPred += 1
    imLabel += 1
    imPred = imPred * (imLabel > 0)

    # Compute area intersection:
    intersection = imPred * (imPred == imLabel)
    (area_intersection, _) = np.histogram(
        intersection, bins=numClass, range=(1, numClass))

    # Compute area union:
    (area_pred, _) = np.histogram(imPred, bins=numClass, range=(1, numClass))
    (area_label, _) = np.histogram(imLabel, bins=numClass, range=(1, numClass))
    area_union = area_pred + area_label - area_intersection

    # Remove classes from unlabeled pixels in gt image.
    # We should not penalize detections in unlabeled portions of the image.
    valid = area_label > 0

    # Compute intersection over union:
    IoU = area_intersection / (area_union + 1e-10)
    mean_IoU = np.average(IoU, weights=valid)
    return mean_IoU 
Example 27
Source File: eval.py    From Single-Human-Parsing-LIP with MIT License 5 votes vote down vote up
def get_mean_acc_and_IoU(pred, gt, numClass):
    imPred = pred.copy()
    imLabel = gt.copy()

    imPred += 1
    imLabel += 1
    imPred = imPred * (imLabel > 0)

    # Compute area intersection:
    intersection = imPred * (imPred == imLabel)
    (area_intersection, _) = np.histogram(
        intersection, bins=numClass, range=(1, numClass))

    # Compute area union:
    (area_pred, _) = np.histogram(imPred, bins=numClass, range=(1, numClass))
    (area_label, _) = np.histogram(imLabel, bins=numClass, range=(1, numClass))
    area_union = area_pred + area_label - area_intersection

    # Remove classes from unlabeled pixels in gt image.
    # We should not penalize detections in unlabeled portions of the image.
    valid = area_label > 0

    # Compute mean acc.
    classes_acc = area_intersection / (area_label + 1e-10)
    mean_acc = np.average(classes_acc, weights=valid)

    # Compute intersection over union:
    IoU = area_intersection / (area_union + 1e-10)
    mean_IoU = np.average(IoU, weights=valid)
    return mean_acc, mean_IoU 
Example 28
Source File: track_lib.py    From TNT with GNU General Public License v3.0 5 votes vote down vote up
def get_IOU(bbox1, bbox2): 
    area1 = bbox1[2]*bbox1[3] 
    area2 = bbox2[2]*bbox2[3] 
    x1 = max(bbox1[0], bbox2[0]) 
    y1 = max(bbox1[1], bbox2[1]) 
    x2 = min(bbox1[0]+bbox1[2]-1, bbox2[0]+bbox2[2]-1) 
    y2 = min(bbox1[1]+bbox1[3]-1, bbox2[1]+bbox2[3]-1)

    #import pdb; pdb.set_trace()
    overlap_area = max(0, (x2-x1+1))*max(0, (y2-y1+1))
    ratio = overlap_area/(area1+area2-overlap_area)
    return ratio,overlap_area,area1,area2 
Example 29
Source File: yolonet.py    From DmsMsgRcg with Apache License 2.0 5 votes vote down vote up
def get_box_iou_with(self, box2):
        x1_min, y1_min, x1_max, y1_max = self.get_coordinates()
        x2_min, y2_min, x2_max, y2_max = box2.get_coordinates()

        intersect_w = self._interval_overlap([x1_min, x1_max], [x2_min, x2_max])
        intersect_h = self._interval_overlap([y1_min, y1_max], [y2_min, y2_max])

        intersect = intersect_w * intersect_h

        union = self.w * self.h + box2.w * box2.h - intersect

        return float(intersect) / union 
Example 30
Source File: evaluation.py    From Pytorch-Instance-Lane-Segmentation with MIT License 5 votes vote down vote up
def get_iou(gt, prob):
    cross = np.multiply(gt, prob)
    unite = gt + prob
    unite[unite >= 1] = 1
    union = np.sum(unite)
    inter = np.sum(cross)
    if (union != 0):
        iou = inter * 1.0 / union
        if (np.sum(gt) == 0):
            iou = -1
    else:
        iou = -10
    return iou 
Example 31
Source File: analyze.py    From TensorVision with MIT License 5 votes vote down vote up
def get_mean_iou(n):
    """
    Get mean intersection over union from a confusion matrix n.

    Parameters
    ----------
    n : dict
        Confusion matrix which has integer keys 0, ..., nb_classes - 1;
        an entry n[i][j] is the count how often class i was classified as
        class j.

    Returns
    -------
    float
        mean intersection over union (in [0, 1])

    Examples
    --------
    >>> n = {0: {0: 10, 1: 2}, 1: {0: 5, 1: 83}}
    >>> get_mean_iou(n)
    0.7552287581699346
    """
    t = []
    k = len(n[0])
    for i in range(k):
        t.append(sum([n[i][j] for j in range(k)]))
    return (1.0 / k) * sum([float(n[i][i]) / (t[i] - n[i][i] +
                            sum([n[j][i] for j in range(k)]))
                            for i in range(k)]) 
Example 32
Source File: analyze.py    From TensorVision with MIT License 5 votes vote down vote up
def get_frequency_weighted_iou(n):
    """
    Get frequency weighted intersection over union.

    Parameters
    ----------
    n : dict
        Confusion matrix which has integer keys 0, ..., nb_classes - 1;
        an entry n[i][j] is the count how often class i was classified as
        class j.

    Returns
    -------
    float
        frequency weighted iou (in [0, 1])

    Examples
    --------
    >>> n = {0: {0: 10, 1: 2}, 1: {0: 5, 1: 83}}
    >>> get_frequency_weighted_iou(n)
    0.8821437908496732
    """
    t = []
    k = len(n[0])
    for i in range(k):
        t.append(sum([n[i][j] for j in range(k)]))
    a = sum(t)**(-1)
    b = sum([(t[i] * n[i][i]) /
             (t[i] - n[i][i] + sum([n[j][i] for j in range(k)]))
             for i in range(k)])
    return a * b 
Example 33
Source File: level2_features.py    From kaggle-kuzushiji-2019 with MIT License 5 votes vote down vote up
def get_max_iou(item, boxes):
    boxes = boxes[boxes[:, 4] != item.Index]  # exclude self
    if boxes.shape[0] == 0:
        return 0
    x1, y1, x2, y2 = (boxes[:, i] for i in range(4))
    area = (x2 - x1 + 1) * (y2 - y1 + 1)
    xx1 = np.maximum(item.x, x1)
    yy1 = np.maximum(item.y, y1)
    xx2 = np.minimum(item.x + item.w, x2)
    yy2 = np.minimum(item.y + item.h, y2)
    w = np.maximum(0, xx2 - xx1 + 1)
    h = np.maximum(0, yy2 - yy1 + 1)
    overlap = (w * h) / area
    return overlap.max() 
Example 34
Source File: tools_pcl.py    From argoverse_baselinetracker with MIT License 5 votes vote down vote up
def get_iou(b1, b2):

    # import pdb; pdb.set_trace()
    b1_c = bbox_to_contour(b1)
    b2_c = bbox_to_contour(b2)

    inter_area = b1_c.intersection(b2_c).area
    union_area = b1_c.area + b2_c.area - inter_area

    return inter_area / union_area 
Example 35
Source File: metrics.py    From Multiple-Object-Forecasting with MIT License 5 votes vote down vote up
def get_iou(bboxes1, bboxes2):
    """
    Adapted from https://gist.github.com/zacharybell/8d9b1b25749fe6494511f843361bb167
    Calculates the intersection-over-union of two bounding boxes.
    Args:
        bbox1 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2.
        bbox2 (numpy.array, list of floats): bounding box in format x1,y1,x2,y2.
    Returns:
        int: intersection-over-onion of bbox1, bbox2
    """
    ious = []
    for bbox1, bbox2 in zip(bboxes1, bboxes2):
        bbox1 = [float(x) for x in bbox1]
        bbox2 = [float(x) for x in bbox2]
        (x0_1, y0_1, x1_1, y1_1) = bbox1
        (x0_2, y0_2, x1_2, y1_2) = bbox2
        # get the overlap rectangle
        overlap_x0 = max(x0_1, x0_2)
        overlap_y0 = max(y0_1, y0_2)
        overlap_x1 = min(x1_1, x1_2)
        overlap_y1 = min(y1_1, y1_2)
        # check if there is an overlap
        if overlap_x1 - overlap_x0 <= 0 or overlap_y1 - overlap_y0 <= 0:
            ious.append(0)
            continue
        # if yes, calculate the ratio of the overlap to each ROI size and the unified size
        size_1 = (x1_1 - x0_1) * (y1_1 - y0_1)
        size_2 = (x1_2 - x0_2) * (y1_2 - y0_2)
        size_intersection = (overlap_x1 - overlap_x0) * (overlap_y1 - overlap_y0)
        size_union = size_1 + size_2 - size_intersection
        iou = size_intersection / size_union
        ious.append(iou)
    return ious 
Example 36
Source File: metrics.py    From image-segmentation-keras with MIT License 5 votes vote down vote up
def get_iou(gt, pr, n_classes):
    class_wise = np.zeros(n_classes)
    for cl in range(n_classes):
        intersection = np.sum((gt == cl)*(pr == cl))
        union = np.sum(np.maximum((gt == cl), (pr == cl)))
        iou = float(intersection)/(union + EPS)
        class_wise[cl] = iou
    return class_wise 
Example 37
Source File: utils.py    From pvcnn with MIT License 5 votes vote down vote up
def get_box_iou_3d(corners_1, corners_t):
    """
    calculate iou of 3d box
    :param corners_1: FloatTensor[B, 3, 8], assume up direction is negative Y
    :param corners_t: FloatTensor[B, 3, 8], assume up direction is negative Y
        NOTE: corner points are in counter clockwise order, e.g.,
          2--1
        3--0 5
        7--4
    :return:
        iou_3d: 3D bounding box IoU, FloatTensor[B]
        iou_2d: bird's eye view 2D bounding box IoU, FloatTensor[B]
    """
    if corners_1.ndim == 3:
        batch_size = corners_1.shape[0]
        iou_3d = np.zeros(batch_size)
        iou_2d = np.zeros(batch_size)
        for b in range(batch_size):
            iou_3d[b], iou_2d[b] = get_box_iou_3d(corners_1[b], corners_t[b])
        return iou_3d, iou_2d
    else:
        # corner points are in counter clockwise order
        corners_1_upper_xz = [(corners_1[0, 3], corners_1[2, 3]), (corners_1[0, 2], corners_1[2, 2]),
                              (corners_1[0, 1], corners_1[2, 1]), (corners_1[0, 0], corners_1[2, 0])]
        corners_t_upper_xz = [(corners_t[0, 3], corners_t[2, 3]), (corners_t[0, 2], corners_t[2, 2]),
                              (corners_t[0, 1], corners_t[2, 1]), (corners_t[0, 0], corners_t[2, 0])]
        area_1 = poly_area(np.array(corners_1_upper_xz))
        area_2 = poly_area(np.array(corners_t_upper_xz))
        inter, inter_area = convex_hull_intersection(corners_1_upper_xz, corners_t_upper_xz)
        iou_2d = inter_area / (area_1 + area_2 - inter_area)
        y_max = min(corners_1[1, 0], corners_t[1, 0])
        y_min = max(corners_1[1, 4], corners_t[1, 4])
        inter_vol = inter_area * max(0.0, y_max - y_min)
        vol1 = box_volume_3d(corners_1)
        vol2 = box_volume_3d(corners_t)
        iou_3d = inter_vol / (vol1 + vol2 - inter_vol)
        return iou_3d, iou_2d 
Example 38
Source File: scoring.py    From waldo with Apache License 2.0 5 votes vote down vote up
def get_iou_from_csvs(gt_csv, pred_csv):
    """
    This function accepts two csv filenames that have been written in a specific format.
    The first argument represents the groud truth csv file and the second represents the
    segmentation results generated by segment.py. 
    It returns a iou dictionary, where the key is the image_id, and the value is a matrix
    called iou_matrix. iou_matrix is a i by j matrix, where i and j is the number of objects in
    the predicted mask and ground truth mask respectiveluy. So iou_matrix[i, j] is the iou
    of object i in predicted mask and object j in ground truth mask. 
    """
    iou_dict = {}
    gt_dict = read_csv_as_dict(gt_csv)
    pred_dict = read_csv_as_dict(pred_csv)
    for image_id in gt_dict:
        if image_id not in pred_dict:
            raise ValueError(
                'All images need to be segmented but now miss: {}'.format(image_id))
        else:
            gt_rles = gt_dict[image_id]
            pred_rles = pred_dict[image_id]
            iou_matrix = np.zeros((len(pred_rles), len(gt_rles)))
            for i, pred_rle in enumerate(pred_rles):
                for j, gt_rle in enumerate(gt_rles):
                    iou_matrix[i, j] = compute_iou(pred_rle, gt_rle)
            iou_dict[image_id] = iou_matrix
    return iou_dict 
Example 39
Source File: metric.py    From DABNet with MIT License 5 votes vote down vote up
def get_iou(data_list, class_num, save_path=None):
    """ 
    Args:
      data_list: a list, its elements [gt, output]
      class_num: the number of label
    """
    from multiprocessing import Pool

    ConfM = ConfusionMatrix(class_num)
    f = ConfM.generateM
    pool = Pool()
    m_list = pool.map(f, data_list)
    pool.close()
    pool.join()

    for m in m_list:
        ConfM.addM(m)

    aveJ, j_list, M = ConfM.jaccard()
    # print(j_list)
    # print(M)
    # print('meanIOU: ' + str(aveJ) + '\n')

    if save_path:
        with open(save_path, 'w') as f:
            f.write('meanIOU: ' + str(aveJ) + '\n')
            f.write(str(j_list) + '\n')
            f.write(str(M) + '\n')
    return aveJ, j_list