找到点矢量的最小值和最大值

use*_*647 2 c++ opencv

我想从点向量中找到最小值和最大值.向量由x和y元素类型组成.我想要x的最小值和最大值以及y的最小值.我的矢量定义为:

 std::vector<cv::Point> location;
findNOZeroInMat(angles,location);

//I tried to use but it gives an error
  minMaxLoc(location.cols(0), &minVal_x, &maxVal_x);
    minMaxLoc(location.cols(1), &minVal_y, &maxVal_y);
Run Code Online (Sandbox Code Playgroud)

我也尝试过location.x但它没有用.如何单独获得x和y的最小值和最大值?

jua*_*nza 7

您可以将std :: minmax_element与自定义小于比较函数/ 仿函数一起使用:

#include <algorithm>

bool less_by_x(const cv::Point& lhs, const cv::Point& rhs)
{
  return lhs.x < rhs.x;
}
Run Code Online (Sandbox Code Playgroud)

然后

auto mmx = std::minmax_element(location.begin(), location.end(), less_by_x);
Run Code Online (Sandbox Code Playgroud)

并且类似地y.mmx.first将具有最小元素的迭代器,并且mmx.second具有最大元素的迭代器.

如果您没有C++ 11支持,则auto需要明确:

typedef std::vector<cv::Point>::const_iterator PointIt;
std::pair<PointIt, PointIt> mmx = std::minmax_element(location.begin(), 
                                                      location.end(), 
                                                      less_by_x);
Run Code Online (Sandbox Code Playgroud)

但请注意,这std::minmax_element需要C++ 11库支持.