-
Notifications
You must be signed in to change notification settings - Fork 0
/
raster2STL.py
executable file
·547 lines (438 loc) · 18.5 KB
/
raster2STL.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
#!/usr/bin/env python
# -*- coding: latin-1 -*-
"""
***********************************************************************
Name: raster2STL.py
Created: 28 Oct 2013
Author: David Segersson
Description
-----------------------------------------------------------------------
Convert raster into STL-format
"""
# Standard modules
from os import path
import sys
from optparse import OptionParser
import logging
import numpy as np
# pyAirviro-modules
from pyAirviro.other.utilities import ProgressBar
try:
from osgeo import ogr
from osgeo import gdal
from osgeo.gdalconst import GDT_Float32, GDT_Int16, GA_ReadOnly
__gdal_loaded__ = True
except:
__gdal_loaded__ = False
# Docstrings for the option parser
usage = "usage: %prog [options] "
version = "%prog 1.0"
log = logging.getLogger(__name__)
if __gdal_loaded__:
gdalDataTypes = {"Float32": GDT_Float32,
"Int16": GDT_Int16}
ogrDataTypes = {"Real": ogr.OFTReal,
"Integer": ogr.OFTInteger}
class Point:
def __init__(self, coords):
self.coords = [coords[0], coords[1], coords[2]]
def __getitem__(self, i):
return self.coords[i]
def __setitem__(self, i, val):
self.coords[i] = val
@property
def x(self):
return self.coords[0]
@property
def y(self):
return self.coords[0]
@property
def z(self):
return self.coords[0]
def round(self, precision):
# rounds to specified number of decimals
for i in range(len(self.coords)):
self.coords[i] = round(self.coords[i], precision)
def asvector(self):
return (self.coords[0], self.coords[1], self.coords[2])
def __eq__(self, p2):
try:
if self.coords == p2.coords:
return True
else:
return False
except:
return False
def __sub__(self, p2):
p = Point((self.x - p2.x, self.y - p2.y, self.z - p2.z))
return p
def __add__(self, p2):
p = Point((self.x + p2.x, self.y + p2.y, self.z + p2.z))
return p
def __mul__(self, p2):
p = Point((self.x * p2.x, self.y * p2.y, self.z * p2.z))
return p
class Triangle:
def __init__(self, p1, p2, p3):
self.points = [p1, p2, p3]
def normal(self):
# vectors that defines the plane
a = self.p2() - self.p1()
b = self.p3() - self.p1()
# cross product p1*p2
x = a[1] * b[2] - a[2] * b[1]
y = a[2] * b[0] - a[0] * b[2]
z = a[0] * b[1] - a[1] * b[0]
return (x, y, z)
def p1(self):
return self.points[0]
def p2(self):
return self.points[1]
def p3(self):
return self.points[2]
def round(self, precision):
for p in self.points:
p.round(precision)
def __str__(self):
t1_str = " facet normal %.6e %.6e %.6e\n" % self.normal()
t1_str += " outer loop\n"
t1_str += " vertex %.6e %.6e %.6e\n" % self.p1().asvector()
t1_str += " vertex %.6e %.6e %.6e\n" % self.p2().asvector()
t1_str += " vertex %.6e %.6e %.6e\n" % self.p3().asvector()
t1_str += " endloop\n"
t1_str += " endfacet\n"
return t1_str
def getCentreCoords(row, col, xll, yll, cellsizeX, cellsizeY, nrows, ncols):
"""Return cell centre coordinates"""
x = xll + 0.5 * cellsizeX + col * cellsizeX
y = yll - 0.5 * cellsizeY - (nrows - row - 1) * cellsizeY
return (x, y)
def damp(boundary, avgHeight, dist, bufferDist):
"""Return array of equal size as boundary damped with distance"""
if np.isscalar(boundary):
diff = avgHeight - boundary
else:
diff = avgHeight * np.ones(boundary.shape) - boundary
dampingFactor = min(1, (dist / (0.5 * bufferDist)))
return boundary + diff * dampingFactor
def block2STL(block, stream, xll, yll, cellsizeX, cellsizeY,
nodata, precision):
"""
Write a raster block to a stream in STL format
@param block: raster block
@param stream: a file-like object
@param xll: x-coordinate of lower left block corner
@param yll: y-coordinate of lower left block corner
@param cellsizeX: cellsize in X-direction
@param cellsizeY: cellsize in Y-direction
@param nodata: nodata value
@param precision: precision of STL-file coordinates
"""
nrows, ncols = block.shape
for row in np.arange(1, nrows):
for col in np.arange(ncols - 1):
x_c_upper, y_c_upper = getCentreCoords(row - 1, col, xll, yll,
cellsizeX, cellsizeY,
nrows, ncols)
x_c_right, y_c_upper = getCentreCoords(row - 1, col + 1, xll, yll,
cellsizeX, cellsizeY,
nrows, ncols)
x_c, y_c = getCentreCoords(row, col, xll, yll,
cellsizeX, cellsizeY,
nrows, ncols)
z_c = block[row, col]
z_c_upper = block[row - 1, col]
z_c_upper_right = block[row - 1, col + 1]
z_c_right = block[row, col + 1]
p = Point((x_c, y_c, z_c))
p_right = Point((x_c_right, y_c, z_c_right))
p_upper_right = Point((x_c_right, y_c_upper, z_c_upper_right))
p_upper = Point((x_c, y_c_upper, z_c_upper))
t1 = Triangle(p, p_upper, p_upper_right)
t2 = Triangle(p, p_upper_right, p_right)
t1.round(precision)
if z_c != nodata and z_c_upper != nodata \
and z_c_upper_right != nodata:
stream.writelines(str(t1))
if z_c != nodata and z_c_upper_right != nodata \
and z_c_right != nodata:
stream.writelines(str(t2))
def main():
# -----------Setting up and unsing option parser----------------
parser = OptionParser(usage=usage, version=version)
parser.add_option("-d", "--doc",
action="store_true", dest="doc",
help="Prints more detailed documentation and exit")
parser.add_option("-v", "--verbose",
action="store_const", const=logging.INFO,
dest="loglevel", default=logging.WARNING,
help="Produce verbose output")
parser.add_option("--no-progress",
action="store_const", dest="progressStream",
const=None, default=sys.stdout,
help="turn off the progress bar")
parser.add_option("-i", "--input",
action="store", dest="infileName",
help="Input raster")
parser.add_option("--bandIndex",
action="store", dest="bandIndex",
help="Band index to read from",
default=1)
parser.add_option("-o", "--output",
action="store", dest="output", default=None,
help="Output file")
parser.add_option("--solidName", default="TOPO",
action="store", dest="solidName",
help="Name of solid in STL-output")
parser.add_option("--precision", default=6,
action="store", dest="precision",
help="Precision of coordinates in STL-output")
parser.add_option("--buffer",
action="store", dest="buffer",
help="Add buffer distance to topo, " +
"damping out differences in elevation")
(options, args) = parser.parse_args()
# configuring logging
FORMAT = '%(levelname)s %(message)s'
logging.basicConfig(format=FORMAT)
# ------------Process and validate options---------------
if options.doc:
print __doc__
sys.exit()
if len(args) > 0:
parser.error("Incorrect number of arguments")
# validate infile path
if options.infileName is not None:
inFilePath = options.infileName
if not path.exists(inFilePath):
log.error("Input raster does not exist")
sys.exit(1)
else:
log.error("No input file specified")
sys.exit(1)
# validate outfile path
if options.output is None:
log.error("No output file specified")
sys.exit(1)
if options.buffer is not None:
bufferDist = float(options.buffer)
# Assure that gdal is present
if not __gdal_loaded__:
raise OSError("Function readGDAL needs GDAL with python bindings")
# register all of the raster drivers
gdal.AllRegister()
ds = gdal.Open(inFilePath, GA_ReadOnly)
if ds is None:
log.error('Could not open ' + inFilePath)
sys.exit(1)
ncols = ds.RasterXSize
nrows = ds.RasterYSize
# nbands = ds.RasterCount
# Info used for georeferencing
geoTransform = ds.GetGeoTransform()
xul = geoTransform[0] # top left x
cellsizeX = geoTransform[1] # w-e pixel resolution
rot1 = geoTransform[2] # rotation, 0 if image is "north up"
yul = geoTransform[3] # top left y
rot2 = geoTransform[4] # rotation, 0 if image is "north up"
cellsizeY = geoTransform[5] # n-s pixel resolution
# proj = ds.GetProjection()
# Calculate lower left corner
xll = xul
yll = yul + nrows * cellsizeY # cellsizeY should be a negative value
# Rotated rasters not handled...yet
if rot1 != 0 or rot2 != 0:
log.error('Handling of rotated rasters are not implemented yet')
sys.exit(1)
bandIndex = int(options.bandIndex)
band = ds.GetRasterBand(bandIndex)
nodata = band.GetNoDataValue()
# If no nodata value is present in raster, set to -9999 for completeness
if nodata is None:
nodata = -9999
# Processing of data is made for blocks of the following size
# two rows are processed at a time since triangles
# are created between cell centres.
procXBlockSize = ncols
procYBlockSize = 2
with open(options.output, 'w') as stlFile:
pg = ProgressBar(nrows, options.progressStream)
stlFile.write("solid " + options.solidName + "\n")
# avgHeight = 0
# write original cells to STL
# Loop over blocks of raster
for i in range(0, nrows - 1, 1):
pg.update(i)
data = band.ReadAsArray(xoff=0, yoff=i,
win_xsize=procXBlockSize,
win_ysize=procYBlockSize)
if nodata in data:
log.error("Nodata value found in raster," +
" this should be interpolated before" +
" converting to STL")
sys.exit(1)
# newCellsizeY is negative
blockYll = yul + (procYBlockSize + i) * cellsizeY
blockXll = xll
block2STL(data, stlFile, blockXll, blockYll, cellsizeX,
cellsizeY, nodata, int(options.precision))
# avgHeight += np.mean(data)
# avgHeight /= (nrows - 1)
# write buffer cells to STL
leftBoundary = band.ReadAsArray(
xoff=0, yoff=0,
win_xsize=1,
win_ysize=nrows
)
rightBoundary = band.ReadAsArray(
xoff=ncols - 1, yoff=0,
win_xsize=1,
win_ysize=nrows
)
topBoundary = band.ReadAsArray(
xoff=0, yoff=0,
win_xsize=procXBlockSize,
win_ysize=1
)
bottomBoundary = band.ReadAsArray(
xoff=0, yoff=nrows - 1,
win_xsize=procXBlockSize,
win_ysize=1
)
avgHeight = 0.25 * (
leftBoundary.mean() +
rightBoundary.mean() +
topBoundary.mean() +
bottomBoundary.mean()
)
if options.buffer is not None:
# overlap of one cell since triangles are created between
# cell centres
bufferCells = int(bufferDist / cellsizeX) + 1
leftBuffer = leftBoundary[:]
for i in range(1, bufferCells):
dist = i * cellsizeX
leftBuffer = np.hstack((
damp(leftBoundary, avgHeight, dist, bufferDist),
leftBuffer))
block2STL(leftBuffer, stlFile, xll - (bufferCells - 1) * cellsizeX,
yll, cellsizeX, cellsizeY, nodata,
int(options.precision))
rightBuffer = rightBoundary[:]
for i in range(1, bufferCells):
dist = i * cellsizeX
rightBuffer = np.hstack((
rightBuffer,
damp(rightBoundary, avgHeight, dist, bufferDist)))
block2STL(rightBuffer, stlFile, xll + (ncols - 1) * cellsizeX,
yll, cellsizeX, cellsizeY, nodata,
int(options.precision))
topBuffer = topBoundary[:]
for i in range(1, bufferCells):
dist = abs(i * cellsizeY)
topBuffer = np.vstack((
damp(topBoundary, avgHeight, dist, bufferDist),
topBuffer)
)
block2STL(topBuffer, stlFile, xll,
yul + cellsizeY,
cellsizeX, cellsizeY, nodata,
int(options.precision))
bottomBuffer = bottomBoundary[:]
for i in range(1, bufferCells):
dist = abs(i * cellsizeY)
bottomBuffer = np.vstack((
bottomBuffer,
damp(bottomBoundary, avgHeight, dist, bufferDist))
)
block2STL(bottomBuffer, stlFile, xll,
yll + (bufferCells - 1) * cellsizeY, cellsizeX,
cellsizeY, nodata,
int(options.precision))
# Add corner buffers
cornerBlock = np.ones((bufferCells, bufferCells))
# upper right
blockXll = xll + (ncols - 1) * cellsizeX
blockYll = yul + cellsizeY
startHeight = rightBoundary[0, 0]
cornerPoint = (xll + (ncols - 0.5) * cellsizeX,
yul + 0.5 * cellsizeY)
for col in range(bufferCells):
for row in range(bufferCells):
centre = getCentreCoords(row, col, blockXll, blockYll,
cellsizeX, cellsizeY,
bufferCells, bufferCells)
dist = (np.sqrt(pow(centre[0] - cornerPoint[0], 2) +
pow(centre[1] - cornerPoint[1], 2)))
# dist = min(row, col) * cellsizeX
cornerBlock[row, col] = damp(startHeight, avgHeight,
dist, bufferDist)
cornerBlock[:, 0] = topBuffer[:, -1]
cornerBlock[-1, :] = rightBuffer[0, :]
block2STL(cornerBlock, stlFile, blockXll,
blockYll, cellsizeX, cellsizeY, nodata,
int(options.precision))
# lower left
blockXll = xll - (bufferCells - 1) * cellsizeX
blockYll = yll + (bufferCells - 1) * cellsizeY
startHeight = leftBoundary[-1, 0]
cornerPoint = (xll + 0.5 * cellsizeX,
yll - 0.5 * cellsizeY)
for col in range(bufferCells):
for row in range(bufferCells):
centre = getCentreCoords(row, col, blockXll, blockYll,
cellsizeX, cellsizeY,
bufferCells, bufferCells)
dist = (np.sqrt(pow(centre[0] - cornerPoint[0], 2) +
pow(centre[1] - cornerPoint[1], 2)))
cornerBlock[row, col] = damp(startHeight, avgHeight,
dist, bufferDist)
cornerBlock[:, -1] = bottomBuffer[:, 0]
cornerBlock[0, :] = leftBuffer[-1, :]
block2STL(cornerBlock, stlFile, blockXll,
blockYll, cellsizeX, cellsizeY, nodata,
int(options.precision))
# upper left
blockXll = xll - (bufferCells - 1) * cellsizeX
blockYll = yul + cellsizeY
startHeight = leftBoundary[0, 0]
cornerPoint = (xll + 0.5 * cellsizeX,
yul + 0.5 * cellsizeY)
for col in range(bufferCells):
for row in range(bufferCells):
centre = getCentreCoords(row, col, blockXll, blockYll,
cellsizeX, cellsizeY,
bufferCells, bufferCells)
dist = (np.sqrt(pow(centre[0] - cornerPoint[0], 2) +
pow(centre[1] - cornerPoint[1], 2)))
cornerBlock[row, col] = damp(startHeight, avgHeight,
dist, bufferDist)
cornerBlock[:, -1] = topBuffer[:, 0]
cornerBlock[-1, :] = leftBuffer[0, :]
block2STL(cornerBlock, stlFile, blockXll,
blockYll, cellsizeX, cellsizeY, nodata,
int(options.precision))
# lower right
blockXll = xll + (ncols - 1) * cellsizeX
blockYll = yll + (bufferCells - 1) * cellsizeY
startHeight = rightBoundary[-1, 0]
cornerPoint = (xll + (ncols - 0.5) * cellsizeX,
yll - 0.5 * cellsizeY)
for col in range(bufferCells):
for row in range(bufferCells):
centre = getCentreCoords(row, col, blockXll, blockYll,
cellsizeX, cellsizeY,
bufferCells, bufferCells)
dist = (np.sqrt(pow(centre[0] - cornerPoint[0], 2) +
pow(centre[1] - cornerPoint[1], 2)))
cornerBlock[row, col] = damp(startHeight, avgHeight,
dist, bufferDist)
cornerBlock[:, 0] = bottomBuffer[:, -1]
cornerBlock[0, :] = rightBuffer[-1, :]
block2STL(cornerBlock, stlFile, blockXll,
blockYll, cellsizeX, cellsizeY, nodata,
int(options.precision))
stlFile.write("endsolid %s\n" % options.solidName)
pg.finished()
if __name__ == "__main__":
main()