2011-11-26 109 views
4

我在這裏做錯了什麼?在OpenCV中繪製多邊形?

vector <vector<Point> > contourElement; 

for (int counter = 0; counter < contours -> size(); counter ++) 
{ 
    contourElement.push_back (contours -> at (counter)); 

    const Point *elementPoints [1] = {contourElement.at (0)}; 
    int numberOfPoints [] = {contourElement.at (0).size()}; 

    fillPoly (contourMask, elementPoints, numberOfPoints, 1, Scalar (0, 0, 0), 8); 

我不斷收到const Point部分的錯誤。編譯器說

error: cannot convert 'std::vector<cv::Point_<int>, std::allocator<cv::Point_<int> > >' to 'const cv::Point*' in initialization 

我在做什麼錯? (PS:顯然忽略在for循環結束時的丟失托架由於此僅爲我的代碼部分)

回答

12

讓我們分析問題的行:

const Point *elementPoints [1] = { contourElement.at(0) }; 

您聲明contourElementvector <vector<Point> >,這意味着contourElement.at(0)返回vector<Point>而不是const cv::Point*。所以這是第一個錯誤。

最後,你需要做的是這樣的:

vector<Point> tmp = contourElement.at(0); 
const Point* elementPoints[1] = { &tmp[0] }; 
int numberOfPoints = (int)tmp.size(); 

後來,稱其爲:

fillPoly (contourMask, elementPoints, &numberOfPoints, 1, Scalar (0, 0, 0), 8); 
+0

謝謝。但是,在表示「const Point * elementPoints [1] = {tmp [0]}」的行;「我得到錯誤說:「錯誤:不能在初始化中將'cv :: Point_ '轉換爲'const cv :: Point *'。任何想法爲什麼? – fdh

+0

是的,我忘了添加一個'&'。更新了答案,請現在測試。 – karlphillip

+0

謝謝。它編譯正確,但我有一個問題。你不只是指出一個奇點嗎?你不需要通過所有的點來繪製整個多邊形嗎? – fdh

2

contourElement是vector<Point>矢量,而不是指向:) 所以不是:

const Point *elementPoints 

const vector<Point> *elementPoints 
+0

謝謝。但是對於函數,參數必須是一個常量點而不是一個常量向量點。 – fdh

9

只是爲了記錄(因爲OpenCV的實況是很稀疏這裏)使用C++ API的片段更少:

std::vector<cv::Point> fillContSingle; 
    [...] 
    //add all points of the contour to the vector 
    fillContSingle.push_back(cv::Point(x_coord,y_coord)); 
    [...] 

    std::vector<std::vector<cv::Point> > fillContAll; 
    //fill the single contour 
    //(one could add multiple other similar contours to the vector) 
    fillContAll.push_back(fillContSingle); 
    cv::fillPoly(image, fillContAll, cv::Scalar(128)); 
+2

Afaik這個C++的fillPoly調用沒有記錄在任何地方,但它是繪製填充多邊形的最簡單和最直觀的方法! – Micka

+0

Double >>嵌套的std :: vectors不適用於GCC。我試圖給答案增加一個空格,但每次編輯至少需要6個字符。 –

+0

@ lahjaton_j; Thxs,我添加了一個空白 –