Search code examples
c++opencvcompiler-errorsset

error in creation of Set from Points


I want to have a set of all Pixel Coordinates of an image. Unfortunately i get the following error message:

"error C2678: binary '<' : 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));
    }
}

I suspect that every type that goes into a set has to provide functions for comparison and cv::Point fails to do that. Unfortunately I'm new to C++ and OpenCV and don't know how to check if my suspicion is true.


Solution

  • the long story : if you want to use a set of points, you need to supply a compare operation for points:

    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;
    }
    

    on the otther hand, you'd only need a set, if there were duplicate points to avoid. not so here.

    so it's probably easier just to use a vector instead:

    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;
    }