2013년 7월 18일 목요일

K-means Clustering using VLFeat

#include <opencv2\opencv.hpp>
#include <kmeans.h>

using namespace std;
using namespace cv;

#pragma comment(lib, "opencv_core246.lib")
#pragma comment(lib, "opencv_highgui246.lib")
#pragma comment(lib, "vl.lib")

int main()
{
// data generation
float data[200];
RNG rng(time(0));
for (int i = 0; i < 50; i++)
{
data[i*2] = rng.uniform(20, 230);
data[i*2+1] = rng.uniform(271, 480);
data[100+i*2] = rng.uniform(271, 480);
data[100+i*2+1] = rng.uniform(20, 230);
}

// kmeans initialization
VlKMeans *km = vl_kmeans_new(VL_TYPE_FLOAT, VlDistanceL2);

// parameter setting
vl_kmeans_set_algorithm(km, VlKMeansAlgorithm::VlKMeansLloyd);
vl_kmeans_set_initialization(km, VlKMeansInitialization::VlKMeansPlusPlus);

// kmeans clustering
vl_kmeans_cluster(km, data, 2, 100, 2);

// get centers
const float *centers = (const float *)vl_kmeans_get_centers(km);

// quanization
vl_uint32 assignments[100];
float distances[100];
vl_kmeans_quantize(km, assignments, distances, data, 100);

// result visualization
Mat image(500, 500, CV_8UC3);
circle(image, Point(centers[0],centers[1]), 3, Scalar(255,0,0), 2);
circle(image, Point(centers[2],centers[3]), 3, Scalar(0,0,255), 2);
for (int i = 0; i < 100; i++)
{
if (assignments[i] == 0)
circle(image, Point(data[i*2],data[i*2+1]), 1, Scalar(255,0,0), 2);
else
circle(image, Point(data[i*2],data[i*2+1]), 1, Scalar(0,0,255), 2);
}
cvShowImage("Image", &(IplImage)image);
waitKey();

// termination
vl_kmeans_delete(km);

return 0;
}

댓글 없음:

댓글 쓰기