一般在面试中只会考察二维无旋转矩形框IOU的计算,更复杂的二维框带旋转、三维框等一般不会让写。
二维无旋转矩形框IOU计算
最简单的iou计算, 矩形框,无旋转
2个框的排布可能有下面三种情况,都需要考虑到
代码
#include <iostream>
#include <algorithm>
struct Rectangle {
float x1, y1, x2, y2; // 左上角和右下角坐标
};
float intersectionArea(const Rectangle& rect1, const Rectangle& rect2) {
float overlapWidth = std::max(0.0f, std::min(rect1.x2, rect2.x2) - std::max(rect1.x1, rect2.x1));
float overlapHeight = std::max(0.0f, std::min(rect1.y2, rect2.y2) - std::max(rect1.y1, rect2.y1));
return overlapWidth * overlapHeight;
}
float calculateIOU(const Rectangle& rect1, const Rectangle& rect2) {
float area1 = (rect1.x2 - rect1.x1) * (rect1.y2 - rect1.y1);
float area2 = (rect2.x2 - rect2.x1) * (rect2.y2 - rect2.y1);
float intersection = intersectionArea(rect1, rect2);
float unionArea = area1 + area2 - intersection;
return intersection / unionArea;
}
int main() {
Rectangle rect1 = {50, 50, 150, 150}; // 示例矩形1
Rectangle rect2 = {100, 100, 200, 200}; // 示例矩形2
float iou = calculateIOU(rect1, rect2);
std::cout << "IOU: " << iou << std::endl;
return 0;
}