簡體   English   中英

從std :: vector檢索值 <cv::Point> ::為const_iterator

[英]Retrieve value from std::vector<cv::Point>::const_iterator

我從圖像中找到了輪廓。 我想從輪廓中找到最小點和最小點。

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點的值,該怎么做? 我真的對那些數據類型感到困惑。

您可以從minmax_element文檔中看到它返回了一對迭代器。

鑒於:

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

您可以使用mmx.first來訪問min元素的迭代器,使用mmx.second來訪問max元素的迭代器。

如果要檢索最小和最大y值,則需要執行以下操作:

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

由於您在OpenCV中,因此還可以使用boudingRect查找y值:

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!!!

盡管這可能會比較慢,但是您無需定義自定義比較功能。 如果需要,這還將計算min和max x


這里是一個完整的例子:

#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::minmax()文檔

一對,由最小元素的迭代器作為第一個元素,至最大元素的迭代器作為第二個元素。 如果范圍為空,則返回std :: make_pair(first,first)。 如果幾個元素等於最小的元素,則返回第一個此類元素的迭代器。 如果幾個元素等於最大元素,則返回最后一個此類元素的迭代器。

因此, mmx.first是最小值, mmx.second是最大值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM