从点创建集合时出错

问题描述 投票:0回答:2

我想要一组图像的所有像素坐标。不幸的是我收到以下错误消息:

“错误 C2678:二进制 '<' : no operator found which takes a left-hand operand of type 'const cv::Point' (or there is no acceptable conversion)"

Mat img;
img = imread( "[...]\\picture.jpg", 1 );

set<Point> pointset;
for( int x = 0 ; x < img.cols ; x++)
{
    for (int y = 0 ; y < img.rows ; y++)
    {
        pointset.insert(Point(x,y));
    }
}

我怀疑进入集合的每种类型都必须提供比较函数,而 cv::Point 无法做到这一点。不幸的是,我是 C++ 和 OpenCV 的新手,不知道如何检查我的怀疑是否属实。

c++ opencv compiler-errors set
2个回答
3
投票

长话短说:如果你想使用一组点,你需要为点提供比较操作:

struct comparePoints {
    bool operator()(const Point & a, const Point & b) {
        return ( a.x<b.x && a.y<b.y );
    }
};

int main()
{
    Mat img = imread( "clusters.png", 1 );

    set<Point,comparePoints> pointset;
    for( int x = 0 ; x < img.cols ; x++)
    {
        for (int y = 0 ; y < img.rows ; y++)
        {
            pointset.insert(Point(x,y));
        }
    }
    return 0;
}

另一方面,如果需要避免重复的点,您只需要一组。这里不是这样。

所以使用向量可能更容易:

int main()
{
    Mat img = imread( "clusters.png", 1 );

    vector<Point> points;
    for( int x = 0 ; x < img.cols ; x++)
    {
        for (int y = 0 ; y < img.rows ; y++)
        {
            points.push_back(Point(x,y));
        }
    }
    return 0;
}

0
投票

@berak 的代码需要添加 const,否则错误 C3848:

struct comparePoints {
  bool operator()(const POINT& a, const POINT& b) const {
    return a.x < b.x || (a.x == b.x && a.y < b.y);
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.