倾斜框IOU计算实现(c++,python)

本文介绍了一种使用C++和Python实现的多边形交集算法,包括计算多边形面积、交集面积及IOU等关键步骤。通过两种不同的C++实现方式和Python调用Shapely库的方法,展示了如何处理复杂多边形的相交问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


c++实现方式1:

#include <iostream>
#include <vector>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <opencv2/opencv.hpp>
#include "caffe/nms.h"
using namespace std;
using namespace cv;

//cv::Point2f center;

//c++ 多边形求交集
//const int maxn = 300;
const double eps = 1e-8;
int dcmp(double x)
{
    if(x > eps) return 1;
    return x < -eps ? -1 : 0;
}
struct MyPoint
{
    double x, y;
};
double cross(MyPoint a,MyPoint b,MyPoint c) ///叉积
{
    return (a.x-c.x)*(b.y-c.y)-(b.x-c.x)*(a.y-c.y);
}
MyPoint intersection(MyPoint a,MyPoint b,MyPoint c,MyPoint d)
{
    MyPoint p = a;
    double t =((a.x-c.x)*(c.y-d.y)-(a.y-c.y)*(c.x-d.x))/((a.x-b.x)*(c.y-d.y)-(a.y-b.y)*(c.x-d.x));
    p.x +=(b.x-a.x)*t;
    p.y +=(b.y-a.y)*t;
    return p;
}
//计算多边形面积
double PolygonArea(MyPoint p[], int n)
{
    if(n < 3) return 0.0;
    double s = p[0].y * (p[n - 1].x - p[1].x);
    p[n] = p[0];
    for(int i = 1; i < n; ++ i)
        s += p[i].y * (p[i - 1].x - p[i + 1].x);
    return fabs(s * 0.5);
}
double CPIA(MyPoint a[], MyPoint b[], int na, int nb)//ConvexPolygonIntersectArea
{
    MyPoint p[20], tmp[20];
    int tn, sflag, eflag;
    a[na] = a[0], b[nb] = b[0];
    memcpy(p,b,sizeof(MyPoint)*(nb + 1));
    for(int i = 0; i < na && nb > 2; i++)
    {
        sflag = dcmp(cross(a[i + 1], p[0],a[i]));
        for(int j = tn = 0; j < nb; j++, sflag = eflag)
        {
            if(sflag>=0) tmp[tn++] = p[j];
            eflag = dcmp(cross(a[i + 1], p[j + 1],a[i]));
            if((sflag ^ eflag) == -2)
                tmp[tn++] = intersection(a[i], a[i + 1], p[j], p[j + 1]); ///求交点
        }
        memcpy(p, tmp, sizeof(MyPoint) * tn);
        nb = tn, p[nb] = p[0];
    }
    if(nb < 3) return 0.0;
    return PolygonArea(p, nb);
}
double SPIA(MyPoint a[], MyPoint b[], int na, int nb)///SimplePolygonIntersectArea 调用此函数
{
    int i, j;
    MyPoint t1[4], t2[4];
    double res = 0, num1, num2;
    a[na] = t1[0] = a[0], b[nb] = t2[0] = b[0];

    for(i = 2; i < na; i++)
    {
        t1[1] = a[i-1], t1[2] = a[i];
        num1 = dcmp(cross(t1[1], t1[2],t1[0]));
        if(num1 < 0) swap(t1[1], t1[2]);

        for(j = 2; j < nb; j++)
        {

            t2[1] = b[j - 1], t2[2] = b[j];
            num2 = dcmp(cross(t2[1], t2[2],t2[0]));
            if(num2 < 0) swap(t2[1], t2[2]);
            res += CPIA(t1, t2, 3, 3) * num1 * num2;
        }
    }
    return res;
}
//c++ 多边形求交集

double IOU(const proposal_type & r1, const proposal_type & r2)
{    
    double inter = intersection_area(r1,r2);

    double o = inter / (calcularea(r1) + calcularea(r2) - inter);

    return (o >= 0) ? o : 0;
}

double intersection_area(const proposal_type & r1, const proposal_type & r2){
    MyPoint p1[10],p2[10];
    
    p1[0].x=r1.x2;
    p1[0].y=r1.y2;
    p1[1].x=r1.x3;
    p1[1].y=r1.y3;
    p1[2].x=r1.x4;
    p1[2].y=r1.y4;
    p1[3].x=r1.x1;
    p1[3].y=r1.y1;

    p2[0].x=r2.x2;
    p2[0].y=r2.y2;
    p2[1].x=r2.x3;
    p2[1].y=r2.y3;
    p2[2].x=r2.x4;
    p2[2].y=r2.y4;
    p2[3].x=r2.x1;
    p2[3].y=r2.y1;
    double area = SPIA(p1, p2, 4, 4);
    return area;
}

