OPenCV结构分析与形状描述符(2)计算轮廓周长的函数arcLength()的使用

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

算法描述

计算轮廓的周长或曲线的长度。

该函数计算曲线的长度或闭合轮廓的周长。

如果曲线是闭合的(即首尾相连),则计算的是轮廓的周长。

如果曲线是开放的(即首尾不相连),则计算的是曲线的长度。

函数原型

cpp 复制代码
double cv::arcLength	
(
	InputArray 	curve,
	bool 	closed 
)		

参数

  • 参数curve 输入的二维点向量,存储在 std::vector 或 Mat 中。
  • 参数closed 标志,指示曲线是否是闭合的。

代码示例

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

int main()
{
    // 加载一张图片
    cv::Mat img = cv::imread( "/media/dingxin/data/study/OpenCV/sources/images/hawk.jpg", cv::IMREAD_COLOR );

    if ( img.empty() )
    {
        std::cerr << "Error: Image cannot be loaded!" << std::endl;
        return -1;
    }

    // 转换为灰度图
    cv::Mat grayImg;
    cv::cvtColor( img, grayImg, cv::COLOR_BGR2GRAY );

    // 二值化处理
    cv::Mat binaryImg;
    cv::threshold( grayImg, binaryImg, 0, 255, cv::THRESH_BINARY_INV + cv::THRESH_OTSU );

    // 查找轮廓
    std::vector< std::vector< cv::Point > > contours;
    cv::findContours( binaryImg, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE );

    // 计算每个轮廓的周长,并进行近似
    std::vector< std::vector< cv::Point > > approxContours( contours.size() );
    for ( size_t i = 0; i < contours.size(); ++i )
    {
        // 计算闭合轮廓的周长
        double perimeter = cv::arcLength( contours[ i ], true );
        std::cout << "Perimeter of the closed contour: " << perimeter << std::endl;

        // 近似轮廓
        cv::approxPolyDP( contours[ i ], approxContours[ i ], 0.02 * perimeter, true );

        // 绘制原始轮廓
        cv::drawContours( img, contours, static_cast< int >( i ), cv::Scalar( 0, 255, 0 ), 2 );

        // 绘制近似后的轮廓
        cv::drawContours( img, approxContours, static_cast< int >( i ), cv::Scalar( 255, 0, 0 ), 2 );
    }

    // 显示结果图像
    cv::imshow( "Contours and Approximations", img );

    // 等待按键,关闭窗口
    cv::waitKey( 0 );

    return 0;
}

运行结果

终端输出:

bash 复制代码
Perimeter of the closed contour: 20.4853
Perimeter of the closed contour: 1176.15

图像:

相关推荐
啵啵啵鱼5 小时前
Chrome 内存泄漏诊断指南
人工智能
Mirawork5 小时前
AI 低代码建站原理:从自然语言需求到在线应用,拆解 AI 生成网页的完整技术链路
人工智能·低代码·ai·ai编程
xsd202411186 小时前
rea-video开源 AI 视频逆向工具
人工智能
thinking_talk6 小时前
AI 自动诊断慢 SQL 怎么落地:五层能力怎么分,以及生产可用要过哪几道门槛
数据库·人工智能·sql·慢sql
码上观世界7 小时前
IndexTTS接入实时交互数字人系统实践
人工智能·实时互动
具身AGI7 小时前
进博会机器人,隔桌对打乒乓球
人工智能·机器人
逐米时代7 小时前
「制造新解法」行业对标方法:借鉴而不照搬的最佳实践
人工智能·算法·制造
小追兵7 小时前
Claude Managed Agents 自托管是什么?企业如何控制 Agent Runtime、Session 与数据?
人工智能
Wellijohn8 小时前
上下文工程实战:把大模型 Agent 从「能跑」做到「上线不掉链子」
人工智能·llm·agent
JavaGuide8 小时前
Gemini 杀疯了,反重力给我用爽了!分享 8 个 Antigravity 使用技巧
人工智能·后端