#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main() {
Mat img = Mat(600, 600, CV_8UC1, cv::Scalar(125));
Point root_points[1][6];
root_points[0][0] = Point(210, 220);
root_points[0][1] = Point(230, 225);
root_points[0][2] = Point(266, 250);
root_points[0][3] = Point(295, 265);
root_points[0][4] = Point(260, 390);
root_points[0][5] = Point(96, 310);
const Point *ppt[1] = {root_points[0]};
int npt[] = {6};
polylines(img, ppt, npt, 1, 1, Scalar(0, 255, 255), 6, 8, 0);
imshow("Test0", img);
方法1 使用像素点 计算机面积
Mat mask_ann = Mat(img.rows, img.cols, CV_8UC1);
fillPoly(mask_ann, ppt, npt, 1, Scalar(255, 255, 255));
//imwrite("Test1.jpg", mask_ann);
double sum = 0;
for (int i = 0; i < mask_ann.cols; i++)
for (int j = 0; j < mask_ann.rows; j++) {
if (mask_ann.at<uchar>(i, j) == 255) {
sum = sum + 1;
}
}
imshow("Test1", mask_ann);
cout << "曲线围成的轮廓的面积为:" << sum << endl;
vector<Point2f> vec;
/方法二 使用contourArea 计算面积
for (int i = 0; i < npt[0]; i++) {
vec.push_back(root_points[0][i]);
}
vector<Point2f> approx;
approxPolyDP(vec, approx, 5, true);
//接着计算得到的逼近曲线的面积]
double g_dapproxArea = contourArea(approx, true);
cout << "逼近曲线围成的轮廓的面积为:" << g_dapproxArea << endl;
使用向量的方法计算面积
double area = 0;
for (int i = 0; i < npt[0] - 1; i++) {
area = area + (root_points[0][i].x * root_points[0][i + 1].y - root_points[0][i].y * root_points[0][i + 1].x);
}
area = area +
(root_points[0][npt[0] - 1].x * root_points[0][0].y - root_points[0][npt[0] - 1].y * root_points[0][0].x);
cout << "逼近曲线围成的轮廓的面积为:" << abs(area * 0.5) << endl;
waitKey(0);
return 0;
}
opencv计算闭合区域的面积
最新推荐文章于 2025-01-13 17:28:48 发布