-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDatasetUtils.py
560 lines (481 loc) · 17.6 KB
/
DatasetUtils.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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
import torch
import numpy as np
from skimage.draw import disk, ellipse, polygon
import os
import csv
import time
from osgeo import gdal
import sys
import pandas as pd
from itertools import product
img_size = 512
def crop_to_size(arr, x):
"""Crops an array to a size that is divisible by x"""
h, w = arr.shape
h_r = h - (h % x)
w_r = w - (w % x)
return arr[:h_r, :w_r]
def slice_DEM(arr, size, in_file, outDir):
"""Slices an input array into smaller sub-arrays"""
arr = crop_to_size(arr, size)
h, w = arr.shape
assert h % size == 0, f"{h} rows is not evenly divisible by {size}"
assert w % size == 0, f"{w} cols is not evenly divisible by {size}"
grid = arr.reshape(h // size, size, -1, size).swapaxes(1, 2).reshape(-1, size, size)
idx = 1
for x in grid:
t_filename = outDir + '/' + in_file + '_' + str(idx) + '.pt'
try:
t = torch.tensor(x)
t = torch.unsqueeze(t, 0)
torch.save(t, t_filename)
except OSError:
print(f"{t_filename} could not be saved, or the file only contains partial data")
idx += 1
if idx > 20:
return
def getNeighbours(cell):
size = 64
for c in product(*(range(n-1, n+2) for n in cell)):
if c != cell and all(0 <= n < size for n in c):
yield c
def getWeight(m, i, j):
neighbours = list(getNeighbours((i, j)))
num_ns = len(neighbours)
weight = 0
for x in neighbours:
weight += (1 - m[x[0], x[1]])/num_ns
return weight
def WeightMatrix(m):
m = torch.squeeze(m).to(torch.float32)
w = torch.empty(m.shape[0], m.shape[1])
for i in range(m.shape[0]):
for j in range(m.shape[1]):
if m[i, j] == 0:
w[i, j] = 0.5
else:
w[i, j] = getWeight(m, i, j)
return w
def CreateSquareMask(holeSize):
""" Adds a square mask to an image
Returns the resulting image and the corresponding mask as a tuple
"""
# create a matrix with the same size as the input image and fill it with 1s
mask = np.ones([img_size, img_size], dtype=int)
# define the mask boundaries
x2 = int(img_size / 2 + holeSize / 2)
y1 = int(img_size / 2 - holeSize / 2)
x1 = int(img_size / 2 - holeSize / 2)
y2 = int(img_size / 2 + holeSize / 2)
# fill the mask area with 0s
mask[x1:x2, y1:y2] = np.zeros([holeSize, holeSize, 3], dtype=int)
return mask
def CreateStripMask(holeWidth):
""" Adds a horizontal strip mask to an image
Returns the resulting image and the corresponding mask as a tuple
"""
# create a matrix with the same size as the input image and fill it with 1s
mask = np.ones([img_size, img_size], dtype=int)
# define the mask boundaries
y1 = int(img_size/2 - holeWidth/2)
y2 = int(img_size/2 + holeWidth/2)
x1 = int(0)
x2 = int(img_size)
# fill the mask area with 0s
mask[x1:x2, y1:y2] = np.zeros([img_size, holeWidth], dtype=int)
return mask
def CreateCircleMask(radius):
"""Adds a circular mask to an image"""
# create numpy array to store the mask
mask = np.ones([img_size, img_size], dtype=int)
# define the centre of the circle to be the centre of the image
c_x, c_y = int(img_size/2), int(img_size/2)
r, c = disk((c_x, c_y), radius)
mask[r, c] = 0
return mask
def CreateEllipseMask(r_radius, c_radius):
"""Adds an elliptical mask to an image"""
# create numpy array
mask = np.ones([img_size, img_size], dtype=int)
# set the centre of the ellipse to be the centre of the image
c_x, c_y = int(img_size/2), int(img_size/2)
r, c = ellipse(c_x, c_y, r_radius, c_radius)
mask[r, c] = 0
return mask
def CreatePolygonMask():
"""Adds a polygon mask to an image"""
# create numpy array
mask = np.ones([img_size, img_size], dtype=int)
# define coordinates for the vertices of the polygon
a = [int(img_size/2), int(img_size/2)] # centre of the image
b = [int(img_size/2), 0] # centre at the top edge
c = [int(3*img_size/5), 0] # 3/5 along the top edge
# define row coordinates
rows = np.array([a[1], b[1], c[1]])
# define column coordinates
cols = np.array([a[0], b[0], c[0]])
# create polygon
r, c = polygon(rows, cols)
# fill mask
mask[r, c] = 0
return mask
def CreateTopLeftEdgeMask():
"""Adds a polygon mask to an image"""
# create numpy array
mask = np.ones([img_size, img_size], dtype=int)
# define coordinates for the vertices of the polygon
a = [0, 0] # top left corner of the image
b = [int(4*img_size/10), 0] # top edge
c = [0, int(6*img_size/10)] # left edge
# define row coordinates
rows = np.array([a[1], b[1], c[1]])
# define column coordinates
cols = np.array([a[0], b[0], c[0]])
# create polygon
r, c = polygon(rows, cols)
# fill mask
mask[r, c] = 0
return mask
def CreateTopRightEdgeMask():
"""Adds a polygon mask to an image"""
# create numpy array
mask = np.ones([img_size, img_size], dtype=int)
# define coordinates for the vertices of the polygon
a = [img_size-1, 0] # top left corner of the image
b = [int(6*img_size/10), 0] # top edge
c = [img_size-1, int(4*img_size/10)] # left edge
# define row coordinates
rows = np.array([a[1], b[1], c[1]])
# define column coordinates
cols = np.array([a[0], b[0], c[0]])
# create polygon
r, c = polygon(rows, cols)
# fill mask
mask[r, c] = 0
return mask
def CreateTopLeftStripMask():
"""Adds a polygon mask to an image"""
# create numpy array
mask = np.ones([img_size, img_size], dtype=int)
# define coordinates for the vertices of the polygon
a = [0, int(img_size * (2/10))]
b = [0, int(img_size * (4/10))]
c = [int(img_size * (4/10)), 0]
d = [int(img_size * (2/10)), 0]
# define column coordinates
cols = np.array([a[0], b[0], c[0], d[0]])
# define row coordinates
rows = np.array([a[1], b[1], c[1], d[1]])
# create polygon
r, c = polygon(rows, cols)
# fill mask
mask[r, c] = 0
return mask
def CreateBottomRightStripMask():
"""Adds a polygon mask to an image"""
# create numpy array
mask = np.ones([img_size, img_size], dtype=int)
# define coordinates for the vertices of the polygon
a = [img_size-1, int(img_size * (2/10))]
b = [img_size-1, int(img_size * (6/10))]
c = [int(img_size * (8/10)), img_size-1]
d = [int(img_size * (6/10)), img_size-1]
# define column coordinates
cols = np.array([a[0], b[0], c[0], d[0]])
# define row coordinates
rows = np.array([a[1], b[1], c[1], d[1]])
# create polygon
r, c = polygon(rows, cols)
# fill mask
mask[r, c] = 0
return mask
def CreateLeftStripMask(holeWidth):
""" Adds a horizontal strip mask to an image
Returns the resulting image and the corresponding mask as a tuple
"""
# create a matrix with the same size as the input image and fill it with 1s
mask = np.ones([img_size, img_size], dtype=int)
# define the mask boundaries
y1 = int(0)
y2 = int(holeWidth)
x1 = int(0)
x2 = int(img_size)
# fill the mask area with 0s
mask[x1:x2, y1:y2] = np.zeros([img_size, holeWidth], dtype=int)
return mask
def CreateHorizontalStripMask(holeWidth):
""" Adds a horizontal strip mask to an image
Returns the resulting image and the corresponding mask as a tuple
"""
# create a matrix with the same size as the input image and fill it with 1s
mask = np.ones([img_size, img_size], dtype=int)
# define the mask boundaries
x1 = int(img_size/2 - holeWidth/2)
x2 = int(img_size/2 + holeWidth/2)
y1 = int(0)
y2 = int(img_size)
# fill the mask area with 0s
mask[x1:x2, y1:y2] = np.zeros([holeWidth, img_size], dtype=int)
return mask
def CreateTopStripMask(holeWidth):
""" Adds a horizontal strip mask to an image
Returns the resulting image and the corresponding mask as a tuple
"""
# create a matrix with the same size as the input image and fill it with 1s
mask = np.ones([img_size, img_size], dtype=int)
# define the mask boundaries
x1 = int(0)
x2 = int(holeWidth)
y1 = int(0)
y2 = int(img_size)
# fill the mask area with 0s
mask[x1:x2, y1:y2] = np.zeros([holeWidth, img_size], dtype=int)
return mask
def createMasks(shapeList, outDir, wDir):
if shapeList[0]:
mask = CreateTopLeftEdgeMask()
t_filename = outDir + '/' + "tl_edge.pt"
w_filename = wDir + '/' + "tl_edge_w.pt"
try:
t = torch.from_numpy(mask)
t = torch.unsqueeze(t, 0)
w = WeightMatrix(t)
torch.save(t, t_filename)
torch.save(w, w_filename)
except OSError:
print(f"{t_filename} could not be saved, or the file only contains partial data")
if shapeList[1]:
mask = CreateTopRightEdgeMask()
t_filename = outDir + '/' + "tr_edge.pt"
w_filename = wDir + '/' + "tr_edge_w.pt"
try:
t = torch.from_numpy(mask)
t = torch.unsqueeze(t, 0)
w = WeightMatrix(t)
torch.save(t, t_filename)
torch.save(w, w_filename)
except OSError:
print(f"{t_filename} could not be saved, or the file only contains partial data")
if shapeList[2]:
mask = CreateTopLeftStripMask()
t_filename = outDir + '/' + "tl_strip.pt"
w_filename = wDir + '/' + "tl_strip_w.pt"
try:
t = torch.from_numpy(mask)
t = torch.unsqueeze(t, 0)
w = WeightMatrix(t)
torch.save(t, t_filename)
torch.save(w, w_filename)
except OSError:
print(f"{t_filename} could not be saved, or the file only contains partial data")
if shapeList[3]:
mask = CreateBottomRightStripMask()
t_filename = outDir + '/' + "br_edge.pt"
w_filename = wDir + '/' + "br_edge_w.pt"
try:
t = torch.from_numpy(mask)
t = torch.unsqueeze(t, 0)
w = WeightMatrix(t)
torch.save(t, t_filename)
torch.save(w, w_filename)
except OSError:
print(f"{t_filename} could not be saved, or the file only contains partial data")
if shapeList[4]:
mask = CreateSquareMask(int(img_size/4))
t_filename = outDir + '/' + "sqr.pt"
w_filename = wDir + '/' + "sqr_w.pt"
try:
t = torch.from_numpy(mask)
t = torch.unsqueeze(t, 0)
w = WeightMatrix(t)
torch.save(t, t_filename)
torch.save(w, w_filename)
except OSError:
print(f"{t_filename} could not be saved, or the file only contains partial data")
if shapeList[5]:
mask = CreateStripMask(int(img_size/8))
t_filename = outDir + '/' + "c_strip.pt"
w_filename = wDir + '/' + "c_strip_w.pt"
try:
t = torch.from_numpy(mask)
t = torch.unsqueeze(t, 0)
w = WeightMatrix(t)
torch.save(t, t_filename)
torch.save(w, w_filename)
except OSError:
print(f"{t_filename} could not be saved, or the file only contains partial data")
if shapeList[6]:
mask = CreateCircleMask(int(img_size/4))
t_filename = outDir + '/' + "circle.pt"
w_filename = wDir + '/' + "circle_w.pt"
try:
t = torch.from_numpy(mask)
t = torch.unsqueeze(t, 0)
w = WeightMatrix(t)
torch.save(t, t_filename)
torch.save(w, w_filename)
except OSError:
print(f"{t_filename} could not be saved, or the file only contains partial data")
if shapeList[7]:
mask = CreateEllipseMask(int(img_size/3), int(img_size/6))
t_filename = outDir + '/' + "ellipse.pt"
w_filename = wDir + '/' + "ellipse_w.pt"
try:
t = torch.from_numpy(mask)
t = torch.unsqueeze(t, 0)
w = WeightMatrix(t)
torch.save(t, t_filename)
torch.save(w, w_filename)
except OSError:
print(f"{t_filename} could not be saved, or the file only contains partial data")
if shapeList[8]:
mask = CreatePolygonMask()
t_filename = outDir + '/' + "polygon.pt"
w_filename = wDir + '/' + "polygon_w.pt"
try:
t = torch.from_numpy(mask)
t = torch.unsqueeze(t, 0)
w = WeightMatrix(t)
torch.save(t, t_filename)
torch.save(w, w_filename)
except OSError:
print(f"{t_filename} could not be saved, or the file only contains partial data")
if shapeList[9]:
mask = CreateLeftStripMask(int(img_size/6))
t_filename = outDir + '/' + "l_strip.pt"
w_filename = wDir + '/' + "l_strip_w.pt"
try:
t = torch.from_numpy(mask)
t = torch.unsqueeze(t, 0)
w = WeightMatrix(t)
torch.save(t, t_filename)
torch.save(w, w_filename)
except OSError:
print(f"{t_filename} could not be saved, or the file only contains partial data")
if shapeList[10]:
mask = CreateHorizontalStripMask(int(img_size/6))
t_filename = outDir + '/' + "h_strip.pt"
w_filename = wDir + '/' + "h_strip_w.pt"
try:
t = torch.from_numpy(mask)
t = torch.unsqueeze(t, 0)
w = WeightMatrix(t)
torch.save(t, t_filename)
torch.save(w, w_filename)
except OSError:
print(f"{t_filename} could not be saved, or the file only contains partial data")
if shapeList[11]:
mask = CreateTopStripMask(int(img_size/7))
t_filename = outDir + '/' + "t_strip.pt"
w_filename = wDir + '/' + "t_strip_w.pt"
try:
t = torch.from_numpy(mask)
t = torch.unsqueeze(t, 0)
w = WeightMatrix(t)
torch.save(t, t_filename)
torch.save(w, w_filename)
except OSError:
print(f"{t_filename} could not be saved, or the file only contains partial data")
def createRows(shapesList, inDir):
outputList = []
for file in os.listdir(inDir):
if shapesList[0]:
row = file, "tl_edge.pt", "tl_edge_w.pt"
outputList.append(row)
if shapesList[1]:
row = file, "tr_edge.pt", "tr_edge_w.pt"
outputList.append(row)
if shapesList[2]:
row = file, "tl_strip.pt", "tl_strip_w.pt"
outputList.append(row)
if shapesList[3]:
row = file, "br_edge.pt", "br_edge_w.pt"
outputList.append(row)
if shapesList[4]:
row = file, "sqr.pt", "sqr_w.pt"
outputList.append(row)
if shapesList[5]:
row = file, "c_strip.pt", "c_strip_w.pt"
outputList.append(row)
if shapesList[6]:
row = file, "circle.pt", "circle_w.pt"
outputList.append(row)
if shapesList[7]:
row = file, "ellipse.pt", "ellipse_w.pt"
outputList.append(row)
if shapesList[8]:
row = file, "polygon.pt", "polygon_w.pt"
outputList.append(row)
if shapesList[9]:
row = file, "l_strip.pt", "l_strip_w.pt"
outputList.append(row)
if shapesList[10]:
row = file, "h_strip.pt", "h_strip_w.pt"
outputList.append(row)
if shapesList[11]:
row = file, "t_strip.pt", "t_strip_w.pt"
outputList.append(row)
return outputList
def createLookUp():
# list of mask shapes to use
shapes = [
True, # tl edge
True, # tr edge
True, # tl strip
True, # br strip
False, # square
True, # centre strip
False, # circle
False, # ellipse
False, # polygon
True, # l strip
True, # h strip
True, # t strip
]
createMasks(shapes, 'outputMasks', 'outputWeights')
print("masks created...")
numShapes = 0
for shape in shapes:
if shape:
numShapes += 1
csvRows = createRows(shapes, 'outputSlices')
print("rows created")
csvFile = 'LookUp/lookUpTable.csv'
try:
# write to csv file
with open(csvFile, 'w', newline='') as csvFile:
csvWriter = csv.writer(csvFile, dialect='excel')
csvWriter.writerows(csvRows)
print('Lookup table created...')
except OSError:
print("Failed to create lookUpTable.csv")
return
def Create():
"""Given an PDS4 input, creates a dataset of slices from the input DEM"""
startTime = time.time()
driver = gdal.GetDriverByName('PDS4')
driver.Register()
file_name = 'Raw_DEMs/lrolrc_0042a/data/esm4/2019355/nac/m1331540878le.img'
data = gdal.Open(file_name)
if data is None:
print('Unable to open file')
sys.exit()
print(f"Cols: {data.RasterXSize}, Rows: {data.RasterYSize}, bands: {data.RasterCount}")
np_array = np.array(data.GetRasterBand(1).ReadAsArray(), dtype='f')
# remove void data at the edges of the DEM
h, w = np_array.shape
trimmed = np_array[0:h, 50:(w-50)]
slice_DEM(trimmed, img_size, 'm1331540878le', 'exampleDEMs')
# createLookUp()
print(f"Dataset created in {time.time()-startTime:.4f} seconds")
def Clean(batchSize):
"""Ensures that the dataset is the correct size"""
filePath = 'LookUp/lookUpTable.csv'
lookUp = pd.read_csv(filePath)
length = len(lookUp)
excess = length % batchSize
if excess > 0:
diff = length - excess
lookUp = lookUp.iloc[:diff]
print(f"Dataset trimmed to fit with a batch size of {batchSize}")
lookUp.to_csv(filePath, index=False)