Store details of a binary image consisting simple polygons

后端 未结 4 1522
礼貌的吻别
礼貌的吻别 2020-12-22 14:56

This question relates to somewhat practice and experienced based process. I have an Mat binary image which consist of simple white color polygons in a black background. Actu

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-22 15:24

    You can simply use findContours, with an appropriate contour approximation method. Basically, aside from CV_CHAIN_APPROX_NONE that will store all points, every other method is fine for this example: CV_CHAIN_APPROX_SIMPLE, CV_CHAIN_APPROX_TC89_L1 and CV_CHAIN_APPROX_TC89_KCOS.

    You can store those points in your database. You can then reload those points, and draw original image with fillPoly.

    This simple example show the retrieved contours points with the approximation method, and how to re-draw the image with those points.

    Note that you're image is aliased (you probably saved it in jpeg before png), so you need to remove aliasing for example keeping only points with value equals to 255.

    #include 
    #include 
    using namespace std;
    using namespace cv;
    
    int main()
    {
        Mat1b img = imread("path_to_image", IMREAD_GRAYSCALE);
    
        // Removing compression artifacts
        img = img == 255;
    
        vector> contours;
        findContours(img.clone(), contours, RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
    
        if (contours.empty()) {return -1;}
    
        // Save the vertices "contours[0]"
    
        // Result image
        Mat3b res;
        cvtColor(img, res, COLOR_GRAY2BGR);
        for (int i = 0; i < contours[0].size(); ++i)
        {
            circle(res, contours[0][i], 3, Scalar(0,255,0));
        }
    
        // Reconstruct image from contours vertex
    
        // Load the vertices
        vector> vertices = { contours[0] };
    
        Mat1b rec(img.rows, img.cols, uchar(0));
        fillPoly(rec, vertices, Scalar(255));
    
        imshow("Vertices", res);
        imshow("Reconstructed", rec);
        waitKey();
    
        return 0;
    }
    

    Green vertices with contour approximation method:

提交回复
热议问题