Just a Computer Graphics Studio & My Life

承上篇文章:描繪連續的點。我們想要找多邊形的重心 (Polygon Center of Gravity),可以怎麼做?OpenCV 多邊形的重心 Polygon Center of Gravity.jpg

我們可以不厭煩地去研究數學理論,但其實OpenCV有捷徑給我們走,那麼就直接套用吧~至於理論就給好學的數學家去研究吧!

/**
 Theme: Polygon Center of Gravity
 IDE: Xcode 7
 Language: C++
 Date: 105/04/22
 Author: HappyMan
 Blog: https://cg2010studio.wordpress.com/
 */
#include <iostream>

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace cv;
using namespace std;

Mat src;

const char* window_name = "Happy Window";

void drawContour(vector<Point> contour)
{
    const Point *pts = (const Point *) Mat(contour).data;
    int npts = Mat(contour).rows;

    cout << "Number of polygon vertices: " << npts << endl;

    // draw the polygon
    polylines(src, &pts, &npts, 1,
              true,            // draw closed contour (i.e. joint end to start)
              Scalar(63,255,0), // colour RGB ordering (here = green)
              3,        // line thickness
              CV_AA, 0);
}

void drawContourCenter(vector<Point> contour)
{
    // center of gravity
    Moments mo = moments(contour);
    Point center = Point(mo.m10/mo.m00 , mo.m01/mo.m00);

    circle(src, center, 10, Scalar(255,0,0), 5, CV_AA, 0);
}
/**
 * @function main
 */

int main(int, char** argv)
{
    /// Load an image
    string fileName = "Fang.jpg";
    src = imread(fileName, CV_LOAD_IMAGE_COLOR);

    if(!src.data)
    { return -1; }

    vector<Point> contour;
    contour.push_back(Point(10,100));
    contour.push_back(Point(120,120));
    contour.push_back(Point(150,260));
    contour.push_back(Point(80,380));
    contour.push_back(Point(450,100));

    drawContour(contour);
    drawContourCenter(contour);

    /// Create a window
    imshow("Happy Source", src);

    /// Wait until user exit program by pressing a key
    waitKey(0);

    return 0;
}

以上程式碼多了個函式:

void drawContourCenter(vector contour);

將多邊形丟入其中,便能描繪多邊形的重心喔!結果如首圖的藍色圓圈~

參考:OpenCV – Contour Features、Gist – find large contour & calculate center of gravity sample code using OpenCV2

Advertisements

發表留言

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s

標籤雲

%d 位部落客按了讚: