问题描述
我从图像中找到了轮廓.我想从轮廓中找到最小点和最小点.
I found a contour from an image. I want to find the min point and min point from the contours.
vector<Point> test = contours[0];
auto mmx = std::minmax_element(test.begin(), test.end(), less_by_y);
bool less_by_y(const cv::Point& lhs, const cv::Point& rhs)
{
return lhs.y < rhs.y;
}
我已经尝试过这种编码,并且可以成功运行.但是由于我的愚蠢,我不知道如何从mmx检索数据.有人请帮助我吗?
I have tried this coding and it run successfully. But due to my stupidness, i do not know how to retrieve data from mmx. Anyone please help me?
如果我要从轮廓访问y点的值,该怎么做?我真的对那些数据类型感到困惑.
If i want to access the value of point y from contours, how to do it? I really confused with those data types.
推荐答案
您可以从 minmax_element 文档,它返回一对迭代器.
You can see from minmax_element documentation that it returns a pair of iterators.
给出:
vector<Point> pts = ...
auto mmx = std::minmax_element(pts.begin(), pts.end(), less_by_y);
您可以使用mmx.first
访问min元素的迭代器,并使用mmx.second
访问max元素的迭代器.
you can access the iterator to the min element with mmx.first
, and the iterator to the max element with mmx.second
.
如果要检索最小和最大y
值,则需要执行以下操作:
If you want to retrieve the min and max y
values you need to do:
int min_y = mmx.first->y;
int max_y = mmx.second->y;
由于您使用的是OpenCV,因此还可以使用boudingRect
查找y
值:
Since you are in OpenCV, you can also find the y
values using boudingRect
:
Rect box = boundingRect(pts);
std::cout << "min y: " << box.tl().y << std::endl;
std::cout << "max y: " << box.br().y - 1 << std::endl; // Note the -1!!!
尽管这可能会慢一些,但您无需定义自定义比较功能.如果需要,这还将计算最小值和最大值x
.
Although this is probably slower, you don't need to define the custom comparison function. This computes also min and max x
, if needed.
下面是一个完整的示例:
Here a complete example:
#include <opencv2/opencv.hpp>
#include <algorithm>
#include <iostream>
using namespace cv;
bool less_by_y(const cv::Point& lhs, const cv::Point& rhs)
{
return lhs.y < rhs.y;
}
int main(int argc, char** argv)
{
// Some points
vector<Point> pts = {Point(5,5), Point(5,0), Point(3,5), Point(3,7)};
// Find min and max "y"
auto mmx = std::minmax_element(pts.begin(), pts.end(), less_by_y);
// Get the values
int min_y = mmx.first->y;
int max_y = mmx.second->y;
// Get the indices in the vector, if needed
int idx_min_y = std::distance(pts.begin(), mmx.first);
int idx_max_y = std::distance(pts.begin(), mmx.second);
// Show results
std::cout << "min y: " << min_y << " at index: " << idx_min_y << std::endl;
std::cout << "max y: " << max_y << " at index: " << idx_max_y << std::endl;
// Using OpenCV boundingRect
Rect box = boundingRect(pts);
std::cout << "min y: " << box.tl().y << std::endl;
std::cout << "max y: " << box.br().y - 1 << std::endl; // Note the -1!!!
return 0;
}
这篇关于从std :: vector< cv :: Point> :: const_iterator检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!