I am still new in C++ and now I need to convert some parts from this old program of mine from C to C++ because I want to apply BackgroundSubtractorMOG2
in my program since it only available in C++. Basically this program will detect contours from a video camera based on background subtraction and choose the largest contours available.
I have a problem particularly on this part (taken from the old program):
double largestArea = 0; //Const. for the largest area
CvSeq* largest_contour = NULL; //Contour for the largest area
while (current_contour != NULL){ //If the current contour available
double area = fabs(cvContourArea(current_contour,CV_WHOLE_SEQ, false)); //Get the current contour's area as "area"
if(area > largestArea){ //If "area" is larger than the previous largest area
largestArea = area;
largest_contour = current_contour;
}
current_contour = current_contour->h_next; //Search for the next contour
}
This part is where the program will scan each contour available as current_contour
, find its area and compare it to previous largest contour. My question is how to get the current_contour
, its area and jump to the next contour in C++? Also, what is indicated by contours.size()
in C++? Is it the number of contours scanned or the total area of the contours?
This is what I've done so far:
for(;;)
{
cap >> frame; // get a new frame from camera
if( frame.empty() )
break;
image=frame.clone();
mog(frame,foreground,-1);
threshold(foreground,foreground,lowerC,upperC,THRESH_BINARY);
medianBlur(foreground,foreground,9);
erode(foreground,foreground,Mat());
dilate(foreground,foreground,Mat());
findContours(foreground,contours,CV_RETR_LIST,CV_CHAIN_APPROX_SIMPLE);
if(contours.empty())
continue;
//Starting this part
double largest_area = 0;
for(int i= 0; i < contours.size(); i++){
double area = contourArea(contours);
if(area >= largest_area){
largest_area = area;
largest_contours = contours;
}
}
//Until this part
drawContours(image,largest_contours,-1,Scalar(0,0,255),2);
imshow( "Capture",image );
imshow("Contours",foreground);
if(waitKey(30) >= 0) break;
}
Thanks in advance.
PS: The old program got some bugs in it but the algorithm works just fine. Free to as me if you need the updated program. Currently using OpenCV 2.4.3 + VS C++ 2010 Exp.
EDIT:
Thanks to everybody who're trying to help me but I already got the answer which is from here. Still, for those how still don't know: OpenCV in C
IS NOT EXACTLY THE SAME AS OpenCV in C++
.