2012-11-30 106 views
4

我使用2.4.3版本的OpenCV,並試圖用「findContours」功能Canny邊緣檢測這樣的後:OpenCV的:findContours功能錯誤

struct Component 
{ 
    cv::Rect boundingBox; 
    double area; 
    double circularity; 
} 

cv::vector <Component> components; 
cv::vector <cv::Vec4i> hierarchy; 
cv::findContours (cannyEdges, components, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE); 

然後,它拋出了一行行的錯誤「CV :: findContours」像這樣:

OpenCV Error: Assertion failed (mtype == type0 || (CV_MAT_CN(mtype) == CV_MAT_CN(type0) && ((1((type0) & fixedDepthMask) != 0)) in unknown function, file ...\opencv\modeuls\core\src\matrix.cpp, line 1421 

我怎樣才能解決這個問題?

+1

我們不能用你給我們重現錯誤。請提供[簡短,獨立,正確(可編譯),示例](http://sscce.org/)。 – karlphillip

+0

@karlphillip:該鏈接爲+1 –

回答

11

cv :: findcontours將每個輪廓返回爲點的向量(請參見http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html#findcontours)。

你有這些載體自己像我創造了這個小例子,轉換成你的數據結構(組件):

#include <opencv2/opencv.hpp> 
#include <iostream> 
struct Component 
{ 
    cv::Rect boundingBox; 
    double area; 
    double circularity; 
}; 
int main() 
{ 
    // Create a small image with a circle in it. 
    cv::Mat image(256, 256, CV_8UC3, cv::Scalar(0, 0, 0)); 
    cv::circle(image, cv::Point(80, 110), 42, cv::Scalar(255,127, 63), -1); 

    // Find canny edges. 
    cv::Mat cannyEdges; 
    cv::Canny(image, cannyEdges, 80, 60); 

    // Show the images. 
    cv::imshow("img", image); 
    cv::imshow("cannyEdges", cannyEdges); 

    // Find the contours in the canny image. 
    cv::vector<cv::Vec4i> hierarchy; 

    // "Each contour is stored as a vector of points." 
    // http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html#findcontours 
    typedef cv::vector<cv::vector<cv::Point> > TContours; 
    TContours contours; 
    cv::findContours(cannyEdges, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE); 
    // cannyEdges is destroyed after calling cv::findContours 

    // Print number of found contours. 
    std::cout << "Found " << contours.size() << " contours." << std::endl; 

    // Convert contours to Components. 
    typedef cv::vector<Component> TComponents; 
    TComponents components; 
    for (TContours::const_iterator it(contours.begin()); it != contours.end(); ++it) 
    { 
     Component c; 
     c.area = cv::contourArea(*it); 
     c.boundingBox = cv::boundingRect(*it); 
     c.circularity = 0.0; // Insert whatever you mean by circularity; 
     components.push_back(c); 
    } 

    for (TComponents::const_iterator it(components.begin()); it != components.end(); ++it) 
     std::cout << it->area << std::endl; // and whatever you want. 

    // Wait for user input. 
    cv::waitKey(); 
} 
+0

親愛的Dobi:非常感謝您的回答。我試過你的代碼,它給出了「typedef cv :: vector(...)」這一行的錯誤,並說「錯誤:類模板的參數列表」std :: vector「丟失」。由於互聯網訪問問題,我很晚纔回復。 –

+0

我想你正在使用一個較舊的編譯器,它不支持模板類型中的>>。我在上面的代碼中糾正了這一點,例如,我製作了「typedef cv :: vector > TContours;」到「typedef cv :: vector > TContours;」。請再試一次。 –

+0

非常感謝你!現在它工作正常。 –