How to find the second Largest Contour in an image
All the while, the example of coding is to calculate the biggest of the smallest area of contour in an image. Is there any idea on how to get the second largest contour area from opencv C++? I believe i can find the second largest area, but the index .. My code is quite messy sorry for that.
here is to find the biggest one.
// iterate through each contour.
for( int i = 0; i< contours.size(); i++ )
{
// Find the area of contour
double a=contourArea( contours[i],false);
arrayarea[i]=a;
if(a>largest_area)
{
largest_area=a;cout<<i<<" area "<<a<<endl;
// Store the index of largest contour
largest_contour_index=i;
cerr << largest_contour_index << "largest_contour_index" << endl;
// Find the bounding rectangle for biggest contour
//bounding_rect=boundingRect(contours[i]);
}
cerr << arrayarea[i] << "arrayarea[i]" << endl;
}
waitKey(0);
first = second = INT_MIN;
for (i = 0; i < arrayarea[i] ; i ++)
{
/* If current element is smaller than first
then update both first and second */
if (arrayarea[i] > first)
{
second = first;
first = arrayarea[i];
}
/* If arr[i] is in between first and
second then update second */
else if (arrayarea[i] > second && arrayarea[i] != first)
second = arrayarea[i];
}
if (second == INT_MIN)
printf("There is no second largest element\n");
else
printf("The second largest element is %dn", second);
What have you tried? Have you looked at the sample code to find the Biggest contour? Did you try to understand that? Where do you struck?
I have a code that gets the two largest contours: https://github.com/sjhalayka/mask_dis...
HI Balaji, as edited, I did not stuck with the biggest contour. The problem that I had stucked is to get the [i] contours which is having the second largest size edited in the question. Sorry for the quite messy coding structure.
@zms, how to sort a vector
take a look at SO post