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

图像:

相关推荐
老王以为15 小时前
走进 AI Agent
前端·人工智能·架构
dong_junshuai15 小时前
每天一个开源项目#59 AirLLM:27.6K星,3.72GB显存跑2.8T模型
人工智能·程序员·github
文心快码BaiduComate15 小时前
Comate 已支持DeepSeek-V4-Flash 正式版
人工智能·程序员
MartinYeung515 小时前
[论文学习]OSReward:为跨平台计算机使用奖励模型建立标准化评估
人工智能·学习
数字供应链安全产品选型16 小时前
悬镜安全打造“中国版 Anthropic Mythos”:以AI治理AI,重构新一代数字供应链安全
人工智能·安全·重构
Tangyuewei16 小时前
2026 下半年:从更快到更可控
人工智能
qq_3164110316 小时前
AI 情感陪伴智能潮玩软硬件一体化开发案例
人工智能·python
Hyyy16 小时前
AI基础——机器学习
人工智能·ai编程
一名普通的电源工程师16 小时前
E0512XT-1WR3 适配优选 钡特电源 DF1-05D12XT|1W 隔离5V转±12V模块电源选型参数技术解析
大数据·网络·人工智能
zx11545016 小时前
大模型工具调用次数限制
人工智能·python