Ask Your Question

Revision history [back]

Problem with getting information on contours

I am writing a function that takes a binary 8-bit image and trying to find the average area of blobs in there. My function is:

void rm_noise(cv::Mat& img, cv::Mat& clean_img)
{
    std::vector<std::vector<cv::Point>> contours;
    std::vector<cv::Vec4i> hierarchy;
    cv::findContours ( img, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
    if ( contours.empty() )
        return;

    clean_img = cv::Mat::zeros(img.size(), CV_8UC1);
    for (size_t i = 0; i < hierarchy.size(); i++)
    {
        cv::drawContours(clean_img, contours, i, cv::Scalar(0XFF), cv::FILLED, cv::LINE_AA, hierarchy);
    }
    cv::imshow("edges", clean_img);
    cv::waitKey();

    double area = 0;
    //for (std::vector<std::vector<cv::Point>>::const_iterator c = contours.begin(); c != contours.end(); c++)
    for (size_t i = 0; i >= 0; i = hierarchy[i][0])
    {
        const std::vector<cv::Point>& c = contours[i];
        double a = std::fabs(cv::contourArea(cv::Mat(c)));
        area += a;
    }
    double avg_area = area /= contours.size();
}

findContours seems to work correctly as I can see the contours drawn properly using a loop with drawContours. However, when I try to get the information on contours such as contourArea or even bounding box, I get strange results. The results seem to give me contour area as very large (something of the order of 10^19 pixels) which is obviously wrong. And the code seg faults. Can someone help me with this as I have already wasted about five days trying different combinations to no avail.