計算輪廓面積: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 }
效果演示: