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