I think that current implementation is dangerous so lets hardcode 1 everywhere `knn` used or change the above lines to

	const int knn = 1;
	int indicesbuf[knn] = {0,};
	float distsbuf[knn] = {0.f,};
	Mat indices(1, knn, CV_32S, indicesbuf);
	Mat dists(1, knn, CV_32F, distsbuf);

Another option is to use `Matx` and don't wrap local variables with Mats