26、Opencv 进行区域的面积计算

基本思想:对一个多边形使用opencv进行面积计算(使用起内部实现方式的向量计算法)进行计算

#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;
}
/home/ubuntu/CLionProjects/test/cmake-build-debug/test
曲线围成的轮廓的面积为:18433
逼近曲线围成的轮廓的面积为:18040
逼近曲线围成的轮廓的面积为:18185

猜你喜欢

转载自blog.csdn.net/sxj731533730/article/details/106769716
今日推荐