Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute IOU(overlaps) using 2 pandas DataFrames

In object detection, IOU(intersection over union) is a value between 0 and 1 that represents the percentage of overlap between 2 boxes drawn on an object in a certain image.

To help you understand what that is, here's an illustration:

iou

The red frame is the real value with coordinates x1(top left), y1(bottom left), x2(top right), y2(bottom right).

The purple frame is the predicted value with coordinates x1_predicted, y1_predicted, x2_predicted, y2_predicted.

The yellow shaded square is the iou, if it's value is greater than a certain threshold(0.5 by convention) the prediction evaluates as True, otherwise it's a False.

Here's the code that calculates IOU for 2 boxes:

def get_iou(box_true, box_predicted):
    x1, y1, x2, y2 = box_true
    x1p, y1p, x2p, y2p = box_predicted
    if not all([x2 > x1, y2 > y1, x2p > x1p, y2p > y1p]):
        return 0
    far_x = np.min([x2, x2p])
    near_x = np.max([x1, x1p])
    far_y = np.min([y2, y2p])
    near_y = np.max([y1, y1p])
    inter_area = (far_x - near_x + 1) * (far_y - near_y + 1)
    true_box_area = (x2 - x1 + 1) * (y2 - y1 + 1)
    pred_box_area = (x2p - x1p + 1) * (y2p - y1p + 1)
    iou = inter_area / (true_box_area + pred_box_area - inter_area)
    return iou

I have the predictions and the actual data contained in 2 csv files which I read into 2 pandas DataFrame objects and go from there.

For every image, I extract detections of a certain object type (ex: car) and the actual data, here's an example for 1 object(car) in 1 image(Beverly_hills1.png)

Actual:
              Image Path Object Name  X_min  Y_min  X_max  Y_max
3842  Beverly_hills1.png         Car    760    432    911    550
3843  Beverly_hills1.png         Car    612    427    732    526
3844  Beverly_hills1.png         Car    462    412    597    526
3845  Beverly_hills1.png         Car    371    432    544    568

Detections:
                  image object_name   x1   y1   x2   y2
594  Beverly_hills1.png         Car  612  422  737  539
595  Beverly_hills1.png         Car  383  414  560  583

Here's how I would compare:

def calculate_overlaps(self, detections, actual):
    calculations = []
    detection_groups = detections.groupby('image')
    actual_groups = actual.groupby('Image Path')
    for item1, item2 in zip(actual_groups, detection_groups):
        for detected_index, detected_row in item2[1].iterrows():
            detected_coordinates = detected_row.values[2: 6]
            detected_overlaps = []
            coords = []
            for actual_index, actual_row in item1[1].iterrows():
                actual_coordinates = actual_row.values[4: 8]
                detected_overlaps.append((
                    self.get_iou(actual_coordinates, detected_coordinates)))
                coords.append(actual_coordinates)
            detected_row['max_iou'] = max(detected_overlaps)
            x1, y1, x2, y2 = coords[int(np.argmax(detected_overlaps))]
            for match, value in zip([f'{item}_match'
                                     for item in ['x1', 'y1', 'x2', 'y2']],
                                    [x1, y1, x2, y2]):
                detected_row[match] = value
            calculations.append(detected_row)
    return pd.DataFrame(calculations)

For every object type this will run which is inefficient.

The end result will look like this:

                     image object_name    x1  ...  y1_match  x2_match  y2_match
594     Beverly_hills1.png         Car   612  ...       427       732       526
595     Beverly_hills1.png         Car   383  ...       432       544       568
1901   Beverly_hills10.png         Car   785  ...       432       940       578
2015  Beverly_hills101.png         Car   832  ...       483      1240       579
2708  Beverly_hills103.png         Car   376  ...       466      1333       741
...                    ...         ...   ...  ...       ...       ...       ...
618    Beverly_hills93.png         Car   922  ...       406       851       659
625    Beverly_hills93.png         Car  1002  ...       406       851       659
1081   Beverly_hills94.png         Car   398  ...       426       527       559
1745   Beverly_hills95.png         Car  1159  ...       438       470       454
1746   Beverly_hills95.png         Car   765  ...       441       772       474

[584 rows x 14 columns]

How to simplify / vectorize this and eliminate for loops? can this be done using np.where()?


1 Answers

First, I noticed your get_iou function has a condition: x2 > x1, y2 > y1, x2p > x1p, y2p > y1p. You should make sure that condition holds for both data frames.

Second, the actual has columns Image Path and Object Name, while detections has image and object_name. You may want to change the corresponding columns to one single name.

That said, here's my solution with merge:

def area(df,columns):
    '''
    compute the box area 
    @param df: a dataframe
    @param columns: box coordinates (x_min, y_min, x_max, y_max)
    '''
    x1,y1,x2,y2 = [df[col] for col in columns]
    return (x2-x1)*(y2-y1)

# rename the columns
actual = actual.rename(columns={'Image Path':'image', 'Object Name':'object_name'})

# merge on `image` and `object_name`
total_df = (actual.merge(detections, on=['image', 'object_name'])

# compute the intersection
total_df['x_max_common'] = total_df[['X_max','x2']].min(1)
total_df['x_min_common'] = total_df[['X_min','x1']].max(1)
total_df['y_max_common'] = total_df[['Y_max','y2']].min(1)
total_df['y_min_common'] = total_df[['Y_min','y1']].max(1)

# valid intersection
true_intersect = (total_df['x_max_common'] > total_df['x_min_common']) & \
                 (total_df['y_max_common'] > total_df['y_min_common'])

# filter total_df with valid intersection
total_df = total_df[true_intersect]

# the various areas
actual_areas = area(total_df, ['X_min','Y_min','X_max','Y_max'])
predicted_areas = area(total_df, ['x1','y1','x2','y2'])
intersect_areas = area(total_df,['x_min_common','y_min_common','x_max_common', 'y_max_common'])

# IOU
iou_areas = intersect_areas/(actual_areas + predicted_areas - intersect_areas)

# assign the IOU to total_df
total_df['IOU'] = iou_areas
like image 87
Quang Hoang Avatar answered Jan 21 '26 07:01

Quang Hoang