OpenCV结构分析与形状描述符(19)查找二维点集的最小面积外接旋转矩形函数minAreaRect()的使用

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

算法描述

找到一个包围输入的二维点集的最小面积旋转矩形。

该函数计算并返回指定点集的最小面积边界矩形(可能是旋转的)。开发者需要注意的是,当数据接近包含的 Mat 元素边界时,返回的 RotatedRect 可能会包含负索引。

minAreaRect 是 OpenCV 库中的一个函数,它用于查找一个给定的二维点集(通常是一个轮廓)的最小面积外接旋转矩形。这个矩形不同于标准的最小包围盒(即由 cv::boundingRect 得到的直立矩形),它可以旋转任意角度以适应轮廓的形状,从而达到最小面积的效果。
使用场景

minAreaRect 常用于物体识别与定位,特别是在需要处理旋转情况下的物体检测时。它可以帮助你找到一个物体的精确位置和方向,这对于机器人视觉、工业检测等领域特别有用。

函数原型

cpp 复制代码
RotatedRect cv::minAreaRect	
(
	InputArray 	points
)	

参数

  • 参数points 输入的二维点向量,存储在 std::vector<> 或 Mat 中。

返回值

  • RotatedRect: 返回的是一个 RotatedRect 对象,它包含了最小外接矩形的信息。RotatedRect 包括三个属性:
    • center (矩形的中心点坐标)
    • size (矩形的宽度和高度)
    • angle (矩形的旋转角度)

代码示例

cpp 复制代码
#include <iostream>
#include <opencv2/opencv.hpp>
#include <vector>

using namespace cv;
int main()
{
    // 创建一个空白图像
    Mat img( 400, 400, CV_8UC3, Scalar( 255, 255, 255 ) );

    std::vector< cv::Point2f > points;
    points.push_back( Point2f( 100, 100 ) );
    points.push_back( Point2f( 125, 125 ) );
    points.push_back( Point2f( 75, 125 ) );
    points.push_back( Point2f( 50, 150 ) );
    points.push_back( Point2f( 150, 150 ) );
    points.push_back( Point2f( 200, 250 ) );
    points.push_back( Point2f( 100, 250 ) );
    points.push_back( Point2f( 150, 300 ) );
    points.push_back( Point2f( 125, 275 ) );
    points.push_back( Point2f( 175, 275 ) );

    // 绘制原始点
    for ( const auto& pt : points )
    {
        circle( img, pt, 5, Scalar( 0, 255, 0 ), -1 );
    }

    // 获取最小面积外接矩形
    cv::RotatedRect rect = cv::minAreaRect( points );

    // 绘制最小面积外接矩形
    cv::Point2f vertices[ 4 ];
    rect.points( vertices );
    for ( int i = 0; i < 4; ++i )
    {

        cv::line( img, vertices[ i ], vertices[ ( i + 1 ) % 4 ], cv::Scalar( 0, 255, 0 ), 2 );
    }

    // 显示图像
    cv::imshow( "Image with Min Area Rect", img );
    cv::waitKey( 0 );

    return 0;
}

运行结果

相关推荐
Shockang1 小时前
AI 智能体安全沙盒实战
人工智能
yuhulkjv3352 小时前
Claude表格复制到word不再崩溃,AI导出鸭批量导出+格式无损一键搞定
人工智能·ai·c#·word·ai导出鸭
大明者省4 小时前
WSL2 Ubuntu22.04 GPU训练环境配置指南
人工智能·算法·计算机视觉
抱抱宝4 小时前
Agent-study项目教程(03):手写 Mini-ReAct Agent(不依赖框架)
javascript·人工智能·gpt·react.js·prompt·agent
抱抱宝4 小时前
大模型应用开发教程08 | 构建完整 RAG 应用(Chroma/FAISS 实战)
人工智能·gpt·prompt·agent
美团技术团队4 小时前
KDD‘26 美团学术论文精选及KDD Cup‘26 DataAgents赛道冠军思路解读
人工智能
AKAMAI4 小时前
当AI模型超出存储增长时
人工智能·云计算
科技绘图5 小时前
快鲸GEO vs 传统AI搜索优化:全链路自动化与高效内容生产在转化闭环上的对比
数据库·人工智能·自动化
DS随心转小程序5 小时前
ChatGPT 文字怎么转为 word?解析各类转换方案,AI 导出鸭成为高效文档转换新选择
人工智能·chatgpt·word·豆包·deepseek·ai导出鸭
乌恩大侠5 小时前
【AI-RAN】硬件产品:DELL 前传交换机
人工智能·spark·aerial·o-ru·ai-ran