Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Member-only story

Understanding Non-Maximum Suppression (NMS) in Object Detection

NGU
Level Up Coding
Published in
4 min read4 days ago

The Key to Accurate Object Detection

Introduction

Non-Maximum Suppression (NMS) is a crucial post-processing technique in object detection that helps eliminate redundant and overlapping bounding boxes. It ensures that each detected object is represented by only one bounding box, improving the clarity and accuracy of predictions. NMS is widely used in modern object detection models, including YOLO, Faster R-CNN, and SSD.

How Does NMS Work?

The primary goal of NMS is to filter out multiple, overlapping predictions for the same object. It follows these steps:

  1. Sort Predictions by Confidence Score:
  • The model generates multiple bounding boxes for a detected object, each with a confidence score.
  • Sort all the boxes in descending order of their confidence scores.

2. Select the Box with the Highest Confidence:

  • Pick the bounding box with the highest confidence score and retain it as a final detection.

3. Suppress Overlapping Boxes:

  • Compute the Intersection over Union (IoU) between the retained box and all remaining boxes.
  • Discard boxes that have an IoU greater than a set threshold (e.g., 0.5).

4. Repeat Until No More Boxes Remain:

  • Continue selecting the box with the highest confidence and removing overlapping boxes until all have been processed.

Code Example: Implementing NMS in Python

Here’s a simple Python implementation of NMS using OpenCV and NumPy:

import numpy as np
import cv2

def non_max_suppression(boxes, scores, iou_threshold=0.5):
"""
Perform Non-Maximum Suppression (NMS) on bounding boxes.
:param boxes: List of bounding boxes in (x1, y1, x2, y2) format.
:param scores: List of confidence scores.
:param iou_threshold: IoU threshold for suppression.
:return: List of indices of selected boxes.
"""

indices = cv2.dnn.NMSBoxes(boxes, scores, score_threshold=0.3, nms_threshold=iou_threshold)
return indices.flatten() if len(indices) > 0 else []
# Example bounding boxes and confidence scores
boxes = [(100, 100, 200, 200), (110, 110, 210, 210), (120, 120, 220, 220), (300, 300, 400, 400)]
scores = [0.9, 0.75

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Written by NGU

Microservices. Cloud Native. Architecture. Record Technology, Sports, Life. A picture is worth a thousand words

No responses yet

Write a response