c ++ opencv找到对象的中心并添加圆圈

时间:2017-08-05 18:18:11

标签: c++ opencv

您好我正在尝试学习opencv。用这个代码ı我试图把圆圈放到对象的中心。当ı尝试写1,2,3等它是okey但当ı尝试将圆圈添加到对象的中心时它是问题。

我的代码:

    void findcontours(){
    cv::namedWindow("contourdemo",CV_GUI_EXPANDED);
    src = cv::imread("/home/zugurtaga/Desktop/project/opencv/imgs/seed.jpg");
        if(src.data){

            if(src.channels() > 1){
                cv::cvtColor(src,src,CV_RGB2GRAY);
            }else {
                src = src;
            }

            cv::Mat cImc = src.clone();
            cv::threshold(cImc,cImc,150,255,CV_THRESH_BINARY_INV | CV_THRESH_OTSU);
            cv::imshow("contourdemo",cImc);
            cv::waitKey(0);


            vector<vector <cv::Point> > contours;
            vector<cv::Point> contPoly;
            vector<cv::Vec4i> hierarchy;
            cv::findContours(cImc,contours,hierarchy,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE);
            cout << "Number of counts: " << contours.size() << endl;

            tmp = cv::Mat::zeros(cImc.size(),CV_8UC3);
            cv::RotatedRect rRect;

            //Problem line ???
            shapeMoments = cv::moments(contours);
            cv::HuMoments(shapeMoments,shapeHumoments);

            centerofmass.x = (shapeMoments.m10 / shapeMoments.m00);
            centerofmass.y = (shapeMoments.m01 / shapeMoments.m00);
            cout << "centerofmass.x: " << centerofmass.x << " centerofmass.y: " << centerofmass.y << endl;
            // till here

            for (size_t i = 0; i < contours.size(); i++) {
                cv::drawContours(tmp,contours,i,cv::Scalar(120,0,0),CV_FILLED,8,hierarchy,0,cv::Point());
                rRect = cv::minAreaRect(contours[i]);
                cv::putText(tmp,cv::format("%d",i+1),rRect.center,1,1,cv::Scalar(255,255,255));
                cv::circle(tmp,centerofmass,(int)3,cv::Scalar(255,255,255),-1,8,0);

            }

            cv::imshow("contourdemo",tmp);
            cv::waitKey(0);
            cv::destroyAllWindows();

        }else{
            cout << "No file.." << endl;
        }
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

ı在尝试了一些工作后发现了问题。

 for (size_t i = 0; i < contours.size(); i++) {
                shapeMoments = cv::moments(contours[i]);
                cv::HuMoments(shapeMoments,shapeHumoments);

                centerofmass.x = (shapeMoments.m10 / shapeMoments.m00);
                centerofmass.y = (shapeMoments.m01 / shapeMoments.m00);

                cout << "centerofmass.x: " << centerofmass.x << " centerofmass.y: " << centerofmass.y << endl;

                cv::drawContours(tmp,contours,i,cv::Scalar(120,0,0),CV_FILLED,8,hierarchy,0,cv::Point());
                rRect = cv::minAreaRect(contours[i]);
                cv::putText(tmp,cv::format("%d",i+1),centerofmass,1,1,cv::Scalar(255,255,255));
                cv::circle(tmp,centerofmass,(int)3,cv::Scalar(255,255,255),-1,8,0);

            }

enter image description here