2013-08-26 111 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();