2013-07-22 178 views
3

我是C++和opencv的新手。我寫了一個簡單的程序,你可以在下面找到,但是當我運行它,我總是得到通過findContours(img, ctr, CV_RETR_LIST, CV_CHAIN_APPROX_NONE)拋出按類型斷言引起的異常失敗findcontours斷言失敗

OpenCV Error: Assertion failed (mtype == type0 || (CV_MAT_CN(mtype) == CV_MAT_CN (type0) && ((1 << type0) & fixedDepthMask) != 0)) in create, file C:\opencv\modu les\core\src\matrix.cpp, line 1466.

我需要一個代表一個輪廓和整合輪廓analisys類方法。我知道CONTOUR是與vector<Point>不同的類型,但是因爲它擴展了後者,所以不應該是CONTOUR也是vector<Point>類型(並且以相同的方式vector<CONTOUR>也是vector< vector<Point> >)?我錯了嗎?

請注意,如果你聲明CONTOURvector<vector<Point>>派生的類和地方vector<CONTOUR>一切的聲明在下面的代碼作爲CONTOUR對象Ctr迎刃而解。

非常感謝提前。

這裏是我的代碼

#include "opencv2/opencv.hpp" 

#include <vector> 

using namespace cv; 
using namespace std; 

class CONTOUR : public vector<Point> 
{ 
public: 
    CONTOUR() : vector<Point>(){ }; 
    CONTOUR(const CONTOUR& orig) : vector<Point> (orig){ }; 
    virtual ~CONTOUR(){ }; 

    CONTOUR& operator=(const CONTOUR& rhs) 
    { 
     vector<Point> :: operator = (rhs); 
     return *this; 
    } 

    CONTOUR& operator=(const vector<Point>& rhs) 
    { 
     vector<Point> :: operator = (rhs); 
     return *this; 
    } 
}; 

/** @function main */ 
int main(int argc, char** argv) 
{ 
    VideoCapture Camera; 

    if(Camera.open(0)) 
    { 
     Mat img; 

     namedWindow("VIDEO", CV_WINDOW_AUTOSIZE); 

     for(;;) 
     { 

      Camera >> img; 

      if(!img.empty()) 
      { 
       CONTOUR ctr; 
       RNG n(12345); 

       GaussianBlur(img, img, Size(5,5), 1.0, 1.0); 
       cvtColor(img, img, CV_BGR2GRAY); 
       Canny(img, img, 20, 80, 3); 

       findContours(img, ctr, CV_RETR_LIST, CV_CHAIN_APPROX_NONE); 

       Mat shape = Mat::zeros(img.size(), CV_8UC3); 

       for(unsigned int i = 0; i< ctr.size(); i++) 
       { 
        Scalar color(n.uniform(0,255), n.uniform(0,255), n.uniform(0,255)); 
        drawContours(shape, ctr, i, color, 1, 8); 
       } 

       imshow("VIDEO", shape); 

       if(waitKey(30) >= 0) 
       { 
        break; 
       } 
      } 
     } 
    } 
    else 
    { 
     cout << "Camera not opened" << endl; 
    } 

    return 0; 
} 

回答

6

首先,請允許我這樣說:嘗試使用標準庫的容器多態是BadIdea。不要這樣做。在你的情況下甚至沒有必要。

解決您的問題很簡單:免除class CONTOUR並通過vector<vector<cv::Point>>。這是因爲cv::findContours()要求您通過一個或相當的cv::Mat。這是因爲它使用代理類型作爲只能由這些類型構造的參數,因此斷言失敗。如果要定義輪廓的簡寫形式,請使用typedef std::vector<cv::Point> Contour而不是#define CONTOUR。這給你類型安全的好處。

另外,vector<CONTOUR>不是是與vector<vector<Point>>相同的類型。儘管CONTOUR繼承自vector<cv::Point>,但它們是不同的類型。因此,它們的矢量也是不同的類型。 This answer也可能有助於理解這個問題。

此外,我注意到在您的代碼中,CONTOUR是從vector<cv::Point>派生而來的。這個斷言是說你需要一個向量向量:vector<vector<cv::Point>>

+0

+1。我會給這個答案+5 – baci

+0

謝謝你的答案。編輯我的問題希望它更清楚一點。 – Arloong

+1

@Arloong在這個網站上,如果你[發佈你的解決方案作爲答案](http://stackoverflow.com/help/self-answer)和[接受](http://stackoverflow.com/help/someone -answers)是最有幫助的。除此之外,我**強烈建議您不要使用您發佈的解決方案。當然,它可行,但會帶來不必要的複雜性。 – Aurelius

1

findContour函數中的聲明失敗錯誤只是由於編譯器和opencv二進制文件不匹配造成的。 從項目屬性中選擇適當的編譯器。