opencv | 计算掩膜、外接矩、质心

#include 
#include 
#include 
#include 

#include "seg_test.h"
#include "json/json.h"
#include "json/json-forwards.h"


int main()
{
    std::string imgPath = "D:/0_code/deepvision_Pro/caiju/seg_test/data/imgs/Color_20220407_123819.bmp";

    cv::Mat sourceImg;

    sourceImg = cv::imread(imgPath);


    std::string jsonPath = "D:/0_code/deepvision_Pro/caiju/seg_test/data/annotations/Color_20220407_123819.json";
    Json::Reader m_Reader;
    Json::Value root;
    Json::Value labels;

    std::ifstream fp;
    fp.open(jsonPath, std::ios::binary);
    m_Reader.parse(fp, root);
    std::string engname = root["version"].asString();

    // 获取类别个数
    int labelSize = root["shapes"].size();

    for (int i = 0; i < labelSize; i++)
    {
        labels = root["shapes"][i];
        std::string labelName = labels["label"].asString();
        std::cout << labelName << std::endl;

        Json::Value points = labels["points"];
        std::cout << points.size() << std::endl;
        std::cout << points[0][0] << std::endl;


        cv::Mat maskImg;

        int pointSize = points.size();
        cv::Point pointsP[20];    // 静态创建20个点集容量
        for (int j = 0; j < pointSize; j++)
        {
            pointsP[j].x = points[j][0].asInt();
            pointsP[j].y = points[j][1].asInt();
        }
        const cv::Point* ppt[1] = { pointsP };
        int npt[] = { pointSize };
        sourceImg.copyTo(maskImg);
        maskImg.setTo(cv::Scalar::all(0));
        cv::cvtColor(maskImg, maskImg, cv::COLOR_BGR2GRAY);

        cv::fillPoly(maskImg, ppt, npt, 1, cv::Scalar(255));

        // 查找轮廓
        std::vector> contours;
        std::vector hierarchy;
        cv::findContours(maskImg, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));

        // 计算轮廓矩
        std::vector mu(contours.size());
        for (int k = 0; k < contours.size(); k++)
        {
            mu[k] = cv::moments(contours[k], false);
        }

        // 计算质心
        std::vector mc(contours.size());
        for (int k = 0; k < contours.size(); k++)
        {
            mc[k] = cv::Point2d(mu[k].m10 / mu[k].m00, mu[k].m01 / mu[k].m00);
        }

        // 计算最小外接矩
        cv::RotatedRect minRect = cv::minAreaRect(contours[0]);

        // debug 画出最小外接矩和质心
        // 画最小外接矩
        cv::Point2f pRect[4];
        minRect.points(pRect);
        for (int k = 0; k < 4; k++)
        {
            cv::line(sourceImg, pRect[k], pRect[(k + 1) % 4], cv::Scalar(255), 1);
        }
        // 画质心
        cv::circle(sourceImg, mc[0], 1, cv::Scalar(0, 0, 255), 1, 8, 0);
    }
    return 0;
}

你可能感兴趣的:(分享,opencv,人工智能,计算机视觉)