def IoU(rect1, rect2):
    """ Calculates IoU of two rectangles.
        Assumes rectanles are in ltrb (left, right, top, bottom) format.
        ltrb is also known as x1y1x2y2 format, whch is two corners
    """
    intersection = max( min(rect1[2], rect2[2]) - max(rect1[0], rect2[0]), 0 ) * \
                   max( min(rect1[3], rect2[3]) - max(rect1[1], rect2[1]), 0 )

    # A1 + A2 - I
    union = (rect1[2] - rect1[0]) * (rect1[3] - rect1[1]) + \
            (rect2[2] - rect2[0]) * (rect2[3] - rect2[1]) - \
            intersection 

    return float(intersection) / max(union, .00001)