Diff of /semseg/utils.py [000000] .. [cc8b8f]

Switch to unified view

a b/semseg/utils.py
1
import numpy as np
2
3
4
# from config.paths import train_images_folder, train_labels_folder
5
6
7
def dice_coeff(gt, pred, eps=1e-5):
8
    dice = np.sum(pred[gt == 1]) * 2.0 / (np.sum(pred) + np.sum(gt))
9
    return dice
10
11
12
def multi_dice_coeff(gt, pred, num_classes):
13
    labels = one_hot_encode_np(gt, num_classes)
14
    outputs = one_hot_encode_np(pred, num_classes)
15
    dices = list()
16
    for cls in range(1, num_classes):
17
        outputs_ = outputs[:, cls]
18
        labels_  = labels[:, cls]
19
        dice_ = dice_coeff(outputs_, labels_)
20
        dices.append(dice_)
21
    return sum(dices) / (num_classes-1)
22
23
24
def one_hot_encode_np(label, num_classes):
25
    """ Numpy One Hot Encode
26
    :param label: Numpy Array of shape BxHxW or BxDxHxW
27
    :param num_classes: K classes
28
    :return: label_ohe, Numpy Array of shape BxKxHxW or BxKxDxHxW
29
    """
30
    assert len(label.shape) == 3 or len(label.shape) == 4, 'Invalid Label Shape {}'.format(label.shape)
31
    label_ohe = None
32
    if len(label.shape) == 3:
33
        label_ohe = np.zeros((label.shape[0], num_classes, label.shape[1], label.shape[2]))
34
    elif len(label.shape) == 4:
35
        label_ohe = np.zeros((label.shape[0], num_classes, label.shape[1], label.shape[2], label.shape[3]))
36
    for batch_idx, batch_el_label in enumerate(label):
37
        for cls in range(num_classes):
38
            label_ohe[batch_idx, cls] = (batch_el_label == cls)
39
    return label_ohe
40
41
42
def min_max_normalization(input):
43
    return (input - input.min()) / (input.max() - input.min())
44
45
46
def z_score_normalization(input):
47
    input_mean = np.mean(input)
48
    input_std = np.std(input)
49
    # print("Mean = {:.2f} - Std = {:.2f}".format(input_mean,input_std))
50
    return (input - input_mean)/input_std
51
52
53
def zero_pad_3d_image(image, pad_ref=(64,64,64), value_to_pad = 0):
54
    if value_to_pad == 0:
55
        image_padded = np.zeros(pad_ref)
56
    else:
57
        image_padded = value_to_pad * np.ones(pad_ref)
58
    image_padded[:image.shape[0],:image.shape[1],:image.shape[2]] = image
59
    return image_padded