[ebf7be]: / code / preprocessing.py

Download this file

190 lines (152 with data), 7.1 kB

  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
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
"""
Preprocessing for U-net
Thresholding and mask the lung part
Use annotation to mask the nodules
"""
import numpy as np
import pandas as pd
import os
from skimage.segmentation import clear_border
from skimage.measure import label,regionprops, perimeter
from skimage.morphology import ball, disk, dilation, binary_erosion, remove_small_objects, erosion, closing, reconstruction, binary_closing
from skimage.filters import roberts, sobel
from scipy import ndimage as ndi
from glob import glob
from tqdm import tqdm
import SimpleITK as sitk
import scipy.misc
import matplotlib.pyplot as plt
def get_segmented_lungs(im, plot=False):
binary = im < 604
cleared = clear_border(binary)
label_image = label(cleared)
areas = [r.area for r in regionprops(label_image)]
areas.sort()
if len(areas) > 2:
for region in regionprops(label_image):
if region.area < areas[-2]:
for coordinates in region.coords:
label_image[coordinates[0], coordinates[1]] = 0
binary = label_image > 0
selem = disk(2)
binary = binary_erosion(binary, selem)
selem = disk(10)
binary = binary_closing(binary, selem)
edges = roberts(binary)
binary = ndi.binary_fill_holes(edges)
get_high_vals = binary == 0
im[get_high_vals] = 0
return im
def segment_lung_from_ct_scan(ct_scan):
return np.asarray([get_segmented_lungs(slice) for slice in ct_scan])
def load_itk(filename):
itkimage = sitk.ReadImage(filename)
ct_scan = sitk.GetArrayFromImage(itkimage)
origin = np.array(list(reversed(itkimage.GetOrigin())))
spacing = np.array(list(reversed(itkimage.GetSpacing())))
return ct_scan, origin, spacing
def world_2_voxel(world_coordinates, origin, spacing):
stretched_voxel_coordinates = np.absolute(world_coordinates - origin)
voxel_coordinates = stretched_voxel_coordinates / spacing
return voxel_coordinates
def voxel_2_world(voxel_coordinates, origin, spacing):
stretched_voxel_coordinates = voxel_coordinates * spacing
world_coordinates = stretched_voxel_coordinates + origin
return world_coordinates
def seq(start, stop, step=1):
n = int(round((stop - start)/float(step)))
if n > 1:
return([start + step*i for i in range(n+1)])
else:
return([])
def draw_circles(image,cands,origin,spacing):
#make empty matrix, which will be filled with the mask
RESIZE_SPACING = [1, 1, 1]
image_mask = np.zeros(image.shape)
#run over all the nodules in the lungs
for ca in cands.values:
#get middel x-,y-, and z-worldcoordinate of the nodule
radius = np.ceil(ca[4])/2
coord_x = ca[1]
coord_y = ca[2]
coord_z = ca[3]
image_coord = np.array((coord_z,coord_y,coord_x))
#determine voxel coordinate given the worldcoordinate
image_coord = world_2_voxel(image_coord,origin,spacing)
#determine the range of the nodule
noduleRange = seq(-radius, radius, RESIZE_SPACING[0])
#create the mask
for x in noduleRange:
for y in noduleRange:
for z in noduleRange:
coords = world_2_voxel(np.array((coord_z+z,coord_y+y,coord_x+x)),origin,spacing)
if (np.linalg.norm(image_coord-coords) * RESIZE_SPACING[0]) < radius:
image_mask[int(np.round(coords[0])),int(np.round(coords[1])),int(np.round(coords[2]))] = int(1)
return image_mask
def create_nodule_mask(imagePath, cands, fcount, subsetnum,final_lung_mask,final_nodule_mask):
#if os.path.isfile(imagePath.replace('original',SAVE_FOLDER_image)) == False:
img, origin, spacing = load_itk(imagePath)
#calculate resize factor
RESIZE_SPACING = [1, 1, 1]
resize_factor = spacing / RESIZE_SPACING
new_real_shape = img.shape * resize_factor
new_shape = np.round(new_real_shape)
real_resize = new_shape / img.shape
new_spacing = spacing / real_resize
#resize image
lung_img = scipy.ndimage.interpolation.zoom(img, real_resize)
# Segment the lung structure
lung_img = lung_img + 1024
lung_mask = segment_lung_from_ct_scan(lung_img)
lung_img = lung_img - 1024
#create nodule mask
nodule_mask = draw_circles(lung_img,cands,origin,new_spacing)
lung_img_512, lung_mask_512, nodule_mask_512 = np.zeros((lung_img.shape[0], 512, 512)), np.zeros((lung_mask.shape[0], 512, 512)), np.zeros((nodule_mask.shape[0], 512, 512))
original_shape = lung_img.shape
i_start = 0
i_end = 0
flag = 0
for z in range(lung_img.shape[0]):
offset = (512 - original_shape[1])
upper_offset = int(np.round(offset/2))
lower_offset = int(offset - upper_offset)
new_origin = voxel_2_world([-upper_offset,-lower_offset,0],origin,new_spacing)
lung_mask_512[z, upper_offset:-lower_offset,upper_offset:-lower_offset] = lung_mask[z,:,:]
nodule_mask_512[z, upper_offset:-lower_offset,upper_offset:-lower_offset] = nodule_mask[z,:,:]
# return final_lung_mask,final_nodule_mask
# save images.
np.save(os.path.join(OUTPUT_PATH,"lung_mask_%04d_%04d.npy" % (subsetnum, fcount)),lung_mask_512)
np.save(os.path.join(OUTPUT_PATH,"nodule_mask_%04d_%04d.npy" % (subsetnum, fcount)),nodule_mask_512)
# Helper function to get rows in data frame associated with each file
def get_filename(file_list, case):
for f in file_list:
if case in f:
return(f)
# Getting list of image files
LUNA_DATA_PATH = '/home/marshallee/Documents/lung/'
OUTPUT_PATH = '/home/marshallee/Documents/lung/output'
final_lung_mask = np.zeros((1,512,512))
final_nodule_mask = np.zeros((1,512,512))
# create a list of subsets, which are lists of file paths
FILE_LIST = []
for i in range(0, 9):
LUNA_SUBSET_PATH = LUNA_DATA_PATH + 'subset'+str(i)+'/'
FILE_LIST.append(glob(LUNA_SUBSET_PATH + '*.mhd'))
for subsetnum, subsetlist in enumerate(FILE_LIST):
# The locations of the nodes
df_node = pd.read_csv(LUNA_DATA_PATH + "mask-generate/CSVFILES/annotations.csv")
#df_node = pd.read_csv(LUNA_DATA_PATH + "CSVFILES/annotations.csv")
df_node["file"] = df_node["seriesuid"].map(lambda file_name: get_filename(subsetlist, file_name))
df_node = df_node.dropna()
# Looping over the image files
for fcount, img_file in enumerate(tqdm(subsetlist)):
mini_df = df_node[df_node["file"]==img_file] # get all nodules associate with file
if mini_df.shape[0]>0: # some files may not have a nodule--skipping those
# feeding mini_df to the function will work for "cands"
final_lung_mask, final_nodule_mask =create_nodule_mask(img_file, mini_df, fcount, subsetnum,final_lung_mask,final_nodule_mask)
final_lung_mask = final_lung_mask[1:]
final_nodule_mask = final_nodule_mask[1:]
print(final_lung_mask.shape)
print(final_nodule_mask.shape)
np.save(os.path.join(OUTPUT_PATH,'final_lung_mask.npy'),final_lung_mask)
np.save(os.path.join(OUTPUT_PATH,'final_nodule_mask.npy'),final_nodule_mask)