Task: Implement Non-Maximum Suppression (NMS)
Non-Maximum Suppression is a critical post-processing technique in object detection pipelines. When object detectors like YOLO, SSD, or Faster R-CNN generate predictions, they often produce multiple overlapping bounding boxes for the same object. NMS filters these redundant detections by keeping only the most confident box and suppressing boxes that significantly overlap with it.
Input:
boxes: An array-like of shape (N, 4) containing N bounding boxes in format [x1, y1, x2, y2] where (x1, y1) is the top-left corner and (x2, y2) is the bottom-right cornerscores: An array-like of shape (N,) containing confidence scores for each boxiou_threshold: A float between 0 and 1 specifying the Intersection over Union threshold for suppression
Output:
- Return a list of indices of the kept boxes, ordered by descending confidence score
- Return -1 for invalid inputs (mismatched dimensions, invalid shapes, threshold out of range)
- Return empty list for empty input
Algorithm Overview:
- Select the box with the highest confidence score
- Remove all boxes that have high IoU overlap with the selected box
- Repeat until no boxes remain
IoU (Intersection over Union):
The IoU between two boxes measures their overlap and is computed as the area of intersection divided by the area of union.
Examples
Example 1:
Input:
boxes = [[0, 0, 10, 10], [1, 1, 11, 11], [20, 20, 30, 30], [21, 21, 31, 31]]
scores = [0.9, 0.8, 0.95, 0.7]
iou_threshold = 0.5Output:
[2, 0]Explanation: Box 2 (score 0.95) at [20,20,30,30] is selected first as it has the highest score. Box 3 (score 0.7) overlaps significantly with Box 2 (IoU = 81/119 = 0.68 > 0.5), so it is suppressed. Box 0 (score 0.9) at [0,0,10,10] is selected next. Box 1 (score 0.8) overlaps significantly with Box 0 (IoU = 81/119 = 0.68 > 0.5), so it is suppressed. Final result: indices [2, 0].
Starter Code
import numpy as np
def non_maximum_suppression(boxes, scores, iou_threshold):
"""
Apply Non-Maximum Suppression (NMS) to bounding boxes.
Args:
boxes: Array-like of shape (N, 4) with boxes in format [x1, y1, x2, y2]
scores: Array-like of shape (N,) with confidence scores
iou_threshold: float, IoU threshold for suppression (0 to 1)
Returns:
List of indices of kept boxes, ordered by descending score
Returns -1 for invalid inputs
"""
# Your code here
passPython3
ReadyLines: 1Characters: 0
Ready