opencv c++计算2个矩形的交并比
时间: 2024-03-27 10:37:52 浏览: 269
C++判断矩形相交的方法
5星 · 资源好评率100%
要计算两个矩形的交并比,可以使用OpenCV中的Rect对象和相应的函数进行计算。假设有两个矩形rect1和rect2,可以按照以下步骤计算它们的交并比:
1. 计算两个矩形的交集,可以使用Rect类的intersection()函数:
```
Rect intersection = rect1 & rect2;
```
2. 计算两个矩形的并集,可以使用Rect类的union()函数:
```
Rect union_rect = rect1 | rect2;
```
3. 计算交并比,可以使用交集面积除以并集面积:
```
double iou = (double)intersection.area() / (double)union_rect.area();
```
完整代码如下:
```
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
Rect rect1(50, 50, 100, 100);
Rect rect2(70, 70, 100, 100);
Rect intersection = rect1 & rect2;
Rect union_rect = rect1 | rect2;
double iou = (double)intersection.area() / (double)union_rect.area();
cout << "Intersection: " << intersection << endl;
cout << "Union: " << union_rect << endl;
cout << "IoU: " << iou << endl;
return 0;
}
```
输出结果为:
```
Intersection: [70 x 80 from (70, 70)]
Union: [150 x 130 from (50, 50)]
IoU: 0.410256
```
阅读全文