|
|
|
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 |
|
|