AI_*_*_NA 4 dice pytorch semantic-segmentation
我想知道如何计算多类分割的骰子系数。
这是计算二元分割任务的骰子系数的脚本。如何循环每个类并计算每个类的骰子?
先感谢您
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)
Run Code Online (Sandbox Code Playgroud)
Zab*_*azi 11
您可以对二进制类使用 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}')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16108 次 |
| 最近记录: |