1

I'm having trouble while trying to create polygon using the shapely library in python.

[testPolygon(polygonShape) for polygonShape in fileAppender]

and the testPolygon function is defined as:

def testPolygon(polygonShape): 
    if shapely.wkt.loads(polygonShape).is_valid:
        print("great")

but I'm having this error:

IllegalArgumentException: Invalid number of points in LinearRing found 3 - must be 0 or >= 4

Is there anyway to check if the string object (polygonShape) is a valid polygon before parse it? Or even better, if it's possible to correct this corrupt polygon?

Paulo Calado
  • 195
  • 1
  • 3
  • 7

1 Answers1

1

Your LineString wkt is likely containing a geometry that is not a valid polygon. For example:

>>> from shapely.geometry import Polygon
>>> from shapely.wkt import loads

>>> wkt = 'LINESTRING (0 0, 1 1, 0 0)'
>>> poly = Polygon(loads(wkt).coords)

As you can see the LineString does start and end at the same vertex and has multiple edges, but it doesn't make it a polygon since you only have 3 points, i.e. "Invalid number of points in LinearRing found 3":

IllegalArgumentException: Invalid number of points in LinearRing found 3 - must be 0 or >= 4
Shell is not a LinearRing

but poly is still an object of type Polygon

>>> type(poly)
<class 'shapely.geometry.polygon.Polygon'>

so you can check if it's a valid polygon by:

>>> poly.is_empty
True

Why would you want to check if it's a valid polygon this way? Because IllegalArgumentException is NOT an actual exception as in you can't catch it with try/except. I don't know why. I hope someone in the comments knows.

Michael Kelso
  • 151
  • 1
  • 8