Ask Your Question
2

Merge contour from vector<Points>

asked 2020-06-26 09:47:11 -0600

Visionmop gravatar image

updated 2020-06-26 09:58:24 -0600

I would like to form an external contour from different vector points. The individual contours are continuous and contain curved lines (1 pixel wide). The merged contour should connect the lines like as marked in red in the image below

image description => image description

I would transfer the single points into a total vector. How can i determine the order I have to follow? I suppose every single contour must be ordered clockwise?

//xPts = vector<vector<int>> containing all x-Values of contour

int cntContours = xPts.size();
std::vector<cv::Point> contourMerged;
for (int cn = 0; cn < cntContours; cn++)
{
    vector<double> xTmp =  xPts[cn];
    vector<double> yTmp =  yPts[cn];

    for (int pn = 0; pn < xTmp.size(); pn++)
    {
        cv::Point tmp;
        int xt = (int)xTmp[pn];
        int yt = (int)yTmp[pn];
        tmp.x = xt;
        tmp.y = yt;

        contourMerged.push_back(tmp);
    }

}
// close contour
contourMerged.push_back(contourMerged[0]);

Thank you!

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2020-06-29 08:10:08 -0600

you can try the code below which finds a center point between all contours and sorts contours circularly ( maybe this will be a starting point )

#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>

using namespace cv;
using namespace std;

Point center;

struct contour_sorter
{
    bool operator ()(const vector<Point>& a, const vector<Point>& b)
    {
        double angle1 = atan2(a[0].y - center.y, a[0].x - center.x) * 180.0 / CV_PI;
        double angle2 = atan2(b[0].y - center.y, b[0].x - center.x) * 180.0 / CV_PI;
        return (angle1 < angle2);
    }
};

int main(int argc, char** argv)
{
    Mat src = imread("15931824191786043.jpg");
    Mat bw;

    cvtColor(src, bw, COLOR_BGR2GRAY);
    bw = bw < 127;

    Rect r = boundingRect(bw);
    center = (r.tl() + r.br()) * 0.5;

    // Find contours
    vector<vector<Point> > contours;
    vector<Point> allcontours;
    findContours(bw, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);

    sort(contours.begin(), contours.end(), contour_sorter());

    for (size_t i = 0; i < contours.size()-1; i++)
    {
        drawContours(src, contours, i, Scalar(0, 0, 255), 1);

        imshow("src", src);
        waitKey(0);
    }
    waitKey(0);
}
edit flag offensive delete link more

Comments

Thank you, I think i can deal with this

Visionmop gravatar imageVisionmop ( 2020-07-06 04:30:56 -0600 )edit

i have some ideas about next steps but did not try well. tell me please your progress if any.

sturkmen gravatar imagesturkmen ( 2020-07-06 05:51:43 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2020-06-26 09:47:11 -0600

Seen: 3,454 times

Last updated: Jun 29 '20