double calcularea(const proposal_type & r){
    float d12=sqrt(pow(r.x2-r.x1,2)+pow(r.y2-r.y1,2));
    float d14=sqrt(pow(r.x4-r.x1,2)+pow(r.y4-r.y1,2));
    float d24=sqrt(pow(r.x2-r.x4,2)+pow(r.y2-r.y4,2));
    float d32=sqrt(pow(r.x2-r.x3,2)+pow(r.y2-r.y3,2));
    float d34=sqrt(pow(r.x3-r.x4,2)+pow(r.y3-r.y4,2));
    float p1=(d12+d14+d24)/2;
    float p2=(d24+d32+d34)/2;
    float s1=sqrt(p1*(p1-d12)*(p1-d14)*(p1-d24));
    float s2=sqrt(p2*(p2-d32)*(p2-d34)*(p2-d24));
    return s1+s2;
}

bool cmpr(const proposal_type &a,const proposal_type &b){
    return a.score > b.score;
}

void nms(vector<proposal_type>& proposals, const double nms_threshold)
{

    //按分数排序
    sort(proposals.begin(),proposals.end(),cmpr);
    //标志,false代表留下,true代表扔掉
    vector<bool> del(proposals.size(), false);
    for(size_t i = 0; i < proposals.size(); i++){
        if(!del[i]){
            // std::cout<<scores[i]<<std::endl;
            for(size_t j = i+1; j < proposals.size()-1; j++){
                if(!del[j] && IOU(proposals[i], proposals[j]) > nms_threshold){
                    del[j] = true;//IOU大于阈值,扔掉
                }
            }
        }
    }
/*for(int i=0;i<del.size();i++){
cout<<del[i]<<" ";
}*/
    vector<proposal_type> new_proposals;
    /*for(const auto i : index){
        if(!del[i]) new_proposals.push_back(proposals[i]);
    }*/
    for(int i=0;i<proposals.size();i++){
        if(!del[i]) new_proposals.push_back(proposals[i]);
    }
//cout<<new_proposals.size()<<endl;
    proposals.clear();
    vector<proposal_type>().swap(proposals);
    proposals = new_proposals;
//    cout<<proposals.size()<<endl;
    // scores.clear();
    //vector<float>().swap(scores);
}

c++实现方式2(调用opencv接口):


float calcIOU(cv::RotatedRect rect1, cv::RotatedRect rect2) {
    float areaRect1 = rect1.size.width * rect1.size.height;
    float areaRect2 = rect2.size.width * rect2.size.height;
    vector<cv::Point2f> vertices;

    int intersectionType = cv::rotatedRectangleIntersection(rect1, rect2, vertices);
    if (vertices.size()==0)
        return 0.0;
    else{
        vector<cv::Point2f> order_pts;
        // 找到交集(交集的区域),对轮廓的各个点进行排序

        cv::convexHull(cv::Mat(vertices), order_pts, true);
        double area = cv::contourArea(order_pts);
        float inner = (float) (area / (areaRect1 + areaRect2 - area + 0.0001));

        return inner;

    }

}

python实现(调用shapely):

from shapely.geometry import Polygon
def intersection(g, p):
    g=np.asarray(g)
    p=np.asarray(p)
    g = Polygon(g[:8].reshape((4, 2)))
    p = Polygon(p[:8].reshape((4, 2)))
    if not g.is_valid or not p.is_valid:
        return 0
    inter = Polygon(g).intersection(Polygon(p)).area
    union = g.area + p.area - inter
    if union == 0:
        return 0
    else:
        return inter/union

亲测,2种c++的实现方式结果相同。

 

 

