Ask Your Question
0

Retrieving two highest values from vector

asked 2013-02-22 20:41:29 -0600

Tomazi gravatar image

Hi people

I have declared a vector that stores an area of all Bounding Boxes in a given frame. I then used a iterated this vector from beginning to end to retrieve value. I then sorted these values in ascending order (lowest -> highest).

Here is the Code i use:

  double area = contourArea(boundingBoxArea);
        list_area.push_back(area);
        sort(list_area.begin(), list_area.end());
        vector<double>::const_iterator area_iter;

        int i = 0;
        for(area_iter = list_area.begin(); area_iter != list_area.end(); area_iter++)
        {
            i++;
            cout<<"Iterator " <<i<< " size is : " <<*area_iter<<endl;
        }

My issue is that I am only interested in the last two values out of the set of numbers (2 highest values) but I cant really get my head around it to how should i go about it to achieve my goal.

Anyone out here has a suggestion or solution to my problem...?

Regards

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2013-02-24 07:47:28 -0600

Guanta gravatar image

If list_area is a std::vector<double> than the largest two values you just get by taking the last two from your sorted vector:

double largest_area = list_area[list_area.size()-1];
double 2nd_largest_area = list_area[list_area.size()-2];

If it is not a std::vector<double>, then either change your list to a vector or access it via the reverse-iterator:

std::list<double>::reverse_iterator rit = list_area.rbegin();
double largest_area = *rit;
double 2nd_largest_area = *(++rit);

Btw: OpenCV also offers a sort and also a sortIdx method, the latter one may be worth considiering, since I guess you also would like the corresponding contours from your largest two areas. Then you just need to convert your vector to a Matrix, then sort by index and take the first two indices. Example: Considering you have your contours as std::vector<std::vector<cv::Point> > all_contours, and the corresponding sizes in a std::vector<double> sizes. Then you get the two largest areas in the following way (code not tested):

cv::Mat1d size_mat(1, list_area.size(), list_area);
cv::Mat1i ind;
cv::sortIdx(size_mat, ind, CV_SORT_EVERY_ROW | CV_SORT_DESCENDING);
std::vector<cv::Point> largest_contour = all_contours[ind(0,0)];
std::vector<cv::Point> 2nd_largest_contour = all_contours[ind(0,1)];
edit flag offensive delete link more

Question Tools

Stats

Asked: 2013-02-22 20:41:29 -0600

Seen: 1,920 times

Last updated: Feb 24 '13