利用 python/keras/tensorflow 计算 DICE系数,评估 3D 分割结果

有 200幅 分割图像和其对应的 ground truth,现利用 python 语言计算 DICE 系数,评估分割结果

import nibabel as nib
import scipy.io as io
import os
import numpy as np
import tensorflow as tf
from keras import backend as K


def dice_coefficient(y_true, y_pred, smooth=0.00001):
    y_true_f = K.flatten(y_true)
    y_pred_f = K.flatten(y_pred)
    intersection = K.sum(y_true_f * y_pred_f)
    return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)

pred_dir = '/home/share/name/20200206_test_labeled/code/pred_result'
true_dir = '/home/share/name/20200206_test_labeled/mask'
pred_filenames = os.listdir(pred_dir)
pred_filenames.sort(key=lambda x:x[:-9])

true_filenames = os.listdir(true_dir)
true_filenames.sort(key=lambda x:x[:-8])

dice_value = np.zeros(200)
temp = []
for f in range(200):
    pred_path = os.path.join(pred_dir, pred_filenames[f])
    img_pred = nib.load(pred_path)
    y_pred = img_pred.get_fdata()
    true_path = os.path.join(true_dir, true_filenames[f])
    img_true = nib.load(true_path)
    y_true = img_true.get_fdata()
    temp.append(dice_coefficient(y_true, y_pred))
    pass


with tf.Session() as sess:
    dice_value = sess.run(temp)
    pass

mat_path = '/home/share/name/20200206_test_labeled/DICE_value.mat'
io.savemat(mat_path, {'DICE_value': dice_value})

 

你可能感兴趣的:(python,code)