forked from pulkitag/pycaffe-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
other_utils.py
415 lines (377 loc) · 10.3 KB
/
other_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
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
## @package other_utils
# Miscellaneous Util Functions
#
import numpy as np
import scipy.misc as scm
import matplotlib.pyplot as plt
import copy
import os
from os import path as osp
import collections as co
import pdb
from easydict import EasyDict as edict
##
# Get the defaults
def get_defaults(setArgs, defArgs, defOnly=True):
for key in setArgs.keys():
if defOnly:
assert defArgs.has_key(key), 'Key not found: %s' % key
defArgs[key] = copy.deepcopy(setArgs[key])
return defArgs
##
# Verify if all the keys are present recursively in the dict
def verify_recursive_key(data, keyNames, verifyOnly=False):
'''
data : dict like data['a']['b']['c']...['l']
keyNames: list of keys
verifyOnly: if TRUE then dont raise exceptions - just return the truth value
'''
assert isinstance(keyNames, list), 'keyNames is required to be a list'
#print data, keyNames
if verifyOnly:
if not data.has_key(keyNames[0]):
return False
else:
assert data.has_key(keyNames[0]), '%s not present' % keyNames[0]
for i in range(1,len(keyNames)):
dat = reduce(lambda dat, key: dat[key], keyNames[0:i], data)
assert isinstance(dat, dict), 'Wrong Keys'
if verifyOnly:
if not dat.has_key(keyNames[i]):
return False
else:
assert dat.has_key(keyNames[i]), '%s key not present' % keyNames[i]
return True
##
# Set the value of a recursive key.
def set_recursive_key(data, keyNames, val):
if verify_recursive_key(data, keyNames):
dat = reduce(lambda dat, key: dat[key], keyNames[:-1], data)
dat[keyNames[-1]] = val
else:
raise Exception('Keys not present')
def add_recursive_key(data, keyNames, val):
#isKey = verify_recursive_key(data, keyNames)
#assert not isKey, 'key is already present'
dat = reduce(lambda dat, key: dat[key], keyNames[:-1], data)
dat[keyNames[-1]] = val
##
# Delete the recursive key
def del_recursive_key(data, keyNames):
if verify_recursive_key(data, keyNames):
dat = reduce(lambda dat, key: dat[key], keyNames[:-1], data)
del dat[keyNames[-1]]
else:
raise Exception('Keys not present')
##
# Get the item from a recursive key
def get_item_recursive_key(data, keyNames, verifyOnly=False):
if verify_recursive_key(data, keyNames, verifyOnly=verifyOnly):
dat = reduce(lambda dat, key: dat[key], keyNames[:-1], data)
return dat[keyNames[-1]]
else:
print "Not found:", keyNames
return None
##
# Find the path to the key in a recursive dictionary.
def find_path_key(data, keyName):
'''
Returns path to the first key of name keyName that is found.
if keyName is a list - [k1, k2 ..kp] then find in data[k1][k2]...[kp-1] the key kp
'''
path = []
prevKey = []
if not isinstance(data, dict):
return path
#Find if all keys except the last one exist or not.
if isinstance(keyName, list):
data = copy.deepcopy(data)
for key in keyName[0:-1]:
if key not in data:
return []
else:
data = data[key]
prevKey = keyName[0:-1]
keyName = keyName[-1]
if data.has_key(keyName):
return [keyName]
else:
for key in data.keys():
pathFound = find_path_key(data[key], keyName)
if len(pathFound) > 0:
return prevKey + [key] + pathFound
return path
##
# Find an item in dict
# keyName should be a string or an list of a single name.
def get_item_dict(data, keyName):
keyPath = find_path_key(data, keyName)
#print keyPath
if len(keyPath)==0:
return None
else:
return get_item_recursive_key(data, keyPath)
##
#Find the key to the item in a dict
def find_keyofitem(data, item):
keyName = None
for k in data.keys():
tp = type(data[k])
if tp == dict or tp ==edict:
keyPath = find_keyofitem(data[k], item)
if keyPath is None:
continue
else:
keyName = [k] + keyPath
else:
if data[k] == item:
keyName = [k]
return keyName
##
# Read the image
def read_image(imName, color=True, isBGR=False, imSz=None):
'''
color: True - if a gray scale image is encountered convert into color
'''
im = plt.imread(imName)
if color:
if im.ndim==2:
print "Converting grayscale image into color image"
im = np.tile(im.reshape(im.shape[0], im.shape[1],1),(1,1,3))
if isBGR:
im = im[:,:,[2,1,0]]
#Resize if needed
if imSz is not None:
assert isinstance(imSz,int)
im = scm.imresize(im, (imSz,imSz))
return im
##
# Crop the image
def crop_im(im, bbox, **kwargs):
'''
The bounding box is assumed to be in the form (xmin, ymin, xmax, ymax)
kwargs:
imSz: Size of the image required
'''
cropType = kwargs['cropType']
imSz = kwargs['imSz']
x1,y1,x2,y2 = bbox
x1 = max(0, x1)
y1 = max(0, y1)
x2 = min(im.shape[1], x2)
y2 = min(im.shape[0], y2)
if cropType=='resize':
imBox = im[y1:y2, x1:x2]
imBox = scm.imresize(imBox, (imSz, imSz))
if cropType=='contPad':
contPad = kwargs['contPad']
x1 = max(0, x1 - contPad)
y1 = max(0, y1 - contPad)
x2 = min(im.shape[1], x2 + contPad)
y2 = min(im.shape[0], y2 + contPad)
imBox = im[y1:y2, x1:x2]
imBox = scm.imresize(imBox, (imSz, imSz))
else:
raise Exception('Unrecognized crop type')
return imBox
##
# Read and crop the image.
def read_crop_im(imName, bbox, **kwargs):
if kwargs.has_key('color'):
im = read_image(imName, color=kwargs['color'])
else:
im = read_image(imName)
return crop_im(im, bbox, **kwargs)
##
# Makes a table from dict
def make_table(**kwargs):
'''
kwargs should contains keys and lists as the values.
Each dictionaty will be plotted as a column.
'''
for i,key in enumerate(kwargs.keys()):
if i==0:
L = len(kwargs[key])
else:
assert L == len(kwargs[key]), 'Wrong length for %s' % key
N = len(kwargs.keys())
formatStr = "{:<15} "
lines = []
lines.append(''.join(formatStr.format(k) for k in kwargs.keys()) + '\n')
lines.append('-' * 15 * N + '\n')
for i in range(L):
line = ''
for key in kwargs.keys():
if isinstance(kwargs[key][i], int):
fStr = '%d'
elif isinstance(kwargs[key][i], np.float32) or isinstance(kwargs[key][i], np.float64):
fStr = '%.3f'
elif isinstance(kwargs[key][i], str):
fStr = '%s'
else:
fStr = '%s'
line = line + formatStr.format(fStr % kwargs[key][i])
line = line + '\n'
lines.append(line)
for l in lines:
print l
#I will make the rows.
def make_table_rows(**kwargs):
#Find the maximum length of the key.
maxKeyLen = 0
for key,val in kwargs.iteritems():
maxKeyLen = max(maxKeyLen, len(key))
keyLen = maxKeyLen + 15
keyStr = "{:<%d} " % keyLen
formatStr = "{:<15} "
#Lets start printing
lines = []
count = 0
for key,val in kwargs.iteritems():
line = ''
line = line + keyStr.format('%s' % key)
for v in val:
if isinstance(v, int):
fStr = '%d'
elif isinstance(v, np.float32) or isinstance(v, np.float64):
fStr = '%.3f'
elif isinstance(v, str):
fStr = '%s'
else:
fStr = '%s'
line = line + formatStr.format(fStr % v)
line = line + '\n'
lines.append(line)
if count == 0:
lines.append('-' * 100 + '\n')
count += 1
for l in lines:
print l
##
# In a recursive dictionary - subselect a few fields
# while vary others. For eg d['vr1']['a1']['b1'], d['vr2']['a1']['b2'], d['vr3']['a2']['b3']
# Now I might be interested only in values such that the second field is fixed to 'a1'
# So that I get the output as d['vr1']['b1'], d['vr2']['b2']
def conditional_select(data, fields, reduceFn=None):
'''
data : dict
fields : fields (a list)
[None,'a1',None] means that keep the second field fixed to 'a1',
but consider all values of other fields.
reduceFn : Typically the dict would store an array
reductionFn can be any function to reduce this array to
a quantity of interset like mean etc.
'''
newData = co.OrderedDict()
for key in data.keys():
if fields[0] is None:
#Chose all the keys
newData[key] = conditional_select(data[key], fields[1:], reduceFn=reduceFn)
else:
if key == fields[0]:
if len(fields) > 1:
newData = conditional_select(data[key], fields[1:], reduceFn=reduceFn)
else:
if reduceFn is None:
newData = copy.deepcopy(data[key])
else:
newData = copy.deepcopy(reduceFn(data[key]))
return newData
return newData
##
# Count the things.
def count_unique(arr, maxVal=None):
if maxVal is None:
elms = np.unique(arr)
else:
elms = range(maxVal+1)
count = np.zeros((len(elms),))
for i,e in enumerate(elms):
count[i] = np.sum(arr==e)
return count
##
# Create dir
def create_dir(dirName):
if not os.path.exists(dirName):
os.makedirs(dirName)
##
#Private function for chunking a path
def _chunk_path(fName, N):
assert '/' not in fName
L = len(fName)
if L <= N:
return fName
else:
slices=[]
for i in range(0,L,N):
slices.append(fName[i:min(L, i+N)])
newName = ''.join('%s/' % s for s in slices)
newName = newName[0:-1]
return newName
##
# chunk filenames
def chunk_filename(fName, maxLen=255):
'''
if any of the names is larger than 256 then
the file cannot be stored so some chunking needs
to be done
'''
splitNames = fName.split('/')
newSplits = []
for s in splitNames:
if len(s)>=maxLen:
newSplits.append(_chunk_path(s, maxLen-1))
else:
newSplits.append(s)
newName = ''.join('%s/' % s for s in newSplits)
newName = newName[0:-1]
dirName = os.path.dirname(newName)
create_dir(dirName)
return newName
##
# Hash a dictonary into string
def hash_dict_str(d, ignoreKeys=[]):
d = copy.deepcopy(d)
oKeys = []
for k in ignoreKeys:
if k in d.keys():
del d[k]
for k,v in d.iteritems():
if type(v) in [bool, int, float, str, type(None)]:
continue
else:
assert type(v) in [dict, edict, co.OrderedDict],\
'Type not recognized %s, for this type different results for different runs of\
hashing can be obtained, therefore the exception' % v
oKeys.append(k)
hStr = []
for k in oKeys:
hStr.append('-%s' % hash_dict_str({k: d[k]}))
del d[k]
hStr = ''.join('%s' % s for s in hStr)
return '%d%s' % (hash(frozenset(d.items())), hStr)
##
#
def mkdir(fName):
if not osp.exists(fName):
os.makedirs(fName)
##
#Make parameter string for python layers
def make_python_param_str(params, ignoreKeys=['expStr']):
paramStr = ''
for k,v in params.iteritems():
if k in ignoreKeys:
continue
if type(v) == bool:
if v:
paramStr = paramStr + ' --%s' % k
else:
paramStr = paramStr + ' --no-%s' % k
else:
paramStr = paramStr + ' --%s %s' % (k,v)
return paramStr
##
#Convert a list of ints into a string
def ints_to_str(ints):
ch = ''.join(str(unichr(i)) for i in ints)
return ch