有時候想知道多邊形的面積,我們可以怎麼做?現在給定幾個座標點,只要呼叫內建的函式contourArea,就會回傳結果數值喔!這篇就叫做計算輪廓面積 (Calculate Contour Area)。
讀取一張600×600的影像,四個座標點分別為(70,70)、(70,170)、(170,170)、(170,70),面積為10000,因為四邊長都是100,所以用心算就能得出結果。
簡單地把它寫成程式:
/** Theme: Calculate Contour Area IDE: Xcode 7 Language: C++ Date: 105/03/27 Author: HappyMan Blog: https://cg2010studio.wordpress.com/ */ #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> using namespace cv; using namespace std; int main(int argc, char** argv) { // Read the file image = imread("cake.jpg", CV_LOAD_IMAGE_COLOR); if(!image.data) { // Check for invalid input cout << "Could not open or find the image" << endl; return -1; } line(image, Point(70,70), Point(70,170), Scalar(255,0,0), 2, 8); line(image, Point(70,170), Point(170,170), Scalar(0,255,0), 2, 8); line(image, Point(170,170), Point(170,70), Scalar(0,0,255), 2, 8); line(image, Point(170,70), Point(70,70), Scalar(255,255,0), 2, 8); vector<Point> contour; contour.push_back(Point(70,70)); contour.push_back(Point(70,170)); contour.push_back(Point(170,170)); contour.push_back(Point(170,70)); double area = contourArea(contour,false); // Find the area of contour cout << "Happy Area: " << area << endl; // Create a window to display namedWindow("Happy window", WINDOW_AUTOSIZE); imshow("Happy window", image); waitKey(0); // Wait for a keystroke in the window return 0; }
輸出:
Happy Area: 10000
那如果座標點變更為:(70,70)、(470,170)、(370,370)、(270,370),面積為何呢?這就令人傷透腦筋⋯⋯於是就交給厲害的程式來幫我們計算囉~
輸出:
Happy Area: 60000
倘若這些點無法構成一個凸多邊形的話,結果會如何呢?
參考:OpenCV – contourArea。
隨意留個言吧:)~