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,用于指示曲线是否封闭。

代码示例:

 1 #include<opencv.hpp>
 2 #include<iostream>
 3 #include<vector>
 4 using namespace cv;  5 using namespace std;  6 int main() {  7     Mat src = imread("C:/Users/齐明洋/Desktop/示例图片/7.jpg");  8     imshow("src", src);  9 
10     //转换为二值图像
11  Mat bin_img; 12  cvtColor(src, bin_img, COLOR_BGR2GRAY); 13     threshold(bin_img, bin_img, 55, 255, THRESH_BINARY_INV); 14     imshow("bin_img", bin_img); 15 
16     //寻找轮廓
17     vector<vector<Point> >contours; 18  findContours(bin_img, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE); 19 
20     //计算并输出面积周长
21     Mat dst = Mat::zeros(src.size(), src.type()); 22     RNG rngs = { 12345 }; 23     for (int i = 0; i < contours.size(); i++) { 24         Scalar colors = Scalar(rngs.uniform(0, 255), rngs.uniform(0, 255), rngs.uniform(0, 255)); 25         drawContours(dst, contours, i, colors, 1); 26         cout << i<<" 的面积:"<<contourArea(contours[i]) << endl; 27         cout << " 周长:" << arcLength(contours[i], true) << endl; 28  } 29     imshow("dst", dst); 30 
31     waitKey(0); 32 }

效果演示:

 


免责声明!

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



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