1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
|
#include <flann/flann.h>
#include <stdio.h>
#include <stdlib.h>
float* read_points(const char* filename, int rows, int cols)
{
float* data;
float *p;
FILE* fin;
int i,j;
fin = fopen(filename,"r");
if (!fin) {
printf("Cannot open input file.\n");
exit(1);
}
data = (float*) malloc(rows*cols*sizeof(float));
if (!data) {
printf("Cannot allocate memory.\n");
exit(1);
}
p = data;
for (i=0;i<rows;++i) {
for (j=0;j<cols;++j) {
if(fscanf(fin,"%g ",p) != 1) {
printf("Input file is incorrectly formatted.\n");
exit(1);
}
}
}
fclose(fin);
return data;
}
void write_results(const char* filename, int *data, int rows, int cols)
{
FILE* fout;
int* p;
int i,j;
fout = fopen(filename,"w");
if (!fout) {
printf("Cannot open output file.\n");
exit(1);
}
p = data;
for (i=0;i<rows;++i) {
for (j=0;j<cols;++j) {
fprintf(fout,"%d ",*p);
p++;
}
fprintf(fout,"\n");
}
fclose(fout);
}
int main(int argc, char** argv)
{
float* dataset;
float* testset;
int nn;
int* result;
float* dists;
struct FLANNParameters p;
float speedup;
flann_index_t index_id;
int rows = 9000;
int cols = 128;
int tcount = 1000;
/*
* The files dataset.dat and testset.dat can be downloaded from:
* http://people.cs.ubc.ca/~mariusm/uploads/FLANN/datasets/dataset.dat
* http://people.cs.ubc.ca/~mariusm/uploads/FLANN/datasets/testset.dat
*/
printf("Reading input data file.\n");
dataset = read_points("dataset.dat", rows, cols);
printf("Reading test data file.\n");
testset = read_points("testset.dat", tcount, cols);
nn = 3;
result = (int*) malloc(tcount*nn*sizeof(int));
dists = (float*) malloc(tcount*nn*sizeof(float));
p = DEFAULT_FLANN_PARAMETERS;
p.algorithm = FLANN_INDEX_KDTREE;
p.trees = 8;
p.log_level = FLANN_LOG_INFO;
p.checks = 64;
printf("Computing index.\n");
index_id = flann_build_index(dataset, rows, cols, &speedup, &p);
flann_find_nearest_neighbors_index(index_id, testset, tcount, result, dists, nn, &p);
write_results("results.dat",result, tcount, nn);
flann_free_index(index_id, &p);
free(dataset);
free(testset);
free(result);
free(dists);
return 0;
}
|