2013-08-26 109 views
2

我想从点矢量找到最小值和最大值。该向量由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); 

我试过了location.x,但它没有起作用。我怎样才能分别得到x和y的最小值和最大值?

+0

'std :: partial_sort'与自定义比较器。 –

+0

你的意思是排序矢量,并将第一个元素作为最小值和最大值? – user1583647

+0

对矢量进行部分排序,是的。 –

回答

6

您可以使用std::minmax_element定制小于比较函数/仿函数:

#include <algorithm> 

bool less_by_x(const cv::Point& lhs, const cv::Point& rhs) 
{ 
    return lhs.x < rhs.x; 
} 

然后

auto mmx = std::minmax_element(location.begin(), location.end(), less_by_x); 

,类似的还有ymmx.first将有一个迭代器到最小元素,并且mmx.second达到最大值。

如果你没有为auto C++ 11的支持,你需要明确:

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

但要注意,std::minmax_element需要C++ 11库支持。

+0

当我使用这个自动mm = minmax_element(location.begin(),location.end(),less_by_x); auto mmy = minmax_element(location.begin(),location.end(),less_by_y);我得到一个错误mm和mmy没有名称类型 cout <<“min_x”<< mm.first <<“max_x”<< mm.second <<“min_y”<< mmy.first <<“max_y “<< mmy.second << ENDL; – user1583647

+0

@ user1583647你有支持'auto'的C++ 11吗?否则,你需要明确。我会添加一个例子。 – juanchopanza

0

cv::boundingRect正在做你想做的。它

计算点集的右上限矩形。

结果是,其具有的属性x, y, width, heigthcv::Rect的类型,但也提供了方法tl(=左上)和br(=右下角),其对应于所需分钟。和最大。值:

std::vector<cv::Point> points; 
// do something to fill points... 

cv::Rect rect = cv::boundingRect(points); 
cv::Point minVal = rect.tl(); 
cv::Point maxVal = rect.br();