首页 > 代码库 > OpenCV+KMeans算法

OpenCV+KMeans算法

<span style="font-size:18px;">#include <opencv2/opencv.hpp>
#include <iostream>
 
using namespace std;
using namespace cv;
 
int main(int argc, char** argv)
{
    #define  MAX_CLUSTERS 5
    CvScalar color_table[MAX_CLUSTERS];
    IplImage* img = cvCreateImage(cvSize(500,500),8,3);
    cvNamedWindow("source", 1);
    cvShowImage("source", img);
    cvWaitKey(0);
    CvRNG rng = cvRNG(0xffffffff);
    color_table[0] = CV_RGB(255,0,0);
    color_table[1] = CV_RGB(0,255,0);
    color_table[2] = CV_RGB(0,0,255);
    color_table[3] = CV_RGB(255,0,255);
    color_table[4] = CV_RGB(255,255,0);
    cvNamedWindow("clusters", 1);
    while(true)
    {
        int k, cluster_count = cvRandInt(&rng)%MAX_CLUSTERS + 1;
        int i, sample_count = cvRandInt(&rng)%1000 + 1;
        CvMat* points = cvCreateMat(sample_count,1,CV_32FC2);
        CvMat* clusters  = cvCreateMat(sample_count,1,CV_32SC1);
        //高斯分布产生随机点
        for (k = 0; k < cluster_count; k++)
        {
            CvPoint center;
            CvMat point_chunk;
            center.x = cvRandInt(&rng)%img->width;
            center.y = cvRandInt(&rng)%img->height;
            cvGetRows(points, &point_chunk, k*sample_count/cluster_count,
                k == cluster_count - 1 ? sample_count:(k+1)*sample_count/cluster_count);
            cvRandArr(&rng,&point_chunk,CV_RAND_NORMAL,cvScalar(center.x,center.y,0,0),
                cvScalar(img->width/6, img->height/6,0,0));
        }
        for(i = 0; i < sample_count/2; i++)
        {
            CvPoint2D32f* pt1 = (CvPoint2D32f*)points->data.fl + cvRandInt(&rng)%sample_count;
            CvPoint2D32f* pt2 = (CvPoint2D32f*)points->data.fl + cvRandInt(&rng)%sample_count;
            CvPoint2D32f temp;
            CV_SWAP(*pt1,*pt2, temp);
        }
        cvKMeans2(points,cluster_count,clusters,cvTermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER,10, 1.0));
        cvZero(img);
        for(i = 0; i < sample_count; i++ )
        {
            CvPoint2D32f pt = ((CvPoint2D32f*)points->data.fl)[i];
            int cluster_idx = clusters->data.i[i];
            cvCircle(img, cvPointFrom32f(pt), 2, color_table[cluster_idx], CV_FILLED);
        }
        cvReleaseMat(&points);
        cvReleaseMat(&clusters);
        cvShowImage("clusters", img);
        if(cvWaitKey(0) == 27)   //'ESC'
            break;
    }
    return 0;
}</span>

技术分享


技术分享



OpenCV+KMeans算法