Fast contour set comparison?

I wouldn’t say its a trivial computation.

Naively:

def iou(mask1, mask2):
    return (mask1 & mask2).sum() / (mask1 | mask2).sum()

t = time.time()
for m1 in masks:
    for m2 in masks:
        iou(m1,m2)
print(f'{time.time()-t}:3.1f')

takes almost 9 seconds on my 24 core 3900x.
(here with ~24 masks).

I can spend time optimizing this… but what I’m looking for is a algorithm that efficiently compares the outlines of masks. Even this IOU case isn’t too great for me because new object the scene take a chomp out of the masks existing segments – the IOU score penalizes the lost space even though the contour may be very similar. Something like IOU of the contour mask with contourmask = mask & ~erode(mask,n) masks might be better for measuring whether a blob has the same shape? Perhaps there are even better measures of shape difference.