面试题-手撕IOU计算

一般在面试中只会考察二维无旋转矩形框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;
}

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值