OpenCV结构分析与形状描述符(24)检测两个旋转矩形之间是否相交的一个函数rotatedRectangleIntersection()的使用

  • 操作系统:ubuntu22.04
  • OpenCV版本:OpenCV4.9
  • IDE:Visual Studio Code
  • 编程语言:C++11

算法描述

测两个旋转矩形之间是否存在交集。

如果存在交集,则还返回交集区域的顶点。

下面是一些交集配置的例子。斜线图案表示交集区域,红色顶点是由函数返回的。

rotatedRectangleIntersection() 这个函数看起来像是用于检测两个旋转矩形之间是否相交的一个方法。在计算机图形学和游戏开发中,检测两个旋转矩形是否相交是一个常见的需求,尤其是在物理引擎或碰撞检测系统中。

函数原型

cpp 复制代码
int cv::rotatedRectangleIntersection	
(
	const RotatedRect & 	rect1,
	const RotatedRect & 	rect2,
	OutputArray 	intersectingRegion 
)		

参数

  • 参数rect1 第一个矩形
  • 参数rect2 第二个矩形
  • 参数intersectingRegion 交集区域的顶点输出数组。最多返回8个顶点。存储为 std::vectorcv::Point2f 或者类型为 CV_32FC2 的 cv::Mat 作为 Mx1。

代码示例

在这个示例中:

  • 如果numVertices为0,表示没有交集。
  • 如果numVertices大于0,表示有交集,并且intersectingRegion中存储了交集区域的顶点。
cpp 复制代码
#include <iostream>
#include <opencv2/opencv.hpp>
#include <vector>

int main()
{
    // 创建两个旋转矩形实例
    cv::RotatedRect rect1( cv::Point2f( 100, 100 ), cv::Size2f( 50, 100 ), 30 );  // 中心点, 尺寸, 旋转角度
    cv::RotatedRect rect2( cv::Point2f( 120, 120 ), cv::Size2f( 100, 50 ), -20 );

    // 用于存储交集区域顶点的向量
    std::vector< cv::Point2f > intersectingRegion;

    // 调用函数检测两个旋转矩形是否相交
    int numVertices = cv::rotatedRectangleIntersection( rect1, rect2, intersectingRegion );

    // 检查返回值以确定交集情况
    if ( numVertices == 0 )
    {
        std::cout << "No intersection." << std::endl;
    }
    else if ( numVertices > 0 )
    {
        std::cout << "Intersection with " << numVertices << " vertices:" << std::endl;
        for ( const auto& pt : intersectingRegion )
        {
            std::cout << "Vertex: (" << pt.x << ", " << pt.y << ")" << std::endl;
        }
    }
    else
    {
        std::cout << "Error occurred during intersection calculation." << std::endl;
    }

    return 0;
}

运行结果

bash 复制代码
Intersection with 1 vertices:
Vertex: (136.054, 87.5523)
Vertex: (97.1611, 154.917)
Vertex: (95.9088, 155.373)
Vertex: (75.3445, 143.5)
Vertex: (64.4649, 113.609)
相关推荐
温九味闻醉8 分钟前
关于腾讯广告算法大赛2025项目分析1 - dataset.py
人工智能·算法·机器学习
White-Legend10 分钟前
第三波GPT5.4 日400刀
人工智能·ai编程
. . . . .15 分钟前
Claude Code Hooks的原理、触发执行机制以及如何编写 Hooks
人工智能
w_t_y_y19 分钟前
codex(一)下载安装&使用
人工智能
唐兴通个人42 分钟前
唐兴通应邀为平安财产险北京分公司高层主讲《新媒体营销》专项培训,引领保险业AI时代内容营销变革
人工智能
朗心心理1 小时前
朗心科技:以数智化引领心理健康服务新标杆
大数据·人工智能·科技·心理健康·朗心科技·数智化心理育人·一站式心理中心建设
LaughingZhu1 小时前
Product Hunt 每日热榜 | 2026-03-23
数据库·人工智能·经验分享·神经网络·chatgpt
一个帅气昵称啊1 小时前
基于.NET AgentFramework开发OpenClaw智能体框架
人工智能·自然语言处理·c#·.net·openclaw
Hello.Reader2 小时前
深度学习 — 从人工智能到深度学习的演进之路(一)
人工智能·深度学习