资源简介
k均值聚类算法,代码实现
代码片段和文件信息
#include “comm.hpp“
#define K 5
#define TH 0.02 //阈值
#define SAMPLE_NUM 100 //样本数量
#define HEIGHT 512
#define WIDTH 512
#define RANDOM_X (rand() % WIDTH) //通过取余取得指定范围的随机数
#define RANDOM_Y (rand() % HEIGHT) //通过取余取得指定范围的随机数
#define RANDOM_COLOR (rand() % 255)
typedef struct _feature
{
double x; //特征x
double y; //特征y
} FEATURE;
typedef struct _sample
{
FEATURE feature;
int cluster; //所属的类
} SAMPLE;
typedef struct _cluster
{
FEATURE center;
FEATURE pre_center;
int count; //样本个数
} CLUSTER;
typedef struct _color
{
unsigned char val[3];
} COLOR;
static CLUSTER c[K];
static COLOR color[K];
static SAMPLE s[SAMPLE_NUM];
static IplImage *p_image = NULL;
static double dist(FEATURE f1 FEATURE f2)
{
double x = f1.x - f2.x;
double y = f1.y - f2.y;
return static_cast(sqrt(x * x + y * y));
}
static void update_center()
{
double x[K]y[K];
memset(x0sizeof(x));
memset(y0sizeof(y));
for(int i = 0; i < SAMPLE_NUM; i++)
{
x[s[i].cluster] += s[i].feature.x;
y[s[i].cluster] += s[i].feature.y;
}
for(int i = 0; i < K; i++)
{
c[i].pre_center = c[i].center;
c[i].center.x = x[i] / c[i].count;
c[i].center.y = y[i] / c[i].count;
c[i].count = 0;
}
}
static bool good_result()
{
for(int i = 0; i < K; i++)
{
if(dist(c[i].centerc[i].pre_center) > TH)
return false;
}
return true;
}
static void show_outcome()
{
unsigned char *data = NULL;
for(int y = 0; y < HEIGHT; y++)//这里将平面中所有的点都标记,就可以看到平面是怎样被划分的了
{
data = (unsigned char *)(p_image->widthStep * y + p_image->imageData);
for(int x = 0; x < WIDTH; x++)
{
double min_dist = 1000;
int min_k = 0;
FEATURE f;
f.x = x;
f.y = y;
for(int i = 0; i < K; i++)
{
double tmp = dist(c[i].center f);
if(tmp < min_dist)
{
min_dist = tmp;
min_k = i;
}
}
*(data + (x * p_image->nChannels + 0)) = color[min_k].val[0];
*(data + (x * p_image->nChannels + 1)) = color[min_k].val[1];
*(data + (x * p_image->nChannels + 2)) = color[min_k].val[2];
*(data + (x * p_image->nChannels + 3)) = 200;
// IMG_B(imgxy) = color[min_k].val[0];
// IMG_G(imgx
- 上一篇:C++命令行实现的学生社团管理系统
- 下一篇:文件版本号修改
评论
共有 条评论