# 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);

edit retag close merge delete

1

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?

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.

Sort by » oldest newest most voted

@zms As @berak and @sturkmen proposed, you can sort your vector of contours based off of their areas and pick the second element; if sorted in ascending order. To achieve this, you would need to pass a lambda function to sort(). Keep in mind though that the sorting operation is O(N log(N)). If this method deems hard for you to implement; especially with the lambda stuff, then I would recommend following this easier tutorial then convert the logic to use contourArea instead. If done correctly, it should give you the index of the second largest contour and its O(N)

more

Official site

GitHub

Wiki

Documentation