如何选择出所有的轮廓

How to select all out of a contour?

本文关键字:轮廓 何选择 选择      更新时间:2023-10-16

我有一个二值图像的轮廓,我得到最大的对象,我想把这个对象全部选中来绘制它。我有这样的代码:

vector<vector<Point> > contours;
findContours( img.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
vector<Rect> boundSheet( contours.size() );
int largest_area=0;
for( int i = 0; i< contours.size(); i++ )
  {
   double a= contourArea( contours[i],false);
   if(a>largest_area){
   largest_area=a; 
   boundSheet[i] = boundingRect(contours[i]); 
   }
  }

我想用drawContours画出边界外的所有东西,我怎么选择所有的轮廓?

using namespace cv;
int main(void)
{
    // 'contours' is the vector of contours returned from findContours
    // 'image' is the image you are masking
    // Create mask for region within contour
    Mat maskInsideContour = Mat::zeros(image.size(), CV_8UC1);
    int idxOfContour = 0;  // Change to the index of the contour you wish to draw
    drawContours(maskInsideContour, contours, idxOfContour,
                 Scalar(255), CV_FILLED); // This is a OpenCV function
    // At this point, maskInsideContour has value of 255 for pixels 
    // within the contour and value of 0 for those not in contour.
    Mat maskedImage = Mat(image.size(), CV_8UC3);  // Assuming you have 3 channel image
    // Do one of the two following lines:
    maskedImage.setTo(Scalar(180, 180, 180));  // Set all pixels to (180, 180, 180)
    image.copyTo(maskedImage, maskInsideContour);  // Copy pixels within contour to maskedImage.
    // Now regions outside the contour in maskedImage is set to (180, 180, 180) and region
    // within it is set to the value of the pixels in the contour.
    return 0;
}