shapely.make_valid#
- make_valid(geometry, *, method='linework', keep_collapsed=True, **kwargs)#
Repair invalid geometries.
Two
methodsare available:the ‘linework’ algorithm tries to preserve every edge and vertex in the input. It combines all rings into a set of noded lines and then extracts valid polygons from that linework. An alternating even-odd strategy is used to assign areas as interior or exterior. A disadvantage is that for some relatively simple invalid geometries this produces rather complex results.
the ‘structure’ algorithm tries to reason from the structure of the input to find the ‘correct’ repair: exterior rings bound area, interior holes exclude area. It first makes all rings valid, then shells are merged and holes are subtracted from the shells to generate valid result. It assumes that holes and shells are correctly categorized in the input geometry.
Example:
(
Source code,png,hires.png,pdf)
When using
make_validon a Polygon, the result can be a GeometryCollection. For this example this is the case when the ‘linework’methodis used. LineStrings in the result are drawn in red.- Parameters:
- geometryGeometry or array_like
Geometry or geometries to repair.
- method{‘linework’, ‘structure’}, default ‘linework’
Algorithm to use when repairing geometry. ‘structure’ requires GEOS >= 3.10.
Added in version 2.1.0.
- keep_collapsedbool, default True
For the ‘structure’ method, True will keep components that have collapsed into a lower dimensionality. For example, a ring collapsing to a line, or a line collapsing to a point. Must be True for the ‘linework’ method.
Added in version 2.1.0.
- **kwargs
See NumPy ufunc docs for other keyword arguments.
Examples
>>> import shapely >>> from shapely import Polygon >>> polygon = Polygon([(0, 0), (1, 1), (1, 2), (1, 1), (0, 0)]) >>> shapely.is_valid(polygon) False >>> shapely.make_valid(polygon) <MULTILINESTRING ((0 0, 1 1), (1 1, 1 2))> >>> shapely.make_valid(polygon, method="structure", keep_collapsed=True) <LINESTRING (0 0, 1 1, 1 2, 1 1, 0 0)> >>> shapely.make_valid(polygon, method="structure", keep_collapsed=False) <POLYGON EMPTY>