如何从轮廓中选择所有?

时间:2014-07-01 00:51:33

标签: c++ opencv

我有一个二进制图像的轮廓,我得到了最大的对象,我想要选择所有这个对象来绘制它。我有这段代码:

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绘制边界之外的所有内容,如何选择全部轮廓?

1 个答案:

答案 0 :(得分:1)

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;
}