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); }

效果演示:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM