I am trying to use OpenCV’s KNearest function (OpenCV 4.5.1, C++) to calculate the distance to the nearest neighbor. I am not interested in either classification or regression, simply measuring this distance. I am able to accomplish this when using the ‘Brute Force’ version of the algorithm but not the ‘KDTree’ version.
I have run some simple experiments to try to get this working. Here is some test code:
`cv::Mat trainData = (cv::Mat_(5, 2) << 3.0, 3.0, 4.0, 4.0, 5.0, 5.1, 7.0, 7.1, 10.1, 11);
cv::Mat trainLabels = (cv::Mat_(5, 1) << 0, 0, 0, 0, 0);
cv::Ptr<cv::ml::KNearest> knnKdt = cv::ml::KNearest::create();
knnKdt->setAlgorithmType(cv::ml::KNearest::KDTREE);
knnKdt->train(trainData, cv::ml::ROW_SAMPLE, trainLabels);
cv::Mat testData = (cv::Mat_(2, 2) << 15, 14, 4, 4.1);
cv::Mat result, responses, dists;
knnKdt->findNearest(testData, 1, result, responses, dists);`
When I use the debugger to inspect the variables AFTER having called ‘findNearest’, I see that ‘result’ is of size (2, 1) and that both ‘responses’ and ‘dists’ are of size (0, 0). Why is the function not calculating the distances for me? Is there something that I’m missing? When I use the brute force version, everything works as expected. Thanks in advance for any help that you can offer.