2

我将非常感谢在帖子中进一步了解:寻找轮廓之间的最小距离

我正在使用 FindContours 并根据需要获取多个轮廓。问题是我想找到每个相邻对之间的最小距离,例如黄色轮廓和深绿色之间、深绿色和青色之间、青色和紫色之间。

我从上面的帖子中理解了一般方法。但是谁能告诉我如何一个接一个地选择它们(自动)?

在此处输入图像描述

void thresh_function(int, void*)
{

        Mat canny_output;
        vector<vector<Point> > contours;
        vector<Vec4i> hierarchy;


      /// Detect edges using canny
        Canny( roiImg, canny_output, threshold_value, threshold_value*2, 3 );
      /// Find contours
        findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );

      /// Draw contours
        Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 );
        for( int i = 0; i< contours.size(); i++ )
         {
           Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
           drawContours( drawing, contours, i, color, 2, 8, hierarchy, 0, Point() );//Scalar(255,255,255)
         }

        erode(drawing,drawing,erodeElement2);
        erode(drawing,drawing,erodeElement1);
        dilate(drawing,drawing,dilateElement);

      /// Show in a window
     //namedWindow( "Contours", CV_WINDOW_AUTOSIZE );
     resize(drawing, enlargeD0, Size(), 2, 2, CV_INTER_CUBIC);
     done = 1;
     imshow("Contours", enlargeD0);
}
4

1 回答 1

2
vector<vector<Point> > all_contours;
... 
findContours(... all_contours ... CV_CHAIN_APPROX_NONE ...);
...

// Remove small contours
int minSize = 20;
vector<vector<Point> > contours;
contours.reserve(all_contours.size());
for(int i=0; i<all_contours.size(); ++i)
{
    if(all_contours[i].size() > minSize) 
    {
         contours.push_back(all_contours[i]);
    }
}  

Mat1f dist(contours.size(), contours.size(), 0.f);
for(int i=0; i<contours.size()-1; ++i)
{
    const vector<Point>& firstContour = contours[i];
    for(int j=i+1; j<contours.size(); ++j)
    {
        const vector<Point>& secondContour = contours[j];
        float d = compute_pairwise_distance(firstContour, secondContour); // You should implement this
        dist(i,j) = d;
        dist(j,i) = d;  // distance from first to second is equal
                        // to distance from second to first 
    }
}

// Now dist contains the pairwise distances between i-th and j-th contours
于 2015-07-17T12:14:34.890 回答