forked from Kitware/Danesfield
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extrude_buildings.py
245 lines (202 loc) · 8.52 KB
/
extrude_buildings.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
#!/usr/bin/env python
###############################################################################
# Copyright Kitware Inc. and Contributors
# Distributed under the Apache License, 2.0 (apache.org/licenses/LICENSE-2.0)
# See accompanying Copyright.txt and LICENSE files for details
###############################################################################
import argparse
import logging
import numpy
import vtk
from vtk.numpy_interface import dataset_adapter as dsa
def main(args):
# Demonstrate generation of extruded objects from a segmentation map, where
# the extrusion is trimmed by a terrain surface.
parser = argparse.ArgumentParser(
description='Generate extruded buildings given a segmentation map, DSM and DTM')
parser.add_argument("segmentation", help="Image with labeled buildings")
parser.add_argument("dsm", help="Digital surface model (DSM)")
parser.add_argument("dtm", help="Digital terain model (DTM)")
parser.add_argument("destination", help="Extruded buildings polygonal file (.vtp)")
parser.add_argument('-l', "--label", type=int, nargs="*",
help="Label value(s) used for buildings outlines."
"If not specified, [6, 17] (buildings, roads) are used.")
parser.add_argument("--no_decimation", action="store_true",
help="Do not decimate the contours")
parser.add_argument("--no_render", action="store_true",
help="Do not render")
parser.add_argument("--debug", action="store_true",
help="Save intermediate results")
args = parser.parse_args(args)
# Read the terrain data
print("Reading and warping the DTM ...")
dtmReader = vtk.vtkGDALRasterReader()
dtmReader.SetFileName(args.dtm)
dtmC2p = vtk.vtkCellDataToPointData()
dtmC2p.SetInputConnection(dtmReader.GetOutputPort())
dtmC2p.Update()
# Range of terrain data
lo = dtmC2p.GetOutput().GetScalarRange()[0]
hi = dtmC2p.GetOutput().GetScalarRange()[1]
# Convert the terrain into a polydata.
surface = vtk.vtkImageDataGeometryFilter()
surface.SetInputConnection(dtmC2p.GetOutputPort())
# Make sure the polygons are planar, so need to use triangles.
tris = vtk.vtkTriangleFilter()
tris.SetInputConnection(surface.GetOutputPort())
# Warp the surface by scalar values
warp = vtk.vtkWarpScalar()
warp.SetInputConnection(tris.GetOutputPort())
warp.SetScaleFactor(1)
warp.UseNormalOn()
warp.SetNormal(0, 0, 1)
warp.Update()
# Read the segmentation of buildings. Original data in GDAL is cell data.
# Point data is interpolated.
print("Reading the segmentation ...")
segmentationReader = vtk.vtkGDALRasterReader()
segmentationReader.SetFileName(args.segmentation)
segmentationC2p = vtk.vtkCellDataToPointData()
segmentationC2p.SetInputConnection(segmentationReader.GetOutputPort())
segmentationC2p.PassCellDataOn()
segmentationC2p.Update()
segmentation = segmentationC2p.GetOutput()
if (args.debug):
segmentationWriter = vtk.vtkXMLImageDataWriter()
segmentationWriter.SetFileName("segmentation.vti")
segmentationWriter.SetInputConnection(segmentationC2p.GetOutputPort())
segmentationWriter.Update()
segmentation = segmentationC2p.GetOutput()
sb = segmentation.GetBounds()
print("segmentation bounds: \t{}".format(sb))
# Extract polygons
# as an alternative, could use vtk.vtkMarchingSquares()
contours = vtk.vtkDiscreteFlyingEdges2D()
contours.SetInputConnection(segmentationC2p.GetOutputPort())
# default labels
# 2 -- no building
# 6 -- building
# 17 -- road or highway
# 65 -- don't score
labels = [6, 17]
if (args.label):
labels = args.label
if (args.debug):
scalarName = segmentation.GetCellData().GetScalars().GetName()
segmentationNp = dsa.WrapDataObject(segmentation)
scalars = segmentationNp.CellData[scalarName]
allLabels = numpy.unique(scalars)
print("Contouring on labels: {} of {}".format(labels, allLabels))
else:
print("Contouring on labels: {}".format(labels))
contours.SetNumberOfContours(len(labels))
for i in range(len(labels)):
contours.SetValue(i, labels[i])
if (args.debug):
contoursWriter = vtk.vtkXMLPolyDataWriter()
contoursWriter.SetFileName("contours.vtp")
contoursWriter.SetInputConnection(contours.GetOutputPort())
contoursWriter.Update()
contoursData = contours.GetOutput()
cb = contoursData.GetBounds()
print("contours bounds: \t{}".format(cb))
if (not args.no_decimation):
print("Decimating the contours ...")
# combine lines into a polyline
stripperContours = vtk.vtkStripper()
stripperContours.SetInputConnection(contours.GetOutputPort())
stripperContours.SetMaximumLength(3000)
if (args.debug):
stripperWriter = vtk.vtkXMLPolyDataWriter()
stripperWriter.SetFileName("stripper.vtp")
stripperWriter.SetInputConnection(stripperContours.GetOutputPort())
stripperWriter.Update()
# decimate polylines
decimateContours = vtk.vtkDecimatePolylineFilter()
decimateContours.SetMaximumError(0.01)
decimateContours.SetInputConnection(stripperContours.GetOutputPort())
if (args.debug):
decimateWriter = vtk.vtkXMLPolyDataWriter()
decimateWriter.SetFileName("decimate.vtp")
decimateWriter.SetInputConnection(decimateContours.GetOutputPort())
decimateWriter.Update()
contours = decimateContours
# Create loops
print("Creating the loops ...")
loops = vtk.vtkContourLoopExtraction()
loops.SetInputConnection(contours.GetOutputPort())
if (args.debug):
loopsWriter = vtk.vtkXMLPolyDataWriter()
loopsWriter.SetFileName("loops.vtp")
loopsWriter.SetInputConnection(loops.GetOutputPort())
loopsWriter.Update()
# Read the DSM
print("Reading the DSM ...")
dsmReader = vtk.vtkGDALRasterReader()
dsmReader.SetFileName(args.dsm)
dsmC2p = vtk.vtkCellDataToPointData()
dsmC2p.SetInputConnection(dsmReader.GetOutputPort())
dsmC2p.Update()
print("Extruding the buildings ...")
fit = vtk.vtkFitToHeightMapFilter()
fit.SetInputConnection(loops.GetOutputPort())
fit.SetHeightMapConnection(dsmC2p.GetOutputPort())
fit.UseHeightMapOffsetOn()
fit.SetFittingStrategyToPointMaximumHeight()
if (args.debug):
fitWriter = vtk.vtkXMLPolyDataWriter()
fitWriter.SetFileName("fit.vtp")
fitWriter.SetInputConnection(fit.GetOutputPort())
fitWriter.Update()
# Extrude polygon down to surface
extrude = vtk.vtkTrimmedExtrusionFilter()
extrude.SetInputConnection(fit.GetOutputPort())
extrude.SetTrimSurfaceConnection(warp.GetOutputPort())
extrude.SetExtrusionDirection(0, 0, 1)
extrude.CappingOn()
extrudeWriter = vtk.vtkXMLPolyDataWriter()
extrudeWriter.SetFileName(args.destination)
extrudeWriter.SetInputConnection(extrude.GetOutputPort())
extrudeWriter.Update()
if (not args.no_render):
# Create the RenderWindow, Renderer
#
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# Create pipeline. Load terrain data.
lut = vtk.vtkLookupTable()
lut.SetHueRange(0.6, 0)
lut.SetSaturationRange(1.0, 0)
lut.SetValueRange(0.5, 1.0)
# Show the terrain
dtmMapper = vtk.vtkPolyDataMapper()
dtmMapper.SetInputConnection(warp.GetOutputPort())
dtmMapper.SetScalarRange(lo, hi)
dtmMapper.SetLookupTable(lut)
dtmActor = vtk.vtkActor()
dtmActor.SetMapper(dtmMapper)
# show the buildings
trisExtrude = vtk.vtkTriangleFilter()
trisExtrude.SetInputConnection(extrude.GetOutputPort())
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(trisExtrude.GetOutputPort())
mapper.ScalarVisibilityOff()
actor = vtk.vtkActor()
actor.SetMapper(mapper)
# Render it
ren.AddActor(dtmActor)
ren.AddActor(actor)
ren.GetActiveCamera().Elevation(-60)
ren.ResetCamera()
renWin.Render()
iren.Start()
if __name__ == '__main__':
import sys
try:
main(sys.argv[1:])
except Exception as e:
logging.exception(e)
sys.exit(1)