سؤال

friends, I am coding using opencv. I want to find three largest contour in picture/video, I have write code that can find two largest contour, I have difficulty in finding third largest, so I need your suggestions,Merry Christmas! Here is my core code, how to change.

CvSeq *cont = 0
cvFindContours( tempImg, storage, &cont, sizeof(CvContour), 
CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0) ); 

CvSeq *contmax = 0;
CvSeq *contmax2 = contmax;

for(;cont;cont = cont->h_next) //get the two max area, and mark
{
    area = fabs(cvContourArea( cont, CV_WHOLE_SEQ )); 
    printf("area == %lf\n", area);
    if(area > maxArea)
    {
        contmax2 = contmax;
        max2Area = maxArea;
        contmax = cont;
        maxArea = area;
    }
    else if(area > max2Area && area < maxArea)
    {
        contmax2 = cont;
        max2Area = area;
    }

}
CvRect aRect = cvBoundingRect( contmax, 0 );
CvRect bRect = cvBoundingRect( contmax2, 0 ); 
هل كانت مفيدة؟

المحلول

What about this?:

#define N 3

double maxArea[N] = {0};
CvSeq *countours[N], *tmp_cont;
double tmp_area;

for(;cont;cont = cont->h_next)
{
    area = fabs(cvContourArea(cont, CV_WHOLE_SEQ));
    printf("area == %lf\n", area);

    for(int i = N-1; i >= 0; --i)
    {
        if(area > maxArea[i])
        {
            maxArea[i] = area;
            countours[i] = cont;
            for(int j = (i-1); j >= 0; --j)
            {
                if(maxArea[j] < maxArea[j+1])
                {
                    tmp_area = maxArea[j+1];
                    tmp_cont = contours[j+1];
                    maxArea[j+1] = maxArea[j];
                    contours[j+1] = contours[j];
                    maxArea[j] = tmp_area;
                    contours[j] = tmp_cont;
                }
            }
            break;
        }
    }

}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top