Python compute miou

8 Python code examples are found related to " compute miou". 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: train.py    From nnabla-examples with Apache License 2.0 7 votes vote down vote up
def compute_miou(num_classes, gt, pred, mask):

    gt = np.squeeze(np.transpose(gt, (1, 0, 2, 3)), axis=0)
    gt = gt.reshape(gt.shape[0], gt.shape[1]*gt.shape[2])
    gt = one_hot_encode(gt, num_classes)

    pred = pred.reshape(pred.shape[0], pred.shape[1]*pred.shape[2])
    pred = one_hot_encode(pred, num_classes)

    # Now, gt: [B, P, C] ; pred: [B, P, C]
    mask = np.squeeze(np.transpose(mask, (1, 0, 2, 3)), axis=0)
    mask = mask.reshape(mask.shape[0], mask.shape[1]
                        * mask.shape[2])  # mask: [B, P]
    mask = mask[..., None]

    # gt: [B, P, C], mask: [B, P, 1]
    numer = np.sum(np.logical_and(gt, pred) * mask, axis=1)
    denom = np.sum(np.logical_or(gt, pred) * mask, axis=1)
    iou = numer / np.maximum(denom, 1)

    cat_mask = np.max(gt, axis=1)
    iou_per_image = np.sum(iou * cat_mask, axis=1) / np.sum(cat_mask, axis=1)
    miou = np.mean(iou_per_image)

    return miou.mean() 
Example 2
Source File: eval.py    From Pointnet2.ScanNet with MIT License 6 votes vote down vote up
def compute_miou(coords, preds, targets, weights):
    coords, preds, targets, weights = filter_points(coords, preds, targets, weights)
    seen_classes = np.unique(targets)
    mask = np.zeros(CONF.NUM_CLASSES)
    mask[seen_classes] = 1

    pointmiou = np.zeros(CONF.NUM_CLASSES)
    voxmiou = np.zeros(CONF.NUM_CLASSES)

    uvidx, uvlabel, _ = point_cloud_label_to_surface_voxel_label_fast(coords, np.concatenate((np.expand_dims(targets,1),np.expand_dims(preds,1)),axis=1), res=0.02)
    for l in seen_classes:
        target_label = np.arange(targets.shape[0])[targets==l]
        pred_label = np.arange(preds.shape[0])[preds==l]
        num_intersection_label = np.intersect1d(pred_label, target_label).shape[0]
        num_union_label = np.union1d(pred_label, target_label).shape[0]
        pointmiou[l] = num_intersection_label / (num_union_label + 1e-8)

        target_label_vox = uvidx[(uvlabel[:, 0] == l)]
        pred_label_vox = uvidx[(uvlabel[:, 1] == l)]
        num_intersection_label_vox = np.intersect1d(pred_label_vox, target_label_vox).shape[0]
        num_union_label_vox = np.union1d(pred_label_vox, target_label_vox).shape[0]
        voxmiou[l] = num_intersection_label_vox / (num_union_label_vox + 1e-8)

    return pointmiou, voxmiou, mask 
Example 3
Source File: evaluation.py    From SPFN with MIT License 5 votes vote down vote up
def compute_miou_loss(W, I_gt, matching_indices):
    # W - BxNxK
    # I_gt - BxN
    W_reordered = batched_gather(W, indices=matching_indices, axis=2) # BxNxK
    depth = tf.shape(W)[2]
    # notice in tf.one_hot, -1 will result in a zero row, which is what we want
    W_gt = tf.one_hot(I_gt, depth=depth, dtype=tf.float32) # BxNxK
    dot = tf.reduce_sum(W_gt * W_reordered, axis=1) # BxK
    denominator = tf.reduce_sum(W_gt, axis=1) + tf.reduce_sum(W_reordered, axis=1) - dot
    mIoU = dot / (denominator + DIVISION_EPS) # BxK
    return 1.0 - mIoU 
