NMS アルゴリズムの C++ 実装
アルゴリズムの原理:
6 つの候補ボックスがあると仮定し、分類子カテゴリの分類確率に従って並べ替えます.小さい車両から大きい車両に属する確率は、それぞれ A、B、C、D、E、および F です。
最大確率の長方形フレーム(つまり、面積が最も大きいフレーム)F から始めて、A ~ E と F の重複度 IOU があるしきい値より大きいかどうかを判断し、B、D、F の重複度がしきい
_ B と D の領域は冗長です。F を使用します。これはオブジェクトを完全に表すことができるため、F を保持し、B、D を破棄します); そして、保持する最初の長方形フレーム F をマークします。
残りの長方形の箱 A、C、E から、最も確率の高い E を選択し、E と A、C の重複度を判定します。重複度が一定のしきい値を超える場合は破棄します。 2番目の長方形を保持するものとしてEをマークします。
このプロセスを常に繰り返して、保存されているすべての長方形を見つけます。
コードで定義されているボックスは、左上隅の x、y、幅 w、高さ h です。
#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>&vec_boxs,float threshold){
vector<Bbox>results;
std::sort(vec_boxs.begin(),vec_boxs.end(),sort_score);
while(vec_boxs.size() > 0)
{
results.push_back(vec_boxs[0]);
int index = 1;
while(index < vec_boxs.size()){
float iou_value = iou(vec_boxs[0],vec_boxs[index]);
cout << "iou:" << iou_value << endl;
if(iou_value > threshold)
vec_boxs.erase(vec_boxs.begin() + index);
else
index++;
}
vec_boxs.erase(vec_boxs.begin());
}
return results;
}
int main(){
vector<Bbox> input;
Bbox box1 = {
1,1,1,1,0.3};
Bbox box2 = {
0,0,2,2,0.4};
//Bbox box1 = {1,3,2,2,0.3}; //iou为负
//Bbox box2 = {0,0,2,2,0.4};
//Bbox box1 = {4,4,2,2,0.3};
//Bbox box2 = {0,0,2,2,0.4};
// Bbox box1 = {4,4,1,1,0.3};
// Bbox box2 = {0,0,2,2,0.4};
// Bbox box1 = {3,3,1,1,0.3};
// Bbox box2 = {0,0,2,2,0.4};
input.push_back(box1);
input.push_back(box2);
vector<Bbox> res;
res = nms(input, 0.2);
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;
}