其他分享
首页 > 其他分享> > OpenCV contourArea、arcLength 计算轮廓面积与长度

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

作者:互联网

计算轮廓面积:contourArea 函数

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

计算轮廓长度:arcLength 函数

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

double arcLength(InputArray curve, bool 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 }

效果演示:

 

标签:bin,src,contourArea,Mat,img,arcLength,OpenCV,轮廓
来源: https://www.cnblogs.com/ybqjymy/p/15931341.html