Matthias Müller
2013-07-31 09:15:05 UTC
Hello everybody,
is there an efficient way to create a large number of polygons from a
numpy array?
In my case I have one array "vericesXY" which contains the vertices of
2108 polygons:
'''
some code that calculates the vertices
and writes them to an array verticesXY
'''
print verticesXY.shape
(379440, 2)
Then I obtain each polygon's vertices by splitting verticesXY:
(all polygons happen to have the same number of corners)
verticesXYList = np.array_split(verticesXY, 2108)
polys = []
for item in verticesXYList:
polys.append(Polygon(item))
These are the timings:
- calculate vertices: 0.8 sec
- create polygons: 3.0 sec
So the current bottleneck is not the vertex computation buth the loop
that creates the objects.
My next idea was to avoid that loop and speed up instantiation by first
creating a multipolygon from the verticesXYList and then obtain the
individual polygons with
multiPoly = MultiPolygon(someNumpyArray)
polys = multipolygon.geoms
But there I got stuck with the MultiPolygon constructor for which I
can't generate an appropriate numpy array of the right form [1]. - What
gives me headaches are the mandatory empty elements that represent the
holes.
- Matthias
[1]: (taken from shapely source code documentation)
ob = MultiPolygon([
(( (0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0) ), []),
(( (2.0, 2.0), (2.0, 3.0), (3.0, 3.0), (3.0, 2.0) ), []),
...
])
is there an efficient way to create a large number of polygons from a
numpy array?
In my case I have one array "vericesXY" which contains the vertices of
2108 polygons:
'''
some code that calculates the vertices
and writes them to an array verticesXY
'''
print verticesXY.shape
(379440, 2)
Then I obtain each polygon's vertices by splitting verticesXY:
(all polygons happen to have the same number of corners)
verticesXYList = np.array_split(verticesXY, 2108)
polys = []
for item in verticesXYList:
polys.append(Polygon(item))
These are the timings:
- calculate vertices: 0.8 sec
- create polygons: 3.0 sec
So the current bottleneck is not the vertex computation buth the loop
that creates the objects.
My next idea was to avoid that loop and speed up instantiation by first
creating a multipolygon from the verticesXYList and then obtain the
individual polygons with
multiPoly = MultiPolygon(someNumpyArray)
polys = multipolygon.geoms
But there I got stuck with the MultiPolygon constructor for which I
can't generate an appropriate numpy array of the right form [1]. - What
gives me headaches are the mandatory empty elements that represent the
holes.
- Matthias
[1]: (taken from shapely source code documentation)
ob = MultiPolygon([
(( (0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0) ), []),
(( (2.0, 2.0), (2.0, 3.0), (3.0, 3.0), (3.0, 2.0) ), []),
...
])