在目标检测中,常常须要计算IOU。也就是两个矩形的交集除以两个矩形的并集。这里使用OpevCV的Rect来进行IOU的计算。ios
【场景一】无交集,IOU为0ui
#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"); }
结果为:spa
【场景一】有交集,IOU为0.44444code
#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坐标系为:io
总结:能够看出,使用opencv计算IOU比较简单,只须要三行代码,固然,本身手动计算,也不费事,只是须要判断各类场景而已。opencv