I am working on software using OpenCV in C++ environment. The objective is to detect a boxing glove and draw a bounding box around gloves contours.
Take a look at my other answer in this subject. Compile that code and remember to activate the code that is commented out.
Result:
as b_m mentioned, you need to apply the morphological operations. Then I'd do something like finding the largest contour in the image and draw the bounding box around that contour only. I had created the following function for a project of mine which I think will help you if used in a correct manner
CvSeq* findLargestContour(CvSeq* contours){
CvSeq* current_contour = contours;
double largestArea = 0;
CvSeq* largest_contour = NULL;
// check we at least have some contours
if (contours == NULL){return NULL;}
while (current_contour != NULL){
double area = fabs(cvContourArea(current_contour));
if(area > largestArea){
largestArea = area;
largest_contour = current_contour;
}
current_contour = current_contour->h_next;
}
// return pointer to largest
return largest_contour;
}
You currently draw a bounding box around each contour, and findContour will find a contour around each connected white or black component, of which there are many in your picture.
So the first thing I would do is filter all that noise with some morphological operations on the thresholded image: do some opening and closing, both of which are combinations of dilation and erosion.
In your case something like cvDilate (2 times); cvErode(4 times); cvDilate(2 times)
This should merge all white blobs into one smooth blob, but the black hole in the middle will remain. You could find the right one by size, but it is easier to call findContours with the CV_RETR_EXTERNAL instead of CV_RETR_TREE, then it will only return the outermost contours.
Before finding the contours you should apply morphological filter like erode and dilate. After that, you can find the contours and leave out the small ones by calculating its size, or the with and height of the bounding box. Finally you can eliminate those that are inside an other contour using the hierarchy.