在目标检测中,经常需要计算IOU。也就是两个矩形的交集除以两个矩形的并集。这里使用OpevCV的Rect来进行IOU的计算。
【场景一】无交集,IOU为0
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int main() {
Rect rect;
rect.x = 0;
rect.y = 0;
rect.width = 10;
rect.height = 10;
Rect rect1;
rect1.x = 10;
rect1.y = 10;
rect1.width = 10;
rect1.height = 10;
//计算两个矩形的交集
Rect rect2 = rect | rect1;
cout << rect2.x <<";"<< rect2.y << ";"<<rect2.width <<";"<< rect2.height <<";"<< rect2.area() << endl;
//计算两个举行的并集
Rect rect3 = rect & rect1;
cout << rect3.x << ";" << rect3.y << ";" << rect3.width << ";" << rect3.height << ";" << rect3.area() << endl;
//计算IOU
double IOU = rect3.area() *1.0/ rect2.area();
cout << "IOU=" << IOU << endl;
system("Pause");
}
结果为:
【场景一】有交集,IOU为0.44444
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int main() {
Rect rect;
rect.x = 0;
rect.y = 0;
rect.width = 10;
rect.height = 10;
Rect rect1;
rect1.x = 2;
rect1.y = 2;
rect1.width = 10;
rect1.height = 10;
//计算两个矩形的交集
Rect rect2 = rect | rect1;
cout << rect2.x <<";"<< rect2.y << ";"<<rect2.width <<";"<< rect2.height <<";"<< rect2.area() << endl;
//计算两个举行的并集
Rect rect3 = rect & rect1;
cout << rect3.x << ";" << rect3.y << ";" << rect3.width << ";" << rect3.height << ";" << rect3.area() << endl;
//计算IOU
double IOU = rect3.area()*1.0 / rect2.area();
cout << "IOU=" << IOU << endl;
system("Pause");
}
Rect坐标系为:
总结:可以看出,使用opencv计算IOU比较简单,只需要三行代码,当然,自己手动计算,也不费事,只是需要判断各种场景而已。