Ask Your Question

Revision history [back]

I don't know what you want exactly but results seems is OK(may be there is a bug...)

#include <opencv2/opencv.hpp> 
#include <iostream>
#include <fstream>

using namespace std;
using namespace cv;

int main (int argc,char **argv)
{
    VideoCapture vid(0);


    if (!vid.isOpened())
    {
        cout << "cannot open video stream!";
        return 0;
    }
    int code = 0;
    Mat img;
    Mat labels;
    Mat centers; 
    int mode = 0;
    while (code != 27)
    {
        vid >> img;
        if (img.empty())
        {
            cout << "cannot read video stream!";
            return 0;
        }
        Mat src, srcF;

        img.convertTo(srcF, CV_32FC3);
        vector<Vec3f> plan;
        plan.assign((Vec3f*)srcF.datastart, (Vec3f*)srcF.dataend);
        int clusterCount = 18;
        if (centers.empty())
            kmeans(plan, clusterCount, labels, TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 10, 1.0), 10, KMEANS_PP_CENTERS, centers);
        else
            kmeans(plan, clusterCount, labels, TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 10, 1.0), 1, KMEANS_USE_INITIAL_LABELS, centers);
        Mat mask;
        imshow("Original", img);
        int maxCluster = 0, ind = -1;
        Mat result = Mat::zeros(img.rows, img.cols, CV_8UC3);
        labels = labels.reshape(0, img.rows);
        for (int i = 0; i < clusterCount; i++)
        {
            cv::Mat cloud = (labels == i);
            result.setTo(Scalar(centers.at<float>(i, 0), centers.at<float>(i, 1), centers.at<float>(i, 2)), cloud);
        }
        labels = labels.reshape(0, img.rows*img.cols);
        imshow("New", result);
        code = waitKey(10);
        if (code == 'r')
            centers = Mat();
        if (code == 'n')
            mode = 1;
        if (code == 'u')
            mode = 0;
        if (mode == 1)
            centers = Mat();
    }
}