-
Notifications
You must be signed in to change notification settings - Fork 44
/
utils.py
68 lines (61 loc) · 2.3 KB
/
utils.py
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import argparse
import os
import numpy as np
from medpy.filter.smoothing import anisotropic_diffusion
from scipy.ndimage import median_filter
from skimage import measure, morphology
import scipy.ndimage as ndimage
from sklearn.cluster import KMeans
def is_dir_path(string):
if os.path.isdir(string):
return string
else:
raise NotADirectoryError(string)
def segment_lung(img):
#function sourced from https://www.kaggle.com/c/data-science-bowl-2017#tutorial
"""
This segments the Lung Image(Don't get confused with lung nodule segmentation)
"""
mean = np.mean(img)
std = np.std(img)
img = img-mean
img = img/std
middle = img[100:400,100:400]
mean = np.mean(middle)
max = np.max(img)
min = np.min(img)
#remove the underflow bins
img[img==max]=mean
img[img==min]=mean
#apply median filter
img= median_filter(img,size=3)
#apply anistropic non-linear diffusion filter- This removes noise without blurring the nodule boundary
img= anisotropic_diffusion(img)
kmeans = KMeans(n_clusters=2).fit(np.reshape(middle,[np.prod(middle.shape),1]))
centers = sorted(kmeans.cluster_centers_.flatten())
threshold = np.mean(centers)
thresh_img = np.where(img<threshold,1.0,0.0) # threshold the image
eroded = morphology.erosion(thresh_img,np.ones([4,4]))
dilation = morphology.dilation(eroded,np.ones([10,10]))
labels = measure.label(dilation)
label_vals = np.unique(labels)
regions = measure.regionprops(labels)
good_labels = []
for prop in regions:
B = prop.bbox
if B[2]-B[0]<475 and B[3]-B[1]<475 and B[0]>40 and B[2]<472:
good_labels.append(prop.label)
mask = np.ndarray([512,512],dtype=np.int8)
mask[:] = 0
#
# The mask here is the mask for the lungs--not the nodes
# After just the lungs are left, we do another large dilation
# in order to fill in and out the lung mask
#
for N in good_labels:
mask = mask + np.where(labels==N,1,0)
mask = morphology.dilation(mask,np.ones([10,10])) # one last dilation
# mask consists of 1 and 0. Thus by mutliplying with the orginial image, sections with 1 will remain
return mask*img
def count_params(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)