0

I have a contours of a binary image, I get the largest object, and I want select all out this object to paint it. I have this code:

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

I want to paint everything outside the boundary with drawContours, how can I select all out contour?

Divi
  • 7,621
  • 13
  • 47
  • 63
  • 2
    Take a look at my answer to this [post](http://stackoverflow.com/questions/10176184/with-opencv-try-to-extract-a-region-of-a-picture-described-by-arrayofarrays/10186535#10186535). It shows you how to use drawContours() to draw a given contour onto a mask to mask out the contour. If instead you wish to ignore the contour and keep everything outside it, just set the original value of the mask to a positive value and use drawContours() to fill the region of the contour in the mask with 0. That is, invert the value in the example for given in the link. – lightalchemist Jul 01 '14 at 03:44
  • Thanks!!!!, it work me :D, only have a problem with the color, i wanted paint gray, what is would have to change? – user3779874 Jul 01 '14 at 21:30

1 Answers1

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;
}
lightalchemist
  • 10,031
  • 4
  • 47
  • 55