【问题标题】:How calculate the dice coefficient for multi-class segmentation task using Python?如何使用 Python 计算多类分割任务的骰子系数?
【发布时间】:2020-08-12 18:29:01
【问题描述】:

我想知道如何计算多类分割的骰子系数。

这是计算二元分割任务骰子系数的脚本。如何遍历每个班级并计算每个班级的骰子?

提前谢谢你

import numpy 



def dice_coeff(im1, im2, empty_score=1.0):

    im1 = numpy.asarray(im1).astype(numpy.bool)
    im2 = numpy.asarray(im2).astype(numpy.bool)

    if im1.shape != im2.shape:
        raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")

    im_sum = im1.sum() + im2.sum()
    if im_sum == 0:
        return empty_score

    # Compute Dice coefficient
    intersection = numpy.logical_and(im1, im2)

    return (2. * intersection.sum() / im_sum)

【问题讨论】:

    标签: pytorch dice semantic-segmentation


    【解决方案1】:

    您可以对二元类使用 dice_score,然后对所有类重复使用二元映射以获得多类骰子分数。

    我假设您的图像/分割图格式为 (batch/index of image, height, width, class_map)

    import numpy as np
    import matplotlib.pyplot as plt
    
    def dice_coef(y_true, y_pred):
        y_true_f = y_true.flatten()
        y_pred_f = y_pred.flatten()
        intersection = np.sum(y_true_f * y_pred_f)
        smooth = 0.0001
        return (2. * intersection + smooth) / (np.sum(y_true_f) + np.sum(y_pred_f) + smooth)
    
    def dice_coef_multilabel(y_true, y_pred, numLabels):
        dice=0
        for index in range(numLabels):
            dice += dice_coef(y_true[:,:,:,index], y_pred[:,:,:,index])
        return dice/numLabels # taking average
    
    num_class = 5
    
    imgA = np.random.randint(low=0, high= 2, size=(5, 64, 64, num_class) ) # 5 images in batch, 64 by 64, num_classes map
    imgB = np.random.randint(low=0, high= 2, size=(5, 64, 64, num_class) )
    
    
    plt.imshow(imgA[0,:,:,0]) # for 0th image, class 0 map
    plt.show()
    
    plt.imshow(imgB[0,:,:,0]) # for 0th image, class 0 map
    plt.show()
    
    dice_score = dice_coef_multilabel(imgA, imgB, num_class)
    print(f'For A and B {dice_score}')
    
    dice_score = dice_coef_multilabel(imgA, imgA, num_class)
    print(f'For A and A {dice_score}')
    

    【讨论】:

      猜你喜欢
      • 2018-04-15
      • 2022-07-25
      • 2021-07-07
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      • 2022-09-24
      • 2020-08-29
      • 2019-03-04
      相关资源
      最近更新 更多