3

Got this warning when trying to calculate the intersection between two geometry objects.

>>> shapely.intersection(LineString([(0, 0), (1, 1)], LineString([(2.5, 2.5), (3, 3)]))
.../lib/python3.9/site-packages/shapely/set_operations.py:133: RuntimeWarning: invalid value encountered in intersection
  return lib.intersection(a, b, **kwargs)
Anas
  • 91
  • 1
  • 8

1 Answers1

5

I think the warning occurs when there is no intersection at all between the two geometries, so what I did is to check if there is an intersection first with intersects() and only then calculate the intersection between them.

You can then handle the case where no intersection occurs according to your application.

def get_iou( polygon1, polygon2):
    if polygon1.intersects(polygon2): 
        intersect = polygon1.intersection(polygon2).area
        union = polygon1.union(polygon2).area
        return intersect/union
    return 0
Anas
  • 91
  • 1
  • 8
  • 1
    For an IoU calculation, the overhead of this is about 1.5-3us on my computer. You obviously get a huge speedup in the case when IoU is 0. I'd say it is definitely worth it. [Link to gist with profiling.](https://gist.github.com/michaelwooley/b1eaea53b3d764427125e3033a264fdd) – webelo Jul 07 '23 at 21:06