问题
I have tried to implement this code, but I have a trouble when I want to determine the most extreme point of the contour follow this tutorial.
# determine the most extreme points along the contour
extLeft = tuple(c[c[:, :, 0].argmin()][0])
extRight = tuple(c[c[:, :, 0].argmax()][0])
extTop = tuple(c[c[:, :, 1].argmin()][0])
extBot = tuple(c[c[:, :, 1].argmax()][0])
Can anyone help me to solve this problem?
回答1:
Starting from a std::vector<cv::Point>
, you can use std::max_element
and std::min_element
with an appropriate comparator, that works on x
coordinates to find left and right points, and works on y
coordinates to find top and bottom points:
// Your points
vector<Point> pts;
...
Point extLeft = *min_element(pts.begin(), pts.end(),
[](const Point& lhs, const Point& rhs) {
return lhs.x < rhs.x;
});
Point extRight = *max_element(pts.begin(), pts.end(),
[](const Point& lhs, const Point& rhs) {
return lhs.x < rhs.x;
});
Point extTop = *min_element(pts.begin(), pts.end(),
[](const Point& lhs, const Point& rhs) {
return lhs.y < rhs.y;
});
Point extBot = *max_element(pts.begin(), pts.end(),
[](const Point& lhs, const Point& rhs) {
return lhs.y < rhs.y;
});
来源:https://stackoverflow.com/questions/36591981/finding-extreme-points-in-contours-with-opencv-c