Main Func
```c++
void kNN()
{
img = Mat::zeros(Size(500, 500), CV_8UC3);
knn = KNearest::create();
namedWindow("knn");
//createTrackbar("k", "knn", &k_value, 5, on_k_changed);
const int NUM = 30;
Mat rn(NUM, 2, CV_32SC1);
randn(rn, 0, 50);
for (int i = 0; i < NUM; i++)
addPoint(Point(rn.at(i, 0) + 150, rn.at(i, 1) + 150), 0);
randn(rn, 0, 50);
for (int i = 0; i < NUM; i++)
addPoint(Point(rn.at(i, 0) + 350, rn.at(i, 1) + 150), 1);
randn(rn, 0, 70);
for (int i = 0; i < NUM; i++)
addPoint(Point(rn.at(i, 0) + 250, rn.at(i, 1) + 400), 2);
createTrackbar("k", "knn", &k_value, 5, on_k_changed);
trainAndDisplay();
waitKey();
return;
}
```
Display Func
```c++
void trainAndDisplay()
{
knn->train(train, ROW_SAMPLE, label);
for (int i = 0; i < img.rows; ++i) {
for (int j = 0; j < img.cols; ++j) {
Mat sample = (Mat_(1, 2) << j, i);
Mat res;
knn->findNearest(sample, k_value, res);
int response = cvRound(res.at(0, 0));
if (response == 0)
img.at(i, j) = Vec3b(128, 128, 255); // R
else if (response == 1)
img.at(i, j) = Vec3b(128, 255, 128); // G
else if (response == 2)
img.at(i, j) = Vec3b(255, 128, 128); // B
}
}
for (int i = 0; i < train.rows; i++)
{
int x = cvRound(train.at(i, 0));
int y = cvRound(train.at(i, 1));
int l = label.at(i, 0);
if (l == 0)
circle(img, Point(x, y), 5, Scalar(0, 0, 128), -1, LINE_AA);
else if (1 == 1)
circle(img, Point(x, y), 5, Scalar(0, 128, 0), -1, LINE_AA);
else if (1 == 2)
circle(img, Point(x, y), 5, Scalar(128, 0, 0), -1, LINE_AA);
}
imshow("knn", img);
imwrite("knn-result1.png", img);
}
```
![Result](/09_KNN//knn-result1.png)