1、摘除每一类矩形框
2、通过得分阈值排序
3、通过计算iou排除大于iou阈值的矩形框,依次遍历。
代码:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef struct Bbox {
int x;
int y;
int w;
int h;
float score;
}Bbox;
static bool sort_score(Bbox box1,Bbox box2) {
return box1.score > box2.score ? true : false;
}
float iou(Bbox box1, Bbox box2) {
int x1 = max(box1.x, box2.x);
int y1 = max(box1.y, box2.y);
int x2 = min(box1.x + box1.w, box2.x + box2.w);
int y2 = min(box1.y + box1.h, box2.y + box2.h);
int w = max(0, x2 - x1);
int h = max(0, y2 - y1);
float over_area = w * h;
return over_area / (box1.w*box1.h + box2.w*box2.h - over_area);
}
vector<Bbox> nms(std::vector<Bbox>&boxes, float threshold)
{
vector<Bbox>resluts;
std::sort(boxes.begin(), boxes.end(), sort_score);
while (boxes.size()> 0)
{
resluts.push_back(boxes[0]);
int index = 1;
while (index < boxes.size()) {
float iou_value = iou(boxes[0], boxes[index]);
cout << "iou_value=" << iou_value << endl;
if (iou_value > threshold) {
boxes.erase(boxes.begin() + index);
}
else {
index++;
}
}
boxes.erase(boxes.begin());
}
return resluts;
}
int main() {
vector<Bbox> input;
Bbox box1 = { 10,10,10,10,0.5 };
Bbox box2 = { 0,0,20,20,0.6 };
input.push_back(box1);
input.push_back(box2);
vector<Bbox> res;
res = nms(input, 0.15);
for (int i = 0; i < res.size(); i++) {
printf("%d %d %d %d %f", res[i].x, res[i].y, res[i].w, res[i].h, res[i].score);
cout << endl;
}
return 0;
}