【OpenCV系列】【二】利用Rect計算IOU

在目標檢測中,常常須要計算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

相關文章
相關標籤/搜索