Ask Your Question
0

How to write this kmeans python code in c++?

asked 2019-11-20 05:56:54 -0600

Naman Gupta gravatar image

updated 2019-11-20 06:21:14 -0600

I have tried converting this much till now and not able to understand how to convert the rest of it.

def segment_by_angle_kmeans(lines, k=3, **kwargs):
        default_criteria_type = cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER
        criteria = kwargs.get('criteria', (default_criteria_type, 10, 1.0))
        flags = kwargs.get('flags', cv2.KMEANS_RANDOM_CENTERS)
        attempts = kwargs.get('attempts', 10)

        angles = np.array([line[0][1] for line in lines])
        pts = np.array([[np.cos(2 * angle), np.sin(2 * angle)]
                        for angle in angles], dtype=np.float32)
        labels, centers = cv2.kmeans(pts, k, None, criteria, attempts, flags)[1:]
        labels = labels.reshape(-1)

        segmented = defaultdict(list)
        for i, line in zip(range(len(lines)), lines):
            segmented[labels[i]].append(line)

        segmented = list(segmented.values())
        return segmented

C++ code:-

vector<Vec2f> segment(vector<Vec2f> lines, int k = 3) {
    vector<Vec2f> segmented;
    Mat labels;
    vector<Vec2f> angles;

    for (int i = 0; i < lines.size(); i++) {
        float angle = lines[i][1];
        angles.push_back(angle);
    }
    Mat points(angles.size,2, );
    for (int j = 0; j < angles.size(); j++) {
        float angle = 2 * angles[j][1]; 
        float c = cos(angle);
        float s = sin(angle);
        points[j][0] = c;
        points[j][1] = s;
    }
    vector<Vec2f> labels = kmeans(points, k, labels,TermCriteria(TermCriteria::EPS + TermCriteria::MAX_ITER, 10, 1.0),10, KMEANS_RANDOM_CENTERS);
    return segmented;
}

Please Help.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
0

answered 2019-11-20 06:56:30 -0600

berak gravatar image

i don't see any gain in transforming the angles to 2d points, but for now, you probably wanted this:

Mat points(angles.size,2, CV_32F);
for (int j = 0; j < angles.size(); j++) {
    float angle = 2 * angles[j][1]; 
    float c = cos(angle);
    float s = sin(angle);
    points.at<float>(j,0) = c;
    points.at<float>(j,1) = s;
}
vector<int> labels; // if k==3, each point gets a label 0,1,2
TermCriteria term(TermCriteria::EPS + TermCriteria::MAX_ITER, 10, 1.0);
kmeans(points, k,  labels, term, 10, KMEANS_PP_CENTERS);
edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2019-11-20 05:56:54 -0600

Seen: 210 times

Last updated: Nov 20 '19