1

我从图像中找到了轮廓。我想从轮廓中找到最小点和最小点。

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 检索数据。有人请帮帮我吗?

如果我想从轮廓中访问点 y 的值,该怎么做?我真的对这些数据类型感到困惑。

4

2 回答 2

2

您可以从minmax_element文档中看到它返回一对迭代器。

鉴于:

vector<Point> pts = ...
auto mmx = std::minmax_element(pts.begin(), pts.end(), less_by_y);

您可以使用 访问最小元素mmx.first的迭代器,使用 访问最大元素的迭代器mmx.second

如果你想检索y你需要做的最小值和最大值:

int min_y = mmx.first->y;
int max_y = mmx.second->y;

由于您在 OpenCV 中,因此您还可以y使用以下方法找到值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如果需要,这也会计算 min 和 max 。


这里有一个完整的例子:

#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;
}
于 2015-11-22T12:10:05.077 回答
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.

于 2015-11-22T09:34:27.207 回答