OpenCV结构分析与形状描述符(17)判断轮廓是否为凸多边形的函数isContourConvex()的使用

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

算法描述

测试轮廓的凸性。

该函数测试输入的轮廓是否为凸的。轮廓必须是简单的,即没有自相交。否则,函数的输出是不确定的。

cv::isContourConvex 函数是 OpenCV 提供的一个用于判断轮廓是否为凸多边形的函数。这个函数可以用来验证一个给定的轮廓是否是凸的,这对于后续处理(如使用 intersectConvexConvex 来寻找两个凸多边形的交集)是非常有用的。

函数原型

cpp 复制代码
bool cv::isContourConvex	
(
	InputArray 	contour
)	

参数

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

代码示例

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

int main()
{
    // 定义两个矩形的顶点
    cv::Mat p1 = ( cv::Mat_< float >( 4, 2 ) << 0, 0,  // 左上角
                   2, 0,                               // 右上角
                   2, 2,                               // 右下角
                   0, 2 );                             // 左下角

    cv::Mat p2 = ( cv::Mat_< float >( 4, 2 ) << 1, 1,  // 左上角
                   3, 1,                               // 右上角
                   3, 3,                               // 右下角
                   1, 3 );                             // 左下角

    // 验证轮廓是否为凸多边形
    bool isP1Convex = cv::isContourConvex( p1 );
    bool isP2Convex = cv::isContourConvex( p2 );

    std::cout << "Polygon p1 is convex: " << std::boolalpha << isP1Convex << std::endl;
    std::cout << "Polygon p2 is convex: " << std::boolalpha << isP2Convex << std::endl;

    // 如果两个多边形都是凸的,才继续进行交集计算
    if ( isP1Convex && isP2Convex )
    {
        cv::Mat p12;
        bool intersect = cv::intersectConvexConvex( p1, p2, p12, true );

        if ( intersect )
        {
            std::cout << "Polygons intersect." << std::endl;
            std::cout << "Intersection vertices:" << std::endl;
            for ( int i = 0; i < p12.rows; ++i )
            {
                cv::Point2f pt = p12.at< cv::Point2f >( i );
                std::cout << "Vertex " << i << ": (" << pt.x << ", " << pt.y << ")" << std::endl;
            }
        }
        else
        {
            std::cout << "Polygons do not intersect." << std::endl;
        }
    }
    else
    {
        std::cout << "One or both polygons are not convex." << std::endl;
    }

    return 0;
}

运行结果

bash 复制代码
Polygon p1 is convex: true
Polygon p2 is convex: true
Polygons intersect.
Intersection vertices:
Vertex 0: (2, 1)
Vertex 1: (2, 2)
Vertex 2: (1, 2)
Vertex 3: (1, 1)
相关推荐
静心问道1 分钟前
TrOCR: 基于Transformer的光学字符识别方法,使用预训练模型
人工智能·深度学习·transformer·多模态
说私域3 分钟前
基于开源AI大模型、AI智能名片与S2B2C商城小程序源码的用户价值引导与核心用户沉淀策略研究
人工智能·开源
亲持红叶4 分钟前
GLU 变种:ReGLU 、 GEGLU 、 SwiGLU
人工智能·深度学习·神经网络·激活函数
说私域5 分钟前
线上协同办公时代:以开源AI大模型等工具培养网感,拥抱职业变革
人工智能·开源
群联云防护小杜6 分钟前
深度隐匿源IP:高防+群联AI云防护防绕过实战
运维·服务器·前端·网络·人工智能·网络协议·tcp/ip
摘星编程11 分钟前
构建智能客服Agent:从需求分析到生产部署
人工智能·需求分析·智能客服·agent开发·生产部署
不爱学习的YY酱15 分钟前
信息检索革命:Perplexica+cpolar打造你的专属智能搜索中枢
人工智能
whaosoft-1431 小时前
51c自动驾驶~合集7
人工智能
刘晓倩4 小时前
Coze智能体开发实战-多Agent综合实战
人工智能·coze
石迹耿千秋5 小时前
迁移学习--基于torchvision中VGG16模型的实战
人工智能·pytorch·机器学习·迁移学习