opencv —— contourArea、arcLength 计算轮廓面积与长度

计算轮廓面积:contourArea 函数

double contourArea(InputArray contour, bool oriented = false);

  • contour,输入的二维点集(轮廓顶点),可以是 vector 或 Mat 类型。
  • oriented,面向区域标识符。有默认值 false。若为 true,该函数返回一个带符号的面积值,正负取决于轮廓的方向(顺时针还是逆时针)。若为 false,表示以绝对值返回。

计算轮廓长度:arcLength 函数

arcLength 函数用于计算封闭轮廓的周长或曲线的长度。

double arcLength(InputArray curve, bool closed);

  • curve,输入的二维点集(轮廓顶点),可以是 vector 或 Mat 类型。
  • closed,用于指示曲线是否封闭。

代码示例:

#include<opencv.hpp>
#include<iostream>
#include<vector>
using namespace cv;
using namespace std;
int main() {
    Mat src = imread("C:/Users/齐明洋/Desktop/示例图片/7.jpg");
    imshow("src", src);

    //转换为二值图像
    Mat bin_img;
    cvtColor(src, bin_img, COLOR_BGR2GRAY);
    threshold(bin_img, bin_img, 55, 255, THRESH_BINARY_INV);
    imshow("bin_img", bin_img);

    //寻找轮廓
    vector<vector<Point> >contours;
    findContours(bin_img, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);

    //计算并输出面积周长
    Mat dst = Mat::zeros(src.size(), src.type());
    RNG rngs = { 12345 };
    for (int i = 0; i < contours.size(); i++) {
        Scalar colors = Scalar(rngs.uniform(0, 255), rngs.uniform(0, 255), rngs.uniform(0, 255));
        drawContours(dst, contours, i, colors, 1);
        cout << i<<" 的面积:"<<contourArea(contours[i]) << endl;
        cout << "  周长:" << arcLength(contours[i], true) << endl;
    }
    imshow("dst", dst);

    waitKey(0);
}

效果演示:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值