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;
}
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?
If i want to access the value of point y from contours, how to do it? I really confused with those data types.
You can see from minmax_element documentation that it returns a pair of iterators.
Given:
vector<Point> pts = ...
auto mmx = std::minmax_element(pts.begin(), pts.end(), less_by_y);
you can access the iterator to the min element with mmx.first
, and the iterator to the max element with mmx.second
.
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;
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!!!
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;
}
From the std::minmax()
docs:
a pair consisting of an iterator to the smallest element as the first element and an iterator to the greatest element as the second. Returns std::make_pair(first, first) if the range is empty. If several elements are equivalent to the smallest element, the iterator to the first such element is returned. If several elements are equivalent to the largest element, the iterator to the last such element is returned.
So mmx.first
is the minimum and mmx.second
is the maximum.