-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.py
More file actions
219 lines (191 loc) · 10.1 KB
/
data.py
File metadata and controls
219 lines (191 loc) · 10.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
""" Data loader for LTSM-net """
import datetime
import pandas as pd
from sklearn.utils import class_weight
import os
from tensorflow.keras.preprocessing import image as krs
from tensorflow.keras import applications as mn
from PIL import Image , ImageOps
import random
import numpy as np
# write user-defined parameters to file
#with open(os.path.join(log_dir, 'params.txt'), 'w') as f:
# print(args, file=f)
#with open(os.path.join(log_dir, 'params.txt'), 'a') as f:
# print(os.path.basename(sys.argv[0]), file=f)
def us_generator(dataframe, img_path, msk_path, batch_size, imdimensions=(512,512)):
# for each sample, list image name and calculate class weights
images_list = dataframe.index.tolist()
#pths_list = dataframe.pths.tolist()
pos_list = dataframe.position.tolist()
dir_list = dataframe.direction.tolist()
pos_weight = class_weight.compute_sample_weight('balanced', pos_list)
dir_weight = class_weight.compute_sample_weight('balanced', dir_list)
# perform initial shuffle
random.Random(30).shuffle(images_list)
random.Random(30).shuffle(pos_weight)
random.Random(30).shuffle(dir_weight)
i = 0
while True:
# preallocate output for this batch
batch_x = {'imagesS': [], 'rotsS': []}
batch_y = {'prostate_out': [], 'direction_out': [], 'segment_out': []}
batch_w = {'prostate_out': [], 'direction_out': []}
# loop through each sample (b) assigned to this batch
b = 0
while b < batch_size:
# refresh shuffle
if i == len(images_list):
i = 0
random.Random(42).shuffle(images_list)
random.Random(42).shuffle(pos_weight)
random.Random(42).shuffle(dir_weight)
if int(images_list[i][-7:-4]) > 9:
filelist = [os.path.join(img_path, images_list[i][:-7]+str(int(images_list[i][-7:-4])-9+n).zfill(3) + images_list[i][-4:]) for n in range(0,10,2)]
masklist = [os.path.join(msk_path, 'msk_'+images_list[i][:-7]+str(int(images_list[i][-7:-4])-9+n).zfill(3) + images_list[i][-4:]) for n in range(0,10,2)]
ixlist = [images_list[i][:-7]+str(int(images_list[i][-7:-4])-9+n).zfill(3) + images_list[i][-4:] for n in range(0,10,2)]
# augmentation parameters
rnd_angle = random.randint(-25, 25)
#rnd_lr = random.randint(0, 1)
#rnd_ud = random.randint(0, 1)
rnd_x = random.randint(-100, -100)
rnd_y = random.randint(-100, 100)
# preassign probe angle vector list
rotfeatures=[]
# load 5 images in sequence
for n in range(5):
# augment images
image1 = krs.load_img(filelist[n],color_mode='rgb', target_size=imdimensions)
image1.rotate(rnd_angle)
image1.transform(image1.size, Image.AFFINE,(1,0,rnd_x,0,1,rnd_y))
# augment masks
if n==4:
mask1 = krs.load_img(masklist[n],color_mode='grayscale', target_size=imdimensions)
mask1.rotate(rnd_angle)
mask1.transform(mask1.size, Image.AFFINE,(1,0,rnd_x,0,1,rnd_y))
# ensure correct range and scaling
mask1 = krs.img_to_array(mask1)
mask1 = np.clip(mask1,0,1)
mask=mask1+1
image1 = krs.img_to_array(image1)
image1 = mn.mobilenet_v2.preprocess_input(image1) # ensure scaling is appropriate to model
if n == 0:
image = np.expand_dims(image1, axis=0)
else:
image1 = np.expand_dims(image1, axis=0)
image = np.concatenate((image, image1))
# assign probe angle vector to sequence
csv_row = dataframe.loc[ixlist[n], :]
rotfeatures.append([csv_row['rot_si'], csv_row['rot_ap'], csv_row['rot_lr']])
# embed probe vectors into array of equal size to images (necessary for TimeDistributed model wrapper)
csv_features = np.array(rotfeatures)
rsz_features = np.concatenate((csv_features, abs(csv_features)), axis=-1)
# record sequence-level labels from csv
csv_row = dataframe.loc[images_list[i], :]
labelPos = np.array([csv_row['outside'], csv_row['periphery'], csv_row['centre']])
labelDir = np.array([csv_row['left'], csv_row['stop'], csv_row['right']])
# record class weights to balance class sizes
wt_pos = pos_weight[i]
wt_dir = dir_weight[i]
# append each record to the batch
batch_x['imagesS'].append(image)
batch_x['rotsS'].append(rsz_features)
batch_y['prostate_out'].append(labelPos)
batch_y['direction_out'].append(labelDir)
batch_y['segment_out'].append(mask)
batch_w['prostate_out'].append(wt_pos)
batch_w['direction_out'].append(wt_dir)
i += 1
b += 1
else:
i += 1
batch_x['imagesS'] = np.array(batch_x['imagesS'])
batch_x['rotsS'] = np.array(batch_x['rotsS'])
batch_y['prostate_out'] = np.array(batch_y['prostate_out'])
batch_y['direction_out'] = np.array(batch_y['direction_out'])
batch_y['segment_out'] = np.array(batch_y['segment_out'])
batch_w['prostate_out'] = np.array(batch_w['prostate_out'])
batch_w['direction_out'] = np.array(batch_w['direction_out'])
yield(batch_x, batch_y, batch_w)
##### non-sequential generator
def us_single(dataframe, img_path, msk_path, batch_size,imdimensions=(640,480)):
# for each sample, list image name and calculate class weights
images_list = dataframe.index.tolist()
#pths_list = dataframe.pths.tolist()
pos_list = dataframe.position.tolist()
dir_list = dataframe.direction.tolist()
pos_weight = class_weight.compute_sample_weight('balanced', pos_list)
dir_weight = class_weight.compute_sample_weight('balanced', dir_list)
# perform initial shuffle
random.Random(30).shuffle(images_list)
random.Random(30).shuffle(pos_weight)
random.Random(30).shuffle(dir_weight)
i = 0
while True:
# preallocate output for this batch
batch_x = {'images': [], 'rots': []}
batch_y = {'prostate_out': [], 'direction_out': [], 'segment_out': []}
batch_w = {'prostate_out': [], 'direction_out': []}
# loop through each sample (b) assigned to this batch
b = 0
while b < batch_size:
# refresh shuffle
if i == len(images_list):
i = 0
random.Random(42).shuffle(images_list)
random.Random(42).shuffle(pos_weight)
random.Random(42).shuffle(dir_weight)
filelist = os.path.join(img_path, images_list[i])
masklist = os.path.join(msk_path, 'msk_'+images_list[i])
ixlist = images_list[i]
# augmentation parameters
rnd_angle = random.randint(-25, 25)
#rnd_lr = random.randint(0, 1)
#rnd_ud = random.randint(0, 1)
rnd_x = random.randint(-100, -100)
rnd_y = random.randint(-100, 100)
# augment images
image1 = (krs.load_img(filelist,color_mode='rgb', target_size=imdimensions))
image1.rotate(rnd_angle)
image1.transform(image1.size, Image.AFFINE,(1,0,rnd_x,0,1,rnd_y))
# augment masks
mask1 = (krs.load_img(masklist,color_mode='grayscale', target_size=imdimensions))
mask1.rotate(rnd_angle)
mask1.transform(mask1.size, Image.AFFINE,(1,0,rnd_x,0,1,rnd_y))
# ensure correct range and scaling
mask1 = krs.img_to_array(mask1)
mask1 = np.clip(mask1,0,1)
mask=mask1+1
image1 = krs.img_to_array(image1)
image = mn.mobilenet_v2.preprocess_input(image1) # ensure scaling is appropriate to model
# assign probe angle vector to sequence
csv_row = dataframe.loc[ixlist, :]
# embed probe vectors into array of equal size to images (necessary for TimeDistributed model wrapper)
csv_features = np.array([csv_row['rot_si'], csv_row['rot_ap'], csv_row['rot_lr']])
rsz_features = np.concatenate((csv_features, abs(csv_features)), axis=-1)
# record sequence-level labels from csv
labelPos = np.array([csv_row['outside'], csv_row['periphery'], csv_row['centre']])
labelDir = np.array([csv_row['left'], csv_row['stop'], csv_row['right']])
# record class weights to balance class sizes
wt_pos = pos_weight[i]
wt_dir = dir_weight[i]
# append each record to the batch
batch_x['images'].append(image)
batch_x['rots'].append(rsz_features)
batch_y['prostate_out'].append(labelPos)
batch_y['direction_out'].append(labelDir)
batch_y['segment_out'].append(mask)
batch_w['prostate_out'].append(wt_pos)
batch_w['direction_out'].append(wt_dir)
i += 1
b += 1
else:
i += 1
batch_x['images'] = np.array(batch_x['images'])
batch_x['rots'] = np.array(batch_x['rots'])
batch_y['prostate_out'] = np.array(batch_y['prostate_out'])
batch_y['direction_out'] = np.array(batch_y['direction_out'])
batch_y['segment_out'] = np.array(batch_y['segment_out'])
batch_w['prostate_out'] = np.array(batch_w['prostate_out'])
batch_w['direction_out'] = np.array(batch_w['direction_out'])
yield(batch_x, batch_y, batch_w)