-
Notifications
You must be signed in to change notification settings - Fork 0
/
patch_DataLoad_Binary_full_test.py
239 lines (173 loc) · 8.31 KB
/
patch_DataLoad_Binary_full_test.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
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# coding: utf-8
# In[1]:
import itertools
import scipy.io as sio
import numpy as np
import os
import cv2
import random
import h5py
from PIL import Image
import time
import pickle
os.environ['KERAS_BACKEND'] = 'tensorflow'
from keras.utils.np_utils import to_categorical
from keras.utils.data_utils import Sequence
# In[2]:
class ChronoDataSet(Sequence):
def __init__(self,
label_file_path,
data_file_path,
batch_size=128,
start_epoch=0,
mode='TRAIN',
dataset='UCF'):
'''
Constant parameters
'''
self.n_frames = 4
self.image_padding = 16
self.image_size = 112
self.image_jitter = 5
self.channels = 3
self.epoch = start_epoch + 1
self.batch_size = batch_size
self.order_type = [
list(ele) for ele in
itertools.permutations(range(self.n_frames))
if list(ele) != [0,1,2,3] and list(ele) != [3,2,1,0]
]
# TRAIN_UCF, TRAIN_HMDB = [], []
# with open(label_file_path, 'rb') as f:
# TRAIN_UCF, TRAIN_HMDB = pickle.load(f)
# self.label = TRAIN_UCF
# if dataset == 'HMDB':
# self.label = TRAIN_HMDB
self.data_file_path = data_file_path
data = h5py.File(data_file_path,'r')
self.samples = data['train_img'].shape[0]
self.mode = "train_img"
if mode == "VALIDATION":
self.mode = "val_img"
self.samples = data['val_img'].shape[0]
elif mode == "TEST":
print "TEST MODE INITIALIZED"
self.mode = "test_img"
self.samples = data['test_img'].shape[0]
data.close()
self.blocks = [item for item in xrange(0, self.samples, self.batch_size)][:-1]
self.current_img_size = self.image_size + self.image_padding
print "Batch_Size", self.batch_size
def getBlocks(self):
return self.blocks;
def __len__(self):
# return batch size?
return int(self.samples / self.batch_size)
def getBatchRunsPerEpoch(self):
return int(self.samples / self.batch_size)
def opticalFlow(self, frame1, frame2):
hsv = np.zeros_like(frame1)
hsv[...,1] = 255
flow = cv2.calcOpticalFlowFarneback(cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY), cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY), None, 0.5, 3, 15, 3, 5, 1.2, 0)
mag, ang = cv2.cartToPolar(flow[...,0], flow[...,1])
hsv[...,0] = ang*180/np.pi/2
hsv[...,2] = cv2.normalize(mag,None,0,255,cv2.NORM_MINMAX)
return cv2.cvtColor(hsv,cv2.COLOR_HSV2BGR)
def jitter_image(self, image, startxy):
#startxy = np.random.randint(0, self.image_padding), np.random.randint(0, self.image_padding)
# Start points by default
newx, newy = startxy
# Jitter points
sx, sy = random.randint(-self.image_jitter, self.image_jitter), random.randint(-self.image_jitter, self.image_jitter)
# Jitter should not move the crop window outside the image
if startxy[0] + sx > 0 and startxy[0] + self.image_size + sx < self.current_img_size: newx += sx
if startxy[1] + sy > 0 and startxy[1] + self.image_size + sy < self.current_img_size: newy += sy
return image[newx : newx + self.image_size, newy : newy + self.image_size, ...]
def on_epoch_end(self):
#random.shuffle(self.blocks)
print "\nEPOCH", self.epoch, "Ends. Data blocks shuffled!"
self.epoch += 1
def generate_startXY(self):
return (np.random.randint(0, self.image_padding), np.random.randint(0, self.image_padding))
def __getitem__(self, idx):
start_time = time.time()
idxcounter = idx % self.getBatchRunsPerEpoch()
with h5py.File(self.data_file_path,'r') as f:
batch_data = f[self.mode][self.blocks[idxcounter]:self.blocks[idxcounter] + self.batch_size, ...]
#np.random.shuffle(batch_data)
# Spatial Jittering
images = [[self.jitter_image(each_image, startXY) for each_image in sample]
for sample in batch_data for startXY in [self.generate_startXY()]]
# Horizontal Flip
images = [[cv2.flip(images[index][image_index], 1) for image_index in xrange(self.n_frames)]
if np.random.randint(0,2) else images[index] for index in xrange(self.batch_size)]
# Channel Splitting
images = [[np.stack((images[index][image_index][:,:,np.random.randint(0, 3)],)*3, axis=2)
for image_index in xrange(self.n_frames)] for index in xrange(self.batch_size)]
# for image in images:
# print len(image), image[0].shape, image[1].shape, image[2].shape, image[3].shape
# Randomly +ve and -ve test case
images = [(np.stack(tuple([images[index][random_index]
for random_index in self.order_type[np.random.randint(0, len(self.order_type))]]), axis=0), 0)
if False and np.random.randint(0,2) else (images[index][::1 * ((-1)**(np.random.randint(0,2) + 1))], 1) for index in xrange(self.batch_size)]
# print "After labelling"
# for image in images:
# print len(image[1]), image[1][0].shape, image[1][1].shape, image[1][2].shape, image[1][3].shape
labels = np.array([label for _, label in images])
images = np.array([image for image, _ in images])
optical_flow = [np.array([self.opticalFlow(images[index][image_index], images[index][image_index+1]) for image_index in xrange(self.n_frames-1)] + [self.opticalFlow(images[index][-1], images[index][0])], dtype=np.float32) for index in xrange(self.batch_size)]
images = np.array(images, dtype=np.float32)
optical_flow = np.array(optical_flow, dtype=np.float32)
images -= 97.3
# if not (idxcounter + 1)%500:
# print "\nLOAD TIME | Epoch", str(self.epoch), "| Batch", str(self.blocks[idxcounter]), "| processed with time : ", str(time.time() - start_time), "\n"
return ({'IMG_input': images, 'OPT_input': optical_flow}, {'output': labels})
# *Testing of the module*
# ```
# TYNAMO_HOME_DIR = '/nfs/tynamo/home/data/vision7/gdhody/chrono/'
# BLITZLE_HOME_DIR = '/nfs/blitzle/home/data/vision5/gdhody/chrono/'
# HOME_DIR = TYNAMO_HOME_DIR
# HDF5_PATH = os.path.join(HOME_DIR, 'patch.hdf5')
# PICKLE_PATH = os.path.join(HOME_DIR, 'patch.pkl')
# cds = ChronoDataSet(PICKLE_PATH, HDF5_PATH)
# cds.__getitem__(99)
# ```
# In[126]:
# import matplotlib.pyplot as plt
# %matplotlib inline
# TYNAMO_HOME_DIR = '/nfs/tynamo/home/data/vision7/gdhody/chrono/'
# BLITZLE_HOME_DIR = '/nfs/blitzle/home/data/vision5/gdhody/chrono/'
# HOME_DIR = TYNAMO_HOME_DIR
# HDF5_PATH = os.path.join(HOME_DIR, 'patch.hdf5')
# PICKLE_PATH = os.path.join(HOME_DIR, 'patch.pkl')
# cds = ChronoDataSet(PICKLE_PATH, HDF5_PATH)
# print cds.__getitem__(50)[0][0].shape
# np.amax(cds.__getitem__(50)[0][0])
# for inn, frames in enumerate(im):
# index = 1
# print inn, frames.shape
# plt.figure()
# plt.subplots_adjust(wspace=1, hspace=1)
# plt.subplots(figsize=(15, 20))
# for frame in frames:
# suub_plt = plt.subplot(1, 4, index)
# plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB), interpolation='nearest', aspect='equal')
# index += 1
# print l
# In[29]:
# TYNAMO_HOME_DIR = '/nfs/tynamo/home/data/vision7/gdhody/chrono/'
# BLITZLE_HOME_DIR = '/nfs/blitzle/home/data/vision5/gdhody/chrono/'
# HOME_DIR = TYNAMO_HOME_DIR
# HDF5_PATH = os.path.join(HOME_DIR, 'patch.hdf5')
# with h5py.File(HDF5_PATH,'r') as f:
# print np.mean(f['train_img'])
# In[3]:
# import matplotlib.pyplot as plt
# %matplotlib inline
# TYNAMO_HOME_DIR = '/nfs/tynamo/home/data/vision7/gdhody/chrono/'
# BLITZLE_HOME_DIR = '/nfs/blitzle/home/data/vision5/gdhody/chrono/'
# HOME_DIR = TYNAMO_HOME_DIR
# HDF5_PATH = os.path.join(HOME_DIR, 'storage.hdf5')
# PICKLE_PATH = os.path.join(HOME_DIR, 'storage.pkl')
# cds = ChronoDataSet(PICKLE_PATH, HDF5_PATH)
# print cds.__getitem__(50)[0]['OPT_input'][0].shape