请问非极大值抑制的代码用python怎么写?
时间: 2023-12-17 17:48:30 浏览: 62
python 实现非极大值抑制算法(Non-maximum suppression, NMS)
可以使用以下代码实现非极大值抑制:
```Python
def non_max_suppression(boxes, scores, threshold):
"""
Perform non-maximum suppression to a set of boxes with their corresponding scores.
Args:
boxes: Tensor of bounding boxes, shape=(num_boxes, 4).
scores: Tensor of scores, shape=(num_boxes,).
threshold: Threshold to control overlapping between boxes.
Returns:
List of selected box indices after non-maximum suppression.
"""
selected_indices = []
# Sort boxes based on scores in descending order
sorted_indices = np.argsort(scores)[::-1]
while len(sorted_indices) > 0:
# Select the box with highest score and add to selected indices
current_index = sorted_indices[0]
selected_indices.append(current_index)
# Compute IoU between current box and all other boxes
current_box = boxes[current_index]
current_box = np.expand_dims(current_box, axis=0)
other_boxes = np.delete(boxes, current_index, axis=0)
ious = calculate_iou(current_box, other_boxes)
# Remove boxes with high overlap from sorted indices
overlapping_indices = np.where(ious > threshold)[0]
sorted_indices = np.delete(sorted_indices, overlapping_indices + 1)
return selected_indices
```
阅读全文