非极大值抑制用C语言实现
时间: 2024-01-21 16:07:41 浏览: 85
C#图像处理程序实现--Canny实现 笔记整理(其中的非极大值抑制点).rar
非极大值抑制(Non-Maximum Suppression,NMS)是一种常用于目标检测中的算法,其目的是从一组重叠的候选框中选择出最佳的框。
在C语言中,实现非极大值抑制的步骤如下:
1. 定义一个结构体来表示候选框,包括左上角坐标、右下角坐标、得分等信息。
```
typedef struct {
int x1, y1, x2, y2;
float score;
} Box;
```
2. 定义一个比较函数,用于按照得分从高到低排序。
```
int compare(const void *a, const void *b) {
Box *box1 = (Box *)a;
Box *box2 = (Box *)b;
if (box1->score < box2->score) {
return 1;
} else if (box1->score > box2->score) {
return -1;
} else {
return 0;
}
}
```
3. 对所有候选框按照得分从高到低排序。
```
qsort(boxes, num_boxes, sizeof(Box), compare);
```
4. 定义一个数组来保存每个候选框是否被保留的标志,初始值为0。
```
int *keep = (int *)calloc(num_boxes, sizeof(int));
```
5. 遍历所有候选框,对于每个框,如果其与已经被保留的框的重叠面积大于一定阈值,则将其标记为不保留。
```
for (int i = 0; i < num_boxes; i++) {
if (keep[i]) {
continue;
}
for (int j = i + 1; j < num_boxes; j++) {
if (iou(boxes[i], boxes[j]) > thresh) {
keep[j] = 0;
}
}
}
```
6. 将所有被保留的框保存到一个新的数组中。
```
Box *result_boxes = (Box *)malloc(num_boxes * sizeof(Box));
int count = 0;
for (int i = 0; i < num_boxes; i++) {
if (keep[i]) {
result_boxes[count++] = boxes[i];
}
}
```
完整的C语言实现代码如下:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int x1, y1, x2, y2;
float score;
} Box;
int compare(const void *a, const void *b) {
Box *box1 = (Box *)a;
Box *box2 = (Box *)b;
if (box1->score < box2->score) {
return 1;
} else if (box1->score > box2->score) {
return -1;
} else {
return 0;
}
}
float iou(Box box1, Box box2) {
int x_overlap = fmin(box1.x2, box2.x2) - fmax(box1.x1, box2.x1);
int y_overlap = fmin(box1.y2, box2.y2) - fmax(box1.y1, box2.y1);
if (x_overlap > 0 && y_overlap > 0) {
float intersection = x_overlap * y_overlap;
float area1 = (box1.x2 - box1.x1) * (box1.y2 - box1.y1);
float area2 = (box2.x2 - box2.x1) * (box2.y2 - box2.y1);
float union_ = area1 + area2 - intersection;
return intersection / union_;
} else {
return 0.0;
}
}
Box *nms(Box *boxes, int num_boxes, float thresh, int *num_out) {
qsort(boxes, num_boxes, sizeof(Box), compare);
int *keep = (int *)calloc(num_boxes, sizeof(int));
for (int i = 0; i < num_boxes; i++) {
if (keep[i]) {
continue;
}
for (int j = i + 1; j < num_boxes; j++) {
if (iou(boxes[i], boxes[j]) > thresh) {
keep[j] = 0;
}
}
}
Box *result_boxes = (Box *)malloc(num_boxes * sizeof(Box));
int count = 0;
for (int i = 0; i < num_boxes; i++) {
if (keep[i]) {
result_boxes[count++] = boxes[i];
}
}
*num_out = count;
free(keep);
return result_boxes;
}
int main() {
Box boxes[] = {
{10, 10, 50, 50, 0.9},
{20, 20, 60, 60, 0.8},
{30, 30, 70, 70, 0.7},
{40, 40, 80, 80, 0.6},
{50, 50, 90, 90, 0.5},
};
int num_boxes = 5;
int num_out;
Box *result_boxes = nms(boxes, num_boxes, 0.5, &num_out);
for (int i = 0; i < num_out; i++) {
printf("(%d, %d, %d, %d, %.2f)\n", result_boxes[i].x1, result_boxes[i].y1, result_boxes[i].x2, result_boxes[i].y2, result_boxes[i].score);
}
free(result_boxes);
return 0;
}
```
阅读全文