1 | initial version |
Ok, so you already found the contour and bounding rectangle, and you need to make the contour as mask, for this draw contour with thickness=CV_FILLED to a new Mat and later copy the object from your source image using OpenCV Mat::copyTo(OutputArray m, InputArray mask), here you should use contour as mask .
And next thing is fill your rectangle excluding the object. For this draw the rectangle to a new Mat with thickness-CV_FILLED which will fill your rectangle with scalar you provided. Now perform bitwise_xor operation between previously created contour and newly created rectangle image. Using the resultant mask you can fill the area between your contour and rectangle.