-
Notifications
You must be signed in to change notification settings - Fork 0
/
raster2shape.py
executable file
·352 lines (293 loc) · 11.9 KB
/
raster2shape.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
#!/usr/bin/env python
# -*- coding: latin-1 -*-
"""
***********************************************************************
Name: raster2shape.py
Created: 7 Sep 2013
Author: David Segersson
Description
-----------------------------------------------------------------------
Convert raster into vector grid (fishnet) or points
A filter can be given to produce a smaller 'sparse' raster
"""
#Standard modules
from os import path
import sys
from optparse import OptionParser
import numpy as np
#pyAirviro-modules
from pyAirviro.other import logger
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"
if __gdal_loaded__:
gdalDataTypes = {"Float32": GDT_Float32,
"Int16": GDT_Int16}
ogrDataTypes = {"Real": ogr.OFTReal,
"Integer": ogr.OFTInteger}
#-----------Global variables -----------
log = None
# --------------------------------------
def block2poly(block, layer, xll, yll, cellsizeX, cellsizeY, nodata,
fieldName, filter=None):
"""
Write a block to a polygon shape-file
@param block: raster block
@param layer: ogr layer object to write to
@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 fieldName: name of field to write
@param filter: value to be excluded in output shape file
"""
nrows, ncols = block.shape
#start loop at first row, first col
yul = yll - nrows * cellsizeY # cellsizeY is negative
for row in np.arange(nrows):
for col in np.arange(ncols):
if block[row, col] == nodata:
continue
if filter is not None:
if block[row, col] <= filter:
continue
polygon = ogr.Geometry(ogr.wkbPolygon)
ring = ogr.Geometry(ogr.wkbLinearRing)
#Keep in mind that cellsizeY is assumed to be negative
ring.AddPoint(xll + col * cellsizeX,
yul + (row + 1) * cellsizeY) # lower left corner
ring.AddPoint(xll + col * cellsizeX,
yul + (row + 2) * cellsizeY) # upper left corner
ring.AddPoint(xll + col * cellsizeX + cellsizeX,
yul + (row + 2) * cellsizeY) # upper right corner
ring.AddPoint(xll + col * cellsizeX + cellsizeX,
yul + (row + 1) * cellsizeY) # lower right corner
ring.AddPoint(xll + col * cellsizeX,
yul + (row + 1) * cellsizeY) # close ring
#ring.CloseRings()
polygon.AddGeometry(ring)
featureDefn = layer.GetLayerDefn()
feature = ogr.Feature(featureDefn)
feature.SetGeometry(polygon)
feature.SetField(fieldName, float(block[row, col]))
layer.CreateFeature(feature)
polygon.Destroy()
feature.Destroy()
def block2point(block, layer, xll, yll, cellsizeX, cellsizeY, nodata,
fieldName, filter=None):
"""
Write a block to a polygon shape-file
@param block: raster block
@param layer: ogr layer object to write to
@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 fieldName: name of field to write
@param filter: value to be excluded in output shape file
"""
nrows, ncols = block.shape
#start loop at first row, first col
yul = yll - nrows * cellsizeY # cellsizeY is negative
for row in np.arange(nrows):
for col in np.arange(ncols):
if block[row, col] == nodata:
continue
if filter is not None:
if block[row, col] <= filter:
continue
point = ogr.Geometry(ogr.wkbPoint)
#Keep in mind that cellsizeY is assumed to be negative
point.AddPoint(xll + (col + 0.5) * cellsizeX,
yul + (row + 0.5) * cellsizeY)
featureDefn = layer.GetLayerDefn()
feature = ogr.Feature(featureDefn)
feature.SetGeometry(point)
feature.SetField(fieldName, float(block[row, col]))
layer.CreateFeature(feature)
point.Destroy()
feature.Destroy()
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("-l", "--loglevel",
action="store", dest="loglevel", default=2,
help="Sets the loglevel (0-3 where 3=full logging)")
parser.add_option("--no-progress",
action="store_const", dest="progressStream",
const=None, default=sys.stdout,
help="turn off the progress bar")
parser.add_option("-o", "--output",
action="store", dest="outfileName", default=None,
help="Output file")
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("--dataType",
action="store", dest="dataType",
help="Output data type",
default=None)
parser.add_option("--featureType",
action="store", dest="featureType",
help="Type of feature ('poly' or 'point')," +
" default='point'",
default='point')
parser.add_option("--fieldName", metavar='FIELD',
action="store", dest="fieldName",
help="write data in shape file to FIELD," +
" default='value'",
default='value')
parser.add_option("--filter",
action="store", dest="filter",
help="Filter out data equal or below" +
" limit in shape output",
default=None)
(options, args) = parser.parse_args()
#------------Setting up logging capabilities -----------
rootLogger = logger.RootLogger(int(options.loglevel))
global log
log = rootLogger.getLogger(sys.argv[0])
#------------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.outfileName is not None:
outFilePath = path.abspath(options.outfileName)
if ".shp" not in outFilePath:
log.error("Output shape must have .shp extension")
sys.exit(1)
else:
log.error("No output file specified")
sys.exit(1)
#Validate fieldName option
fieldName = options.fieldName
if fieldName == "":
parser.error("fieldName can't be an empty string")
#Validate filter option and convert filter to numeric value if present
if options.filter is not None:
filter = float(options.filter)
else:
filter = None
#validate featureType
if options.featureType not in ('point', 'poly'):
log.error("Invalid feature type, must be either 'point' or 'poly'")
sys.exit(1)
#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
rowmin = 0
colmin = 0
#Processing of data is made for blocks of the following size
#Important - blocks are set to cover all columns for simpler processing
#This might not always be optimal for read/write speed
procXBlockSize = ncols
procYBlockSize = 1
#process option for dataType
dataTypes, defaultDataType = ogrDataTypes, 'Real'
try:
dataType = dataTypes[options.dataType or defaultDataType]
except KeyError:
log.error(
"Unknown datatype choose between: %s" % ",".join(dataTypes.keys()))
sys.exit(1)
#Create and inititialize output vector data source
shapeDriver = ogr.GetDriverByName('ESRI Shapefile')
if path.exists(outFilePath):
shapeDriver.DeleteDataSource(outFilePath)
shapeFile = shapeDriver.CreateDataSource(outFilePath)
if shapeFile is None:
log.error("Could not open output shapefile %s" % outFilePath)
sys.exit(1)
if options.featureType == "point":
layer = shapeFile.CreateLayer(outFilePath, geom_type=ogr.wkbPoint)
else:
layer = shapeFile.CreateLayer(outFilePath, geom_type=ogr.wkbPolygon)
fieldDefn = ogr.FieldDefn(fieldName, dataType)
layer.CreateField(fieldDefn)
#Loop over block of raster (at least one row in each block)
rowsOffset = 0
pg = ProgressBar(nrows, options.progressStream)
for i in range(0, nrows, procYBlockSize):
pg.update(i)
data = band.ReadAsArray(xoff=colmin, yoff=rowmin + i,
win_xsize=procXBlockSize,
win_ysize=procYBlockSize)
blockYll = yul + i * cellsizeY # newCellsizeY is negative
blockXll = xll
if options.featureType == 'point':
block2point(data, layer, blockXll, blockYll, cellsizeX,
cellsizeY, nodata, fieldName, filter)
else:
block2poly(data, layer, blockXll, blockYll, cellsizeX,
cellsizeY, nodata, fieldName, filter)
rowsOffset += procYBlockSize # Update offset
shapeFile.Destroy()
pg.finished()
if __name__ == "__main__":
main()
# try:
# main()
# except:
# import pdb, sys
# e, m, tb = sys.exc_info()
# pdb.post_mortem(tb)