Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 765
Andre Avatar asked Mar 13 '23 23:03

Andre


1 Answers

minmax_element runs the comparison on Point objects and will return Point objects.

The x and y values are independent and it is likely that the min(x) and min(y) will belong to different objects.

I would use for range for this particular case.

Min = Point(640, 480) ;
Max = Point(0,0) ;
for (auto &p : contour)
{
    Min.x = std::min(p.x, Min.x)
    Min.y = std::min(p.y, Min.y)
    Max.x = std::max(p.x, Max.x)
    Max.y = std::max(p.y, Max.y)
}
like image 99
Juan Leni Avatar answered Apr 28 '23 04:04

Juan Leni