3

The Python documentation for OGR lists a Polygonize() method belonging to the Geometry class, as does the C documentation. The docstring suggests it can be called on a geometry object of type "MultiLinestring", however doing so results in an AttributeError. Other methods such as Buffer() work fine.

Did they move or remove this in GDAL 2.x? Lib/site-packages/osgeo/ogr.py does not contain a Polygonize() function. It does say "OGR 1.9.0" in the documentation, but I would assume this normally means OGR >= 1.9.0.

Currently running gdal version 2.2.4.

Code sample:

multiline = ogr.Geometry(ogr.wkbMultiLineString)
multiline.AddGeometry(line)

polygon = multiline.Polygonize()

Results in:

AttributeError: type object 'object' has no attribute '__getattr__'

1 Answer 1

2

The Polygonize method is not available in the python bindings in GDAL 2.2.4. Although it has been around in the core C++ library since GDAL 1.9.0), it was only exposed in the python bindings at GDAL 2.3 (relevant commit).

However, a workaround is to use the ogr.BuildPolygonFromEdges method:

from osgeo import ogr
ogr.UseExceptions()

wkt = """LINESTRING(148.479859015579 -30.082172000762046,150.545288703079 -29.58660013074214,150.896851203079 -31.479043224714392,148.699585578079 -31.815735504845552,148.479859015579 -30.082172000762046)"""

line = ogr.CreateGeometryFromWkt(wkt)
multiline = ogr.Geometry(ogr.wkbMultiLineString)
multiline.AddGeometry(line)

polygon = ogr.BuildPolygonFromEdges(multiline)

print(polygon.ExportToWkt())

Outputs:

POLYGON ((148.479859015579 -30.082172000762,150.545288703079 -29.5866001307421,150.896851203079 -31.4790432247144,148.699585578079 -31.8157355048456,148.479859015579 -30.082172000762))

If you need the GEOS based Polygonize method, either use fiona and shapely or upgrade to gdal 2.3.

2
  • Thank you, this does indeed work. Unfortunately I'm looking for equivalent behavior to shapely's polygonize(), which is able to correct for self-intersections. The docs suggest that OGR's geom.Polygonize() uses GEOS, which is what shapely is based around, so I was hoping there'd be a 1:1 there
    – mikewatt
    Jul 24, 2018 at 16:19
  • Perfect, thank you! The answer I was looking for. I searched for a commit but I was looking in the wrong place. I ended up using shapely but I'll try updating GDAL instead, trying to avoid extra package requirements.
    – mikewatt
    Jul 25, 2018 at 18:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.