How to replace my 'for' loop to find min/max by STL mimax algorithm

Viewed 265

I have to find the min/max values (min x, min y, max x, max y) from a

vector<cv::Point>

Here my code:

vector<cv::Point> contour;

...

Min = Point(640, 480) ;
Max = Point(0,0) ;
for (int j=0; j<(int)contour.size(); j++)
{
    if (contour[j].x < Min.x) Min.x = contour[j].x ;
    if (contour[j].y < Min.y) Min.y = contour[j].y ;
    if (contour[j].x > Max.x) Max.x = contour[j].x ;
    if (contour[j].y > Max.y) Max.y = contour[j].y ;
}

This works fine. I developped a version using mimmax STL:

auto XminXmax = minmax_element(contour.begin(), contour.end(), [](Point p1,Point p2) {return p1.x < p2.x; });
auto YminYmax = minmax_element(contour.begin(), contour.end(), [](Point p1,Point p2) {return p1.y < p2.y; });
Point Min = Point((*XminXmax.first).x, (*YminYmax.first).y );
Point Max = Point((*XminXmax.second).x, (*YminYmax.second).y );

This also works fine and give the same results. However as the algo minmax is called twice, the execution time is twice. Is it possible to optimize this with one call to the minmax algo ?

2 Answers
Related