python 如何计算 dice 系数以衡量图像分割的准确性

How to calculate dice coefficient for measuring accuracy of image segmentation in python

我有一张土地覆盖图像,并使用 K 均值聚类对其进行了分割。现在我想计算我的分割算法的准确性。我在某处读到骰子系数是实质性评估指标。但我不确定如何计算它。 我用 Python 2.7 还有其他有效的评估方法吗?请提供摘要或 link 来源。谢谢!

编辑: 我使用以下代码来测量原始图像和分割图像的骰子相似度,但计算起来似乎需要几个小时:

for i in xrange(0,7672320):
  for j in xrange(0,3):
    dice = np.sum([seg==gt])*2.0/(np.sum(seg)+np.sum(gt)) #seg is the segmented image and gt is the original image. Both are of same size

请参考wiki

处的骰子相似系数

这里有一个示例代码段供您参考。请注意,由于您使用的是 k-means,因此您需要将 k 替换为您想要的集群。

import numpy as np

k=1

# segmentation
seg = np.zeros((100,100), dtype='int')
seg[30:70, 30:70] = k

# ground truth
gt = np.zeros((100,100), dtype='int')
gt[30:70, 40:80] = k

dice = np.sum(seg[gt==k])*2.0 / (np.sum(seg) + np.sum(gt))

print 'Dice similarity score is {}'.format(dice)

如果您使用的内容超过 2 类(又名,带有 1 和 0 的掩码),这是一个重要的说明。

如果您使用多个 类,请确保指定预测和基本事实也等于您想要的值。否则,您最终可能会得到大于 1 的 DSC 值。

这是每个 [] 语句末尾的额外 ==k

import numpy as np

k=1

# segmentation
seg = np.zeros((100,100), dtype='int')
seg[30:70, 30:70] = k

# ground truth
gt = np.zeros((100,100), dtype='int')
gt[30:70, 40:80] = k

dice = np.sum(seg[gt==k]==k)*2.0 / (np.sum(seg[seg==k]==k) + np.sum(gt[gt==k]==k))

print 'Dice similarity score is {}'.format(dice)

如果您正在使用 opencv,您可以使用以下函数:

import cv2
import numpy as np

#load images
y_pred = cv2.imread('predictions/image_001.png')
y_true = cv2.imread('ground_truth/image_001.png') 

# Dice similarity function
def dice(pred, true, k = 1):
    intersection = np.sum(pred[true==k]) * 2.0
    dice = intersection / (np.sum(pred) + np.sum(true))
    return dice

dice_score = dice(y_pred, y_true, k = 255) #255 in my case, can be 1 
print ("Dice Similarity: {}".format(dice_score))

如果您想在使用 tensorflow 的深度学习模型中使用此指标进行评估,您可以使用以下内容:

def dice_coef(y_true, y_pred):
    y_true_f = tf.reshape(tf.dtypes.cast(y_true, tf.float32), [-1])
    y_pred_f = tf.reshape(tf.dtypes.cast(y_pred, tf.float32), [-1])
    intersection = tf.reduce_sum(y_true_f * y_pred_f)
    return (2. * intersection + 1.) / (tf.reduce_sum(y_true_f) + tf.reduce_sum(y_pred_f) + 1.)