File size: 1,230 Bytes
64ea7b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# Metrics between masks in numpy
import numpy as np


def dice(img1: np.ndarray, img2: np.ndarray, epsilon=0.00001):
    assert np.min(img1) >= 0.
    assert np.max(img1) <= 1.
    assert np.min(img2) >= 0.
    assert np.max(img2) <= 1.
    return (np.sum(np.multiply(img1, img2)) * 2 + epsilon) / (np.sum(img1) + np.sum(img2) + epsilon)


def harden(img: np.ndarray):
    h_img = np.zeros_like(img, dtype=np.uint8)
    h_img[img > 0.5] = 1
    return h_img

def restrict(m: np.ndarray):
    rm = np.copy(m)
    rm[rm<0]=0.
    rm[rm>1]=1.
    return rm
    
def check_mask(m):
    if np.min(m) < 0.:
        print("WARNING: Mask contains pixels below 0, constraining it to be over 0")
    if np.max(m) > 1.:
        print("WARNING: Mask contains pixels over 1, constraining them to be below 1")
    assert np.min(m) >= 0.
    assert np.max(m) <= 1.
    
def hard_dice(img1: np.ndarray, img2: np.ndarray, epsilon=0.00001):
    check_mask(img1)
    check_mask(img2)
    return dice(harden(img1), harden(img2), epsilon)


def rel_size_diff(img_r: np.ndarray, img: np.ndarray, epsilon=0.00001):
    
    assert np.min(img) >= 0.
    assert np.max(img) <= 1.
    s_r = np.sum(img_r)
    s = np.sum(img)
    return np.abs(s_r-s) / s_r