OpenCV查找轮廓问题

9
我有以下代码,它执行背景减法,然后使用findContours在前景对象周围绘制边界。
// frame - Input frame from a camera.
// output - Output frame to be displayed.
    void process(cv:: Mat &frame, cv:: Mat &output) {

    cv::cvtColor(frame, gray, CV_BGR2GRAY); 

    // initialize background to 1st frame
    if (background.empty())
        gray.convertTo(background, CV_32F);

    // convert background to 8U
    background.convertTo(backImage,CV_8U);

    // compute difference between current image and background
    cv::absdiff(backImage,gray,foreground);

    // apply threshold to foreground image
    cv::threshold(foreground,output,threshold,255,cv::THRESH_BINARY_INV);

    // accumulate background
    cv::accumulateWeighted(gray, background, learningRate, output);

    // Find regions of interest
    std::vector<std::vector<cv::Point> > v; // Detected foreground points

    cv::findContours(output,v,CV_RETR_LIST,CV_CHAIN_APPROX_NONE);

    // Sort to find the entry with the most points at the beginning.
            // This is done to overcome noisy input.
    std::sort(v.begin(), v.end(), DescendingCompare);

    cv::Mat drawing = frame;

    std::vector<std::vector<cv::Point>> contours_poly(1);

    // Determine an approximate polygon for v[0] which is the largest contour
    cv::approxPolyDP( cv::Mat(v[0]), contours_poly[0], 3, false );

    // Draw polygonal contour
     cv::Scalar color = cv::Scalar( 0,0,255 );
     cv::drawContours( drawing, contours_poly, 0, color, 2, 8, std::vector<cv::Vec4i>(), 0, cv::Point() );

     // Show in a window
    output = drawing;
    v.clear();

}

图像只是一个空白的白色背景,但findContours()返回包含图像4个边缘的轮廓。这最终成为找到的最大轮廓,与我的代码逻辑相冲突。有没有办法解决这个问题?我希望当屏幕为空白时返回一个空向量。
此外,这段代码有没有什么提高效率的方法?

1
哎呀!愚蠢的错误..请将您的答案作为单独的评论,以便我可以标记它为正确。 - Madman
1个回答

5

你的背景应该是黑色(0),任何你想勾勒轮廓的物体都应该是白色(或者>=1)。你反过来了,这就是为什么FindContours检测到的是背景而不是物体的轮廓。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接