Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Contours Centers pass to K-Means ??

Hi All, I am learning about opencv and used some functions. Now i am working on a project to detect the direction of people / object. For this purpose i need find the center of the object. After Background Subtraction the object comes in different part of contours and need to join them into ONE. I have read about K-Means Clustering but i am unable to pass the 2D vector float data. Would you please give me sample example code how to achieve my goal.

/// Find contours findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );

/// Get the moments
vector<Moments> mu(contours.size() );
for( int i = 0; i < contours.size(); i++ )
 { mu[i] = moments( contours[i], false ); }

///  Get the mass centers:
vector<Point2f> mc( contours.size() );
for( int i = 0; i < contours.size(); i++ )
 { mc[i] = Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }

I got the centers of all contours into MC and now need to pass to K-Means. I have learnt with the examples which is working but not sure about my real data.

float data2[15][2]=
    {{118.90323, 1088.7419},
    {143.5, 1064.5},
    {110, 1054},
    {662, 645},
    {650, 625.5},
    {94, 363},
    {60, 360},
    {103.97369, 315.71054},
    {70.5, 313},
    {70.1, 313},
    {70.2, 313},
    {70.3, 313},
    {70.4, 313},
    {70.7, 313},
    {1466, 278.55554}};

    Mat centers1;
    Mat points1(15,2, CV_32FC1,*data2);
    //std::vector<cv::Point2f> points1(data2);  //std::cout << points1 << std::endl;
    Mat labels1;
    int k =4;
    cv::kmeans(points1,k, labels1,TermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 10, 1.0),3, KMEANS_PP_CENTERS, centers1);
    std::cout << "labels: " << labels1 << endl;
    std::cout << "centers " << centers1 << endl;

Looking forward your assistance in this regard. Shan