-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathgenerator.py
190 lines (150 loc) · 6.85 KB
/
generator.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
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
import os
import random
import cv2
import keras
import numpy as np
import constants
import dataset
# TODO use imgaug for more robust image augmentation
def preprocess_input(image, randomVals):
'''
performs data augmentations listed below each with chance == 50%
- Horiontal flip
- Random brightness +- 0.2
- Random contrast +- 0.2
- Random saturation +- 0.2
- Hue Jitter +- 0.1
all random values provided in range (0,1)
'''
if randomVals[0] > 0.5:
# flip image horizontally
#image = np.flip(image, 1)
None
if randomVals[1] > 0.5:
# increase/ decrease contrast
image = np.uint8(np.clip(image * (0.8 + randomVals[2]/2.5), a_min=0, a_max=255))
# Convert image to HSV for some transformations
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV).astype(np.int32)
if randomVals[3] > 0.5:
# change brightness of image
hsv_image[:,:,2] += int(((randomVals[4]/2.5 )- 0.2 ) * 255.)
hsv_image[:,:,2] = np.clip(hsv_image[:,:,2], a_min =0, a_max = 255)
if randomVals[5] > 0.5:
# change staturation
hsv_image[:,:,1] += int(((randomVals[6]/2.5 )- 0.2 ) * 255.)
hsv_image[:,:,1] = np.clip(hsv_image[:,:,1], a_min = 0, a_max = 255)
if randomVals[7] > 0.5:
# change Hue
hsv_image[:,:,0] += int(((randomVals[8]/2.5 )- 0.2 ) * 179.)
hsv_image[:,:,0] = np.clip(hsv_image[:,:,0], a_min = 0, a_max = 179)
# Convert image back from HSV
image = cv2.cvtColor(np.uint8(hsv_image), cv2.COLOR_HSV2BGR)
return image
#for x in range(0,9):
# randomVals.append(random.random())
#input_img = preprocess_input(image=input_img, randomVals=randomVals)
class segmentationGenerator(keras.utils.Sequence):
img_list = []
'''Generates data for Keras'''
'''Framework taken from https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly'''
'''Provided directories should contain the same number of files all with the same names to their pair image'''
def __init__(self, img_dir, seg_dir, batch_size = 64, image_size=(640,192), shuffle=True, augmentations=True, test=False):
# download dataset if not exist
dataset.verify_dataset()
self.img_dir = img_dir
self.seg_dir = seg_dir
self.image_size = image_size
self.batch_size = batch_size
self.shuffle = shuffle
self.augmentations = augmentations
self.inputs = []
self.test = test
self.initalSetup()
def __len__(self):
'''Denotes the number of batches per epoch'''
return int(np.floor(len(self.inputs) / self.batch_size))
def __getitem__(self, index):
'''Generate one batch of data'''
outX = np.empty((self.batch_size, *self.image_size, constants.input_channels))
if constants.use_unet:
outY = np.empty((self.batch_size, *self.image_size, constants.number_classes))
else:
outY = np.empty((self.batch_size, *self.image_size, 3))
outY_0 = np.empty((self.batch_size, *self.image_size, constants.input_channels))
outY_1 = np.empty((self.batch_size, *self.image_size, constants.input_channels))
imageNames = self.inputs[index*self.batch_size:(index+1)*self.batch_size]
for _, imageNameSet in enumerate(imageNames):
img_path = os.path.join(self.img_dir, imageNameSet)
seg_path = os.path.join(self.seg_dir, imageNameSet.replace('_', '_road_'))
img_orig = cv2.imread(img_path)
seg_orig = cv2.imread(seg_path)
# remove red from output
seg_road = seg_orig
# seg_road[:,:,2] = np.zeros([seg_road.shape[0], seg_road.shape[1]])
if constants.use_unet:
seg_road[:,:,1] = 255-seg_road[:,:,0]
seg_road[:,:,2] = np.zeros([seg_road.shape[0], seg_road.shape[1]])
else:
seg_road[:,:,2] = seg_road[:,:,0]
seg_road[:,:,1] = seg_road[:,:,0]
if (seg_orig is None):
print("Error in seg path: " + seg_path)
continue
img = cv2.resize(img_orig, dsize=self.image_size)
seg = cv2.resize(seg_road, dsize=self.image_size)
# print(img.shape)
# cv2.imshow('test', img)
# cv2.waitKey(-1)
# print(seg.shape)
# cv2.imshow('test', seg)
# cv2.waitKey(-1)
if self.augmentations:
randomVals = []
for x in range(0,9):
randomVals.append(random.random())
img_augmented = preprocess_input(image=img, randomVals=randomVals)
else:
img_augmented = img
outX[_] = np.transpose(img_augmented, axes=[1,0,2])
# outY_0[_] = np.transpose(img, axes=[1,0,2])
# outY_1[_] = np.transpose(seg, axes=[1,0,2])
if constants.use_unet:
two_seg = seg[:,:,0:2]
outY[_] = np.transpose(two_seg, axes=[1,0,2])
else:
outY[_] = np.transpose(seg, axes=[1,0,2])
#test_out = outX[_].astype('uint8')#np.transpose(left_augmented, axes=[1,0,2])
#cv2.imshow('test', test_out)
#cv2.waitKey(-1)
# outY = np.concatenate([outY_0,outY_1], axis=3)
return outX, outY #[outY_0, outY_1, outY_2, outY_3]
def on_epoch_end(self):
''' Shuffle the data if that is required'''
if self.shuffle:
random.shuffle(self.inputs)
def initalSetup(self):
#print("")
if (len(segmentationGenerator.img_list) == 0):
imgs = os.listdir(self.img_dir)
imgs.sort()
systemFiles = '.DS_Store'
prefixes = ('.')
for word in imgs[:]:
if word.startswith(prefixes) or word is systemFiles:
imgs.remove(word)
if self.shuffle:
random.shuffle(imgs)
segmentationGenerator.img_list = imgs
if (self.test):
self.inputs = segmentationGenerator.img_list[int(len(segmentationGenerator.img_list) * constants.train_ratio):]
else:
self.inputs = segmentationGenerator.img_list[0:int(len(segmentationGenerator.img_list) * constants.train_ratio)]
#self.inputs = self.inputs[0:100]
print("")
print("")
if __name__ == "__main__":
train = segmentationGenerator(constants.data_test_image_dir, constants.data_train_gt_dir, batch_size=8, shuffle=True)
test = segmentationGenerator(constants.data_test_image_dir, constants.data_train_gt_dir, batch_size=8, shuffle=True, test=True)
train.__getitem__(1)
test.__getitem__(1)
print('Data generator test success.')