Non-Max Suppression In Object Detection
Nabeelah Maryam
Research Student | Artificial Intelligence | Machine Learning |Computer Vision | Sharing My Learning Journey
Non-Max Suppression (NMS) is a crucial post-processing step in object detection algorithms like YOLO (You Only Look Once). It helps in refining the detection results by removing redundant or overlapping bounding boxes, ensuring that each object is represented by a single, precise bounding box. Here’s a detailed explanation of how NMS works in the context of YOLO:
Steps of Non-Max Suppression
Example
Assume YOLO detects the following boxes for an object:
领英推荐
Let's say our IoU threshold is 0.5.
Python Implementation Example
Here's a simple Python implementation of NMS for YOLO:
import numpy as np
def iou(box1, box2):
# Compute the intersection over union of two bounding boxes
x1, y1, x2, y2 = box1
x1_, y1_, x2_, y2_ = box2
xi1 = max(x1, x1_)
yi1 = max(y1, y1_)
xi2 = min(x2, x2_)
yi2 = min(y2, y2_)
inter_area = max(0, xi2 - xi1 + 1) * max(0, yi2 - yi1 + 1)
box1_area = (x2 - x1 + 1) * (y2 - y1 + 1)
box2_area = (x2_ - x1_ + 1) * (y2_ - y1_ + 1)
union_area = box1_area + box2_area - inter_area
return inter_area / union_area
def non_max_suppression(boxes, scores, threshold=0.5):
indices = np.argsort(scores)[::-1]
keep = []
while indices.size > 0:
i = indices[0]
keep.append(i)
rest_indices = indices[1:]
suppressed_indices = []
for j in rest_indices:
if iou(boxes[i], boxes[j]) > threshold:
suppressed_indices.append(j)
indices = np.delete(indices, np.where(np.isin(indices, suppressed_indices)))
indices = indices[1:]
return keep
# Example usage
boxes = np.array([[100, 100, 210, 210], [105, 105, 215, 215], [200, 200, 310, 310]])
scores = np.array([0.9, 0.85, 0.75])
kept_indices = non_max_suppression(boxes, scores, threshold=0.5)
kept_boxes = boxes[kept_indices]
print("Kept boxes:", kept_boxes)