<think>嗯,用户想用Python实现3DIOU计算方法。用户没有提问上下文,从当前请求和引用的资料来看,引用中提到了soft-NMS和IoU损失函数,但用户现在明确需要的是3D场景的交并比计算。3DIOU计算与2D处理有所不同,3D计算需要处理空间信息、三维旋转和不同朝向的物体。可以基于两个长方体在三个维度上的位置、尺寸和旋转角度来计算交集体积。虽然用户没说明具体应用场景,但结合引用中提到的YOLOv11模型,可能是用于自动驾驶或三维物体检测。用户需求可以分为几个关键点:一是需要能处理三维数据的数学方法,二是需要准确的体积计算逻辑,三是可能需要处理旋转的情况。可以基于标准流程构建解决方案:首先将3D参数解析为8个角点坐标,然后计算三维凸多面体交集,最后通过交集体积除以并集体积得到结果。用户应该还需要实用化的建议,比如选择凸包计算库。另外还需要警告用户:旋转处理比轴对齐复杂很多,可能存在边界情况处理问题。关于代码实现,可以给用户一个清晰的基础实现架,核心是三维凸包的交集计算。3DIOU计算流程:1.输入参数包括中心坐标(x,y,z)、尺寸(l,w,h)和旋转角,通常是yaw2.将两个的8个角点坐标转换到世界坐标系下3.构造两个凸多面体对象4.计算凸多面体相交部分的点集5.通过凸包重构交集多面体并计算体积6.计算并集体积:1体积+2体积-交集体积7.IOU=交集体积/并集体积如果用户对速度要求高,还可以补充说明:在非旋转时可以简化为轴对齐计算,这样无需凸包处理库也能快速实现。不过用户当前的引用提到PyTorch环境,可能更关注深度学习中的集成应用。</think> 以下是基于Python的3D IoU计算实现方案,结合空间几何计算和凸包处理,适用于自动驾驶、三维目标检测等场景: ```python import numpy as np from scipy.spatial import ConvexHull from scipy.spatial import Delaunay def get_box_corners(center, dims, rotation): """ 计算3D边界的8个角点 参数: center: [x, y, z] 中心坐标 dims: [l, w, h] 长宽高尺寸 rotation: yaw旋转角(弧度) 返回: (8, 3) 的角点坐标数组 """ l, w, h = dims # 基础立方体角点(局部坐标系) corners = np.array([ [l/2, w/2, h/2], [l/2, w/2, -h/2], [l/2, -w/2, h/2], [l/2, -w/2, -h/2], [-l/2, w/2, h/2], [-l/2, w/2, -h/2], [-l/2, -w/2, h/2], [-l/2, -w/2, -h/2] ]) # 旋转矩阵(yaw) rot_mat = np.array([ [np.cos(rotation), -np.sin(rotation), 0], [np.sin(rotation), np.cos(rotation), 0], [0, 0, 1] ]) # 旋转后平移至世界坐标系 return (rot_mat @ corners.T).T + center def convex_hull_intersection(points1, points2): """ 计算两个凸多面体的相交点集 """ hull1 = ConvexHull(points1) hull2 = ConvexHull(points2) # 寻找相交点 inter_points = [] for simplex in hull1.simplices: for point in points1[simplex]: if Delaunay(points2).find_simplex(point) >= 0: inter_points.append(point) for simplex in hull2.simplices: for point in points2[simplex]: if Delaunay(points1).find_simplex(point) >= 0: inter_points.append(point) return np.unique(np.array(inter_points), axis=0) if inter_points else np.array([]) def compute_3d_iou(box1, box2): """ 计算两个3D边界IoU 参数格式均为: (center, dimensions, rotation) """ # 获取角点 corners1 = get_box_corners(*box1) corners2 = get_box_corners(*box2) # 计算各自体积 vol1 = box1[1][0] * box1[1][1] * box1[1][2] # l*w*h vol2 = box2[1][0] * box2[1][1] * box2[1][2] # 计算交集点集 inter_points = convex_hull_intersection(corners1, corners2) # 计算交集体积 inter_vol = 0.0 if len(inter_points) > 4: # 至少需4个点构成多面体 inter_hull = ConvexHull(inter_points) inter_vol = inter_hull.volume # 计算并集体积 union_vol = vol1 + vol2 - inter_vol # 计算IoU return inter_vol / union_vol if union_vol > 1e-6 else 0.0 # ===== 使用示例 ===== if __name__ == "__main__": # 定义两个3D边界: (中心点, 尺寸, 旋转角) boxA = ([0,0,0], [4,2,1.5], np.pi/4) # 长4m 宽2m 高1.5m, 旋转45° boxB = ([1,1,0.3], [3,1.8,1.2], np.pi/6) iou = compute_3d_iou(boxA, boxB) print(f"3D IoU: {iou:.4f}") ``` ### 实现说明: 1. **空间变换原理** 通过旋转矩阵实现边界朝向变换: $$ R = \begin{bmatrix} \cos\theta & -\sin\theta & 0 \\ \sin\theta & \cos\theta & 0 \\ 0 & 0 & 1 \end{bmatrix} $$ 坐标变换公式:$\text{corners\_world} = R \cdot \text{corners\_local}^T + C$ 2. **几何处理优化** - 使用`ConvexHull`计算凸包体积避免凹面体错误 - 通过`Delaunay.find_simplex`快速检测点是否在多面体内 - 对空交集进行`1e-6`容错处理防止除零错误 3. **计算复杂度** - 角点变换:$O(1)$ - 凸包构建:$O(n\log n)$(n≤8) - 点集检测:$O(m\log m)$(m≤16) ### 扩展建议: 1. **性能优化**:大规模检测建议使用CUDA加速库如[Kaolin](https://kaolin.readthedocs.io/)或[Open3D](http://www.open3d.org/) 2. **损失函数集成**: ```python def IoU_Loss(pred, target): iou = compute_3d_iou(pred, target) return 1 - iou # 最小化IoU损失 ``` 3. **旋转表达**:对于复杂旋转场景,可将旋转参数从yaw扩展为四元数或旋转矩阵 ### 注意事项: - **精度问题**:边长小于0.01m可能引起浮点误差 - **退化情况**:两长方体完全平行时可用AABB算法加速 - **非凸形体**:凹面体需要先做三角剖分处理 > 科学计算库参考: > NumPy数组计算规范: [Array API Standard](https://data-apis.org/array-api/latest/) > Scipy空间算法实现原理: [Qhull Library](http://www.qhull.org/) [^2]
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值