Пример #1
0
def computeIoU(BBox1, BBox2):
    '''
	Compute the IoU (Intersection over Union) between 2 rectangular bounding boxes defined by the top left (Xtop,Ytop) and bottom right (Xbot, Ybot) pixel coordinates
	Code adapted from https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/
	'''
    #print 'BBox1 : ', BBox1
    #print 'BBox2 : ', BBox2

    # Unpack input (python3 - tuple input are no more supported)
    Xleft1, Ytop1, Width1, Height1 = BBox1
    Xleft2, Ytop2, Width2, Height2 = BBox2

    # Compute bottom coordinates
    Xright1 = Xleft1 + Width1 - 1  # we remove -1 from the width since we start with 1 pixel already (the top one)
    Ybot1 = Ytop1 + Height1 - 1  # idem for the height

    Xright2 = Xleft2 + Width2 - 1
    Ybot2 = Ytop2 + Height2 - 1

    # determine the (x, y)-coordinates of the top left and bottom right points of the intersection rectangle
    Xleft = max(Xleft1, Xleft2)
    Ytop = max(Ytop1, Ytop2)
    Xright = min(Xright1, Xright2)
    Ybot = min(Ybot1, Ybot2)

    # Generate a Roi for the BBox just to be able to check that the BBox are not contained within another
    Roi1 = Roi(Xleft1, Ytop1, Width1, Height1)
    Roi2 = Roi(Xleft2, Ytop2, Width2, Height2)

    # Get boolean if BBox within another one (simply test contain with each corner point)
    Roi1_in_Roi2 = Roi2.contains(Xleft1, Ytop1) and Roi2.contains(
        Xright1, Ytop1) and Roi2.contains(Xleft1, Ybot1) and Roi2.contains(
            Xright1, Ybot1)
    Roi2_in_Roi1 = Roi1.contains(Xleft2, Ytop2) and Roi1.contains(
        Xright2, Ytop2) and Roi1.contains(Xleft2, Ybot2) and Roi1.contains(
            Xright2, Ybot2)

    if Roi1_in_Roi2 or Roi2_in_Roi1:
        #print '1 BBox is included within the other'
        IoU = 1  # otherwise using the formula below we have value below 1 eventhough the bbox are included

    elif Xright < Xleft or Ybot < Ytop:  #  (Y axis oriented towards the bottom of the screen) Check that for the intersection box, Xtop,Ytop is indeed on the top left of Xbot,Ybot otherwise it means that there is no intersection (bbox is inverted)
        #print 'No overlap'
        IoU = 0

    else:
        # Compute area of the intersecting box
        Inter = (Xright - Xleft + 1) * (
            Ybot - Ytop + 1
        )  # +1 since we are dealing with pixels. See a 1D example with 3 pixels for instance
        #print('Intersection area : ', Inter)

        # Compute area of the union as Sum of the 2 BBox area - Intersection
        Union = Width1 * Height1 + Width2 * Height2 - Inter
        #print('Union : ', Union)

        # Compute Intersection over union
        IoU = Inter / Union

    #print 'IoU : ', IoU
    return IoU