Example 4
Source File: CLAN_iou.py    From CLAN with MIT License 5 votes vote down vote up
def compute_mIoU(gt_dir, pred_dir, devkit_dir=''):
    """
    Compute IoU given the predicted colorized images and 
    """
    with open(join(devkit_dir, 'info.json'), 'r') as fp:
      info = json.load(fp)
    num_classes = np.int(info['classes'])
    print('Num classes', num_classes)
    name_classes = np.array(info['label'], dtype=np.str)
    mapping = np.array(info['label2train'], dtype=np.int)
    hist = np.zeros((num_classes, num_classes))

    image_path_list = join(devkit_dir, 'val.txt')
    label_path_list = join(devkit_dir, 'label.txt')
    gt_imgs = open(label_path_list, 'r').read().splitlines()
    gt_imgs = [join(gt_dir, x) for x in gt_imgs]
    pred_imgs = open(image_path_list, 'r').read().splitlines()
    pred_imgs = [join(pred_dir, x.split('/')[-1]) for x in pred_imgs]

    for ind in range(len(gt_imgs)):
        pred = np.array(Image.open(pred_imgs[ind]))
        label = np.array(Image.open(gt_imgs[ind]))
        label = label_mapping(label, mapping)
        if len(label.flatten()) != len(pred.flatten()):
            print('Skipping: len(gt) = {:d}, len(pred) = {:d}, {:s}, {:s}'.format(len(label.flatten()), len(pred.flatten()), gt_imgs[ind], pred_imgs[ind]))
            continue
        hist += fast_hist(label.flatten(), pred.flatten(), num_classes)
        if ind > 0 and ind % 10 == 0:
            print('{:d} / {:d}: {:0.2f}'.format(ind, len(gt_imgs), 100*np.mean(per_class_iu(hist))))
    
    mIoUs = per_class_iu(hist)
    for ind_class in range(num_classes):
        print('===>' + name_classes[ind_class] + ':\t' + str(round(mIoUs[ind_class] * 100, 2)))
    print('===> mIoU: ' + str(round(np.nanmean(mIoUs) * 100, 2)))
    return mIoUs 
Example 5
Source File: mIoU_tf.py    From Simple-does-it-weakly-supervised-instance-and-semantic-segmentation with Apache License 2.0 5 votes vote down vote up
def compute_mIoU(self):
        union_ = np.zeros(self.classes, dtype=int)
        inter_ = np.zeros(self.classes, dtype=int)
        in_, un_ = compute()
        sess = tf.Session()
        with open(self.dataset + '/' + self.set_name, 'r') as r:
            for i, img_name in enumerate(tqdm.tqdm(r,
                                                   desc='{:{}}'.format(
                                                       'Load image', SPACE),
                                                   unit_scale=UNIT_SCALE),
                                         start=1):
                # get image name
                img_name = img_name.rstrip()
                # get Ground Truth
                GT = Image.open(self.dataset + '/' + self.GT_dir_name + '/' +
                                img_name + '.png')
                GT = np.array(GT)
                GT = np.where((GT == 255), 0, GT)
                # get prediction
                Pred = Image.open(self.dataset + '/' + self.Pred_dir_name + '/'
                                  + img_name + '.png')
                Pred = np.array(Pred)
                for i in range(self.classes):
                    target = np.where((GT == i), 1, 0)
                    pred = np.where((Pred == i), 1, 0)
                    in__, un__ = sess.run([in_, un_], feed_dict={x: pred,
                                                                 y: target})
                    union_[i] = union_[i] + un__
                    inter_[i] = inter_[i] + in__
        # compute IoU
        IoU = inter_/union_
        print('{:{}}: {}'.format('Set', SPACE, self.set_name))
        for k, v in zip(voc12_class.voc12_classes.keys(), IoU):
            print('{:{}}: {}'.format(k, SPACE, v))
        # count mIoU
        mIoU = np.mean(IoU)

        print('{:{}}: {}'.format('mIoU', SPACE, mIoU))
        return mIoU 
Example 6
Source File: miou_scenario_runner.py    From pylot with Apache License 2.0 5 votes vote down vote up
def compute_and_log_miou(current_frame, current_timestamp, csv, deadline=210):
    """ Computes the mIOU for the given frame relative to the previous frames
    and logs it to the given csv file.

    Args:
        current_frame: The frame to compute the mIOU for.
        current_timestamp: The timestamp associated with the frame.
        csv: The csv file to write the results to.
    """
    SAVED_FRAMES.append((current_timestamp, current_frame))

    # Remove data older than the deadline that we don't need anymore.
    while (current_timestamp - SAVED_FRAMES[0][0]) * 1000 > deadline:
        SAVED_FRAMES.popleft()

    # Go over each of the saved frames, compute the difference in the
    # timestamp, and the mIOU and log both of them.
    for old_timestamp, old_frame in SAVED_FRAMES:
        (mean_iou, class_iou) = \
            current_frame.compute_semantic_iou_using_masks(old_frame)
        time_diff = current_timestamp - old_timestamp

        # Format of the CSV file: (latency_in_ms, class, mean IOU)
        csv.writerow([time_diff * 1000, "Scene", mean_iou])

        # Insert the results for the person.
        person_key = 4
        if person_key in class_iou:
            csv.writerow([time_diff * 1000, "Person", class_iou[person_key]]) 
Example 7
Source File: evaluation.py    From dhSegment with GNU General Public License v3.0 5 votes vote down vote up
def compute_miou(self):
        self.mIOU = np.mean(self.IOU_list)
        return self.mIOU

    # See http://cdn.iiit.ac.in/cdn/cvit.iiit.ac.in/images/ConferencePapers/2017/DocUsingDeepFeatures.pdf