miniflann.cpp 26.5 KB
Newer Older
wester committed
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
#include "precomp.hpp"

#define MINIFLANN_SUPPORT_EXOTIC_DISTANCE_TYPES 0

static cvflann::IndexParams& get_params(const cv::flann::IndexParams& p)
{
    return *(cvflann::IndexParams*)(p.params);
}

cv::flann::IndexParams::~IndexParams()
{
    delete &get_params(*this);
}

namespace cv
{

namespace flann
{

using namespace cvflann;

IndexParams::IndexParams()
{
    params = new ::cvflann::IndexParams();
}

template<typename T>
wester committed
29
T getParam(const IndexParams& _p, const std::string& key, const T& defaultVal=T())
wester committed
30 31 32 33 34 35 36 37 38
{
    ::cvflann::IndexParams& p = get_params(_p);
    ::cvflann::IndexParams::const_iterator it = p.find(key);
    if( it == p.end() )
        return defaultVal;
    return it->second.cast<T>();
}

template<typename T>
wester committed
39
void setParam(IndexParams& _p, const std::string& key, const T& value)
wester committed
40 41 42 43 44
{
    ::cvflann::IndexParams& p = get_params(_p);
    p[key] = value;
}

wester committed
45
std::string IndexParams::getString(const std::string& key, const std::string& defaultVal) const
wester committed
46 47 48 49
{
    return getParam(*this, key, defaultVal);
}

wester committed
50
int IndexParams::getInt(const std::string& key, int defaultVal) const
wester committed
51 52 53 54
{
    return getParam(*this, key, defaultVal);
}

wester committed
55
double IndexParams::getDouble(const std::string& key, double defaultVal) const
wester committed
56 57 58 59 60
{
    return getParam(*this, key, defaultVal);
}


wester committed
61
void IndexParams::setString(const std::string& key, const std::string& value)
wester committed
62 63 64 65
{
    setParam(*this, key, value);
}

wester committed
66
void IndexParams::setInt(const std::string& key, int value)
wester committed
67 68 69 70
{
    setParam(*this, key, value);
}

wester committed
71
void IndexParams::setDouble(const std::string& key, double value)
wester committed
72 73 74 75
{
    setParam(*this, key, value);
}

wester committed
76
void IndexParams::setFloat(const std::string& key, float value)
wester committed
77 78 79 80
{
    setParam(*this, key, value);
}

wester committed
81
void IndexParams::setBool(const std::string& key, bool value)
wester committed
82 83 84 85 86 87 88 89 90
{
    setParam(*this, key, value);
}

void IndexParams::setAlgorithm(int value)
{
    setParam(*this, "algorithm", (cvflann::flann_algorithm_t)value);
}

wester committed
91
void IndexParams::getAll(std::vector<std::string>& names,
wester committed
92
            std::vector<int>& types,
wester committed
93
            std::vector<std::string>& strValues,
wester committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
            std::vector<double>& numValues) const
{
    names.clear();
    types.clear();
    strValues.clear();
    numValues.clear();

    ::cvflann::IndexParams& p = get_params(*this);
    ::cvflann::IndexParams::const_iterator it = p.begin(), it_end = p.end();

    for( ; it != it_end; ++it )
    {
        names.push_back(it->first);
        try
        {
wester committed
109
            std::string val = it->second.cast<std::string>();
wester committed
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
            types.push_back(CV_USRTYPE1);
            strValues.push_back(val);
            numValues.push_back(-1);
        continue;
        }
        catch (...) {}

        strValues.push_back(it->second.type().name());

        try
        {
            double val = it->second.cast<double>();
            types.push_back( CV_64F );
            numValues.push_back(val);
        continue;
        }
        catch (...) {}
        try
        {
            float val = it->second.cast<float>();
            types.push_back( CV_32F );
            numValues.push_back(val);
        continue;
        }
        catch (...) {}
        try
        {
            int val = it->second.cast<int>();
            types.push_back( CV_32S );
            numValues.push_back(val);
        continue;
        }
        catch (...) {}
        try
        {
            short val = it->second.cast<short>();
            types.push_back( CV_16S );
            numValues.push_back(val);
        continue;
        }
        catch (...) {}
        try
        {
            ushort val = it->second.cast<ushort>();
            types.push_back( CV_16U );
            numValues.push_back(val);
        continue;
        }
        catch (...) {}
        try
        {
            char val = it->second.cast<char>();
            types.push_back( CV_8S );
            numValues.push_back(val);
        continue;
        }
        catch (...) {}
        try
        {
            uchar val = it->second.cast<uchar>();
            types.push_back( CV_8U );
            numValues.push_back(val);
        continue;
        }
        catch (...) {}
        try
        {
            bool val = it->second.cast<bool>();
            types.push_back( CV_MAKETYPE(CV_USRTYPE1,2) );
            numValues.push_back(val);
        continue;
        }
        catch (...) {}
        try
        {
            cvflann::flann_algorithm_t val = it->second.cast<cvflann::flann_algorithm_t>();
            types.push_back( CV_MAKETYPE(CV_USRTYPE1,3) );
            numValues.push_back(val);
        continue;
        }
        catch (...) {}


        types.push_back(-1); // unknown type
        numValues.push_back(-1);
    }
}


KDTreeIndexParams::KDTreeIndexParams(int trees)
{
    ::cvflann::IndexParams& p = get_params(*this);
    p["algorithm"] = FLANN_INDEX_KDTREE;
    p["trees"] = trees;
}

LinearIndexParams::LinearIndexParams()
{
    ::cvflann::IndexParams& p = get_params(*this);
    p["algorithm"] = FLANN_INDEX_LINEAR;
}

CompositeIndexParams::CompositeIndexParams(int trees, int branching, int iterations,
                             flann_centers_init_t centers_init, float cb_index )
{
    ::cvflann::IndexParams& p = get_params(*this);
    p["algorithm"] = FLANN_INDEX_KMEANS;
    // number of randomized trees to use (for kdtree)
    p["trees"] = trees;
    // branching factor
    p["branching"] = branching;
    // max iterations to perform in one kmeans clustering (kmeans tree)
    p["iterations"] = iterations;
    // algorithm used for picking the initial cluster centers for kmeans tree
    p["centers_init"] = centers_init;
    // cluster boundary index. Used when searching the kmeans tree
    p["cb_index"] = cb_index;
}

AutotunedIndexParams::AutotunedIndexParams(float target_precision, float build_weight,
                                           float memory_weight, float sample_fraction)
{
    ::cvflann::IndexParams& p = get_params(*this);
    p["algorithm"] = FLANN_INDEX_AUTOTUNED;
    // precision desired (used for autotuning, -1 otherwise)
    p["target_precision"] = target_precision;
    // build tree time weighting factor
    p["build_weight"] = build_weight;
    // index memory weighting factor
    p["memory_weight"] = memory_weight;
    // what fraction of the dataset to use for autotuning
    p["sample_fraction"] = sample_fraction;
}


KMeansIndexParams::KMeansIndexParams(int branching, int iterations,
                  flann_centers_init_t centers_init, float cb_index )
{
    ::cvflann::IndexParams& p = get_params(*this);
    p["algorithm"] = FLANN_INDEX_KMEANS;
    // branching factor
    p["branching"] = branching;
    // max iterations to perform in one kmeans clustering (kmeans tree)
    p["iterations"] = iterations;
    // algorithm used for picking the initial cluster centers for kmeans tree
    p["centers_init"] = centers_init;
    // cluster boundary index. Used when searching the kmeans tree
    p["cb_index"] = cb_index;
}

HierarchicalClusteringIndexParams::HierarchicalClusteringIndexParams(int branching ,
                                      flann_centers_init_t centers_init,
                                      int trees, int leaf_size)
{
    ::cvflann::IndexParams& p = get_params(*this);
    p["algorithm"] = FLANN_INDEX_HIERARCHICAL;
    // The branching factor used in the hierarchical clustering
    p["branching"] = branching;
    // Algorithm used for picking the initial cluster centers
    p["centers_init"] = centers_init;
    // number of parallel trees to build
    p["trees"] = trees;
    // maximum leaf size
    p["leaf_size"] = leaf_size;
}

LshIndexParams::LshIndexParams(int table_number, int key_size, int multi_probe_level)
{
    ::cvflann::IndexParams& p = get_params(*this);
    p["algorithm"] = FLANN_INDEX_LSH;
    // The number of hash tables to use
    p["table_number"] = table_number;
    // The length of the key in the hash tables
    p["key_size"] = key_size;
    // Number of levels to use in multi-probe (0 for standard LSH)
    p["multi_probe_level"] = multi_probe_level;
}

wester committed
288
SavedIndexParams::SavedIndexParams(const std::string& _filename)
wester committed
289
{
wester committed
290
    std::string filename = _filename;
wester committed
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    ::cvflann::IndexParams& p = get_params(*this);

    p["algorithm"] = FLANN_INDEX_SAVED;
    p["filename"] = filename;
}

SearchParams::SearchParams( int checks, float eps, bool sorted )
{
    ::cvflann::IndexParams& p = get_params(*this);

    // how many leafs to visit when searching for neighbours (-1 for unlimited)
    p["checks"] = checks;
    // search for eps-approximate neighbours (default: 0)
    p["eps"] = eps;
    // only for radius search, require neighbours sorted by distance (default: true)
    p["sorted"] = sorted;
}


template<typename Distance, typename IndexType> void
wester committed
311
buildIndex_(void*& index, const Mat& wholedata, const Mat& data, const IndexParams& params, const Distance& dist = Distance())
wester committed
312 313 314
{
    typedef typename Distance::ElementType ElementType;
    if(DataType<ElementType>::type != data.type())
wester committed
315
        CV_Error_(CV_StsUnsupportedFormat, ("type=%d\n", data.type()));
wester committed
316
    if(!data.isContinuous())
wester committed
317
        CV_Error(CV_StsBadArg, "Only continuous arrays are supported");
wester committed
318 319

    ::cvflann::Matrix<ElementType> dataset((ElementType*)data.data, data.rows, data.cols);
wester committed
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

    // currently, additional index support is the lsh algorithm only.
    if( !index || getParam<flann_algorithm_t>(params, "algorithm", FLANN_INDEX_LINEAR) != FLANN_INDEX_LSH)
    {
        Ptr<IndexType> _index = makePtr<IndexType>(dataset, get_params(params), dist);
        _index->buildIndex();
        index = _index;
        // HACK to prevent object destruction
        _index.obj = NULL;
    }
    else // build additional lsh index
    {
        ::cvflann::Matrix<ElementType> wholedataset((ElementType*)wholedata.data, wholedata.rows, wholedata.cols);
        ((IndexType*)index)->addIndex(wholedataset, dataset);
    }
wester committed
335 336 337
}

template<typename Distance> void
wester committed
338
buildIndex(void*& index, const Mat& wholedata, const Mat& data, const IndexParams& params, const Distance& dist = Distance())
wester committed
339
{
wester committed
340
    buildIndex_<Distance, ::cvflann::Index<Distance> >(index, wholedata, data, params, dist);
wester committed
341 342 343 344 345
}

#if CV_NEON
typedef ::cvflann::Hamming<uchar> HammingDistance;
#else
wester committed
346
typedef ::cvflann::HammingLUT2 HammingDistance;
wester committed
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
#endif

Index::Index()
{
    index = 0;
    featureType = CV_32F;
    algo = FLANN_INDEX_LINEAR;
    distType = FLANN_DIST_L2;
}

Index::Index(InputArray _data, const IndexParams& params, flann_distance_t _distType)
{
    index = 0;
    featureType = CV_32F;
    algo = FLANN_INDEX_LINEAR;
    distType = FLANN_DIST_L2;
wester committed
363
    build(_data, _data, params, _distType);
wester committed
364 365
}

wester committed
366
void Index::build(InputArray _wholedata, InputArray _data, const IndexParams& params, flann_distance_t _distType)
wester committed
367 368
{
    algo = getParam<flann_algorithm_t>(params, "algorithm", FLANN_INDEX_LINEAR);
wester committed
369 370 371 372 373 374

    if (algo != FLANN_INDEX_LSH)    // do not release if algo == FLANN_INDEX_LSH
    {
        release();
    }
    if (algo == FLANN_INDEX_SAVED)
wester committed
375
    {
wester committed
376
        load(_data, getParam<std::string>(params, "filename", std::string()));
wester committed
377 378 379 380
        return;
    }

    Mat data = _data.getMat();
wester committed
381 382 383 384
    if (algo != FLANN_INDEX_LSH)    // do not clear if algo == FLANN_INDEX_LSH
    {
        index = 0;
    }
wester committed
385 386 387 388 389 390 391 392 393 394 395
    featureType = data.type();
    distType = _distType;

    if ( algo == FLANN_INDEX_LSH)
    {
        distType = FLANN_DIST_HAMMING;
    }

    switch( distType )
    {
    case FLANN_DIST_HAMMING:
wester committed
396
        buildIndex< HammingDistance >(index, _wholedata.getMat(), data, params);
wester committed
397 398
        break;
    case FLANN_DIST_L2:
wester committed
399
        buildIndex< ::cvflann::L2<float> >(index, _wholedata.getMat(), data, params);
wester committed
400 401
        break;
    case FLANN_DIST_L1:
wester committed
402
        buildIndex< ::cvflann::L1<float> >(index, _wholedata.getMat(), data, params);
wester committed
403 404 405
        break;
#if MINIFLANN_SUPPORT_EXOTIC_DISTANCE_TYPES
    case FLANN_DIST_MAX:
wester committed
406
        buildIndex< ::cvflann::MaxDistance<float> >(index, _wholedata.getMat(), data, params);
wester committed
407 408
        break;
    case FLANN_DIST_HIST_INTERSECT:
wester committed
409
        buildIndex< ::cvflann::HistIntersectionDistance<float> >(index, _wholedata.getMat(), data, params);
wester committed
410 411
        break;
    case FLANN_DIST_HELLINGER:
wester committed
412
        buildIndex< ::cvflann::HellingerDistance<float> >(index, _wholedata.getMat(), data, params);
wester committed
413 414
        break;
    case FLANN_DIST_CHI_SQUARE:
wester committed
415
        buildIndex< ::cvflann::ChiSquareDistance<float> >(index, _wholedata.getMat(), data, params);
wester committed
416 417
        break;
    case FLANN_DIST_KL:
wester committed
418
        buildIndex< ::cvflann::KL_Divergence<float> >(index, _wholedata.getMat(), data, params);
wester committed
419 420 421
        break;
#endif
    default:
wester committed
422
        CV_Error(CV_StsBadArg, "Unknown/unsupported distance type");
wester committed
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
    }
}

template<typename IndexType> void deleteIndex_(void* index)
{
    delete (IndexType*)index;
}

template<typename Distance> void deleteIndex(void* index)
{
    deleteIndex_< ::cvflann::Index<Distance> >(index);
}

Index::~Index()
{
    release();
}

void Index::release()
{
    if( !index )
        return;

    switch( distType )
    {
        case FLANN_DIST_HAMMING:
            deleteIndex< HammingDistance >(index);
            break;
        case FLANN_DIST_L2:
            deleteIndex< ::cvflann::L2<float> >(index);
            break;
        case FLANN_DIST_L1:
            deleteIndex< ::cvflann::L1<float> >(index);
            break;
#if MINIFLANN_SUPPORT_EXOTIC_DISTANCE_TYPES
        case FLANN_DIST_MAX:
            deleteIndex< ::cvflann::MaxDistance<float> >(index);
            break;
        case FLANN_DIST_HIST_INTERSECT:
            deleteIndex< ::cvflann::HistIntersectionDistance<float> >(index);
            break;
        case FLANN_DIST_HELLINGER:
            deleteIndex< ::cvflann::HellingerDistance<float> >(index);
            break;
        case FLANN_DIST_CHI_SQUARE:
            deleteIndex< ::cvflann::ChiSquareDistance<float> >(index);
            break;
        case FLANN_DIST_KL:
            deleteIndex< ::cvflann::KL_Divergence<float> >(index);
            break;
#endif
        default:
wester committed
475
            CV_Error(CV_StsBadArg, "Unknown/unsupported distance type");
wester committed
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
    }
    index = 0;
}

template<typename Distance, typename IndexType>
void runKnnSearch_(void* index, const Mat& query, Mat& indices, Mat& dists,
                  int knn, const SearchParams& params)
{
    typedef typename Distance::ElementType ElementType;
    typedef typename Distance::ResultType DistanceType;
    int type = DataType<ElementType>::type;
    int dtype = DataType<DistanceType>::type;
    CV_Assert(query.type() == type && indices.type() == CV_32S && dists.type() == dtype);
    CV_Assert(query.isContinuous() && indices.isContinuous() && dists.isContinuous());

    ::cvflann::Matrix<ElementType> _query((ElementType*)query.data, query.rows, query.cols);
wester committed
492 493
    ::cvflann::Matrix<int> _indices((int*)indices.data, indices.rows, indices.cols);
    ::cvflann::Matrix<DistanceType> _dists((DistanceType*)dists.data, dists.rows, dists.cols);
wester committed
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517

    ((IndexType*)index)->knnSearch(_query, _indices, _dists, knn,
                                   (const ::cvflann::SearchParams&)get_params(params));
}

template<typename Distance>
void runKnnSearch(void* index, const Mat& query, Mat& indices, Mat& dists,
                  int knn, const SearchParams& params)
{
    runKnnSearch_<Distance, ::cvflann::Index<Distance> >(index, query, indices, dists, knn, params);
}

template<typename Distance, typename IndexType>
int runRadiusSearch_(void* index, const Mat& query, Mat& indices, Mat& dists,
                    double radius, const SearchParams& params)
{
    typedef typename Distance::ElementType ElementType;
    typedef typename Distance::ResultType DistanceType;
    int type = DataType<ElementType>::type;
    int dtype = DataType<DistanceType>::type;
    CV_Assert(query.type() == type && indices.type() == CV_32S && dists.type() == dtype);
    CV_Assert(query.isContinuous() && indices.isContinuous() && dists.isContinuous());

    ::cvflann::Matrix<ElementType> _query((ElementType*)query.data, query.rows, query.cols);
wester committed
518 519
    ::cvflann::Matrix<int> _indices((int*)indices.data, indices.rows, indices.cols);
    ::cvflann::Matrix<DistanceType> _dists((DistanceType*)dists.data, dists.rows, dists.cols);
wester committed
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606

    return ((IndexType*)index)->radiusSearch(_query, _indices, _dists,
                                            saturate_cast<float>(radius),
                                            (const ::cvflann::SearchParams&)get_params(params));
}

template<typename Distance>
int runRadiusSearch(void* index, const Mat& query, Mat& indices, Mat& dists,
                     double radius, const SearchParams& params)
{
    return runRadiusSearch_<Distance, ::cvflann::Index<Distance> >(index, query, indices, dists, radius, params);
}


static void createIndicesDists(OutputArray _indices, OutputArray _dists,
                               Mat& indices, Mat& dists, int rows,
                               int minCols, int maxCols, int dtype)
{
    if( _indices.needed() )
    {
        indices = _indices.getMat();
        if( !indices.isContinuous() || indices.type() != CV_32S ||
            indices.rows != rows || indices.cols < minCols || indices.cols > maxCols )
        {
            if( !indices.isContinuous() )
               _indices.release();
            _indices.create( rows, minCols, CV_32S );
            indices = _indices.getMat();
        }
    }
    else
        indices.create( rows, minCols, CV_32S );

    if( _dists.needed() )
    {
        dists = _dists.getMat();
        if( !dists.isContinuous() || dists.type() != dtype ||
           dists.rows != rows || dists.cols < minCols || dists.cols > maxCols )
        {
            if( !indices.isContinuous() )
                _dists.release();
            _dists.create( rows, minCols, dtype );
            dists = _dists.getMat();
        }
    }
    else
        dists.create( rows, minCols, dtype );
}


void Index::knnSearch(InputArray _query, OutputArray _indices,
               OutputArray _dists, int knn, const SearchParams& params)
{
    Mat query = _query.getMat(), indices, dists;
    int dtype = distType == FLANN_DIST_HAMMING ? CV_32S : CV_32F;

    createIndicesDists( _indices, _dists, indices, dists, query.rows, knn, knn, dtype );

    switch( distType )
    {
    case FLANN_DIST_HAMMING:
        runKnnSearch<HammingDistance>(index, query, indices, dists, knn, params);
        break;
    case FLANN_DIST_L2:
        runKnnSearch< ::cvflann::L2<float> >(index, query, indices, dists, knn, params);
        break;
    case FLANN_DIST_L1:
        runKnnSearch< ::cvflann::L1<float> >(index, query, indices, dists, knn, params);
        break;
#if MINIFLANN_SUPPORT_EXOTIC_DISTANCE_TYPES
    case FLANN_DIST_MAX:
        runKnnSearch< ::cvflann::MaxDistance<float> >(index, query, indices, dists, knn, params);
        break;
    case FLANN_DIST_HIST_INTERSECT:
        runKnnSearch< ::cvflann::HistIntersectionDistance<float> >(index, query, indices, dists, knn, params);
        break;
    case FLANN_DIST_HELLINGER:
        runKnnSearch< ::cvflann::HellingerDistance<float> >(index, query, indices, dists, knn, params);
        break;
    case FLANN_DIST_CHI_SQUARE:
        runKnnSearch< ::cvflann::ChiSquareDistance<float> >(index, query, indices, dists, knn, params);
        break;
    case FLANN_DIST_KL:
        runKnnSearch< ::cvflann::KL_Divergence<float> >(index, query, indices, dists, knn, params);
        break;
#endif
    default:
wester committed
607
        CV_Error(CV_StsBadArg, "Unknown/unsupported distance type");
wester committed
608 609 610 611 612 613 614 615 616 617 618 619 620
    }
}

int Index::radiusSearch(InputArray _query, OutputArray _indices,
                        OutputArray _dists, double radius, int maxResults,
                        const SearchParams& params)
{
    Mat query = _query.getMat(), indices, dists;
    int dtype = distType == FLANN_DIST_HAMMING ? CV_32S : CV_32F;
    CV_Assert( maxResults > 0 );
    createIndicesDists( _indices, _dists, indices, dists, query.rows, maxResults, INT_MAX, dtype );

    if( algo == FLANN_INDEX_LSH )
wester committed
621
        CV_Error( CV_StsNotImplemented, "LSH index does not support radiusSearch operation" );
wester committed
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644

    switch( distType )
    {
    case FLANN_DIST_HAMMING:
        return runRadiusSearch< HammingDistance >(index, query, indices, dists, radius, params);

    case FLANN_DIST_L2:
        return runRadiusSearch< ::cvflann::L2<float> >(index, query, indices, dists, radius, params);
    case FLANN_DIST_L1:
        return runRadiusSearch< ::cvflann::L1<float> >(index, query, indices, dists, radius, params);
#if MINIFLANN_SUPPORT_EXOTIC_DISTANCE_TYPES
    case FLANN_DIST_MAX:
        return runRadiusSearch< ::cvflann::MaxDistance<float> >(index, query, indices, dists, radius, params);
    case FLANN_DIST_HIST_INTERSECT:
        return runRadiusSearch< ::cvflann::HistIntersectionDistance<float> >(index, query, indices, dists, radius, params);
    case FLANN_DIST_HELLINGER:
        return runRadiusSearch< ::cvflann::HellingerDistance<float> >(index, query, indices, dists, radius, params);
    case FLANN_DIST_CHI_SQUARE:
        return runRadiusSearch< ::cvflann::ChiSquareDistance<float> >(index, query, indices, dists, radius, params);
    case FLANN_DIST_KL:
        return runRadiusSearch< ::cvflann::KL_Divergence<float> >(index, query, indices, dists, radius, params);
#endif
    default:
wester committed
645
        CV_Error(CV_StsBadArg, "Unknown/unsupported distance type");
wester committed
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
    }
    return -1;
}

flann_distance_t Index::getDistance() const
{
    return distType;
}

flann_algorithm_t Index::getAlgorithm() const
{
    return algo;
}

template<typename IndexType> void saveIndex_(const Index* index0, const void* index, FILE* fout)
{
    IndexType* _index = (IndexType*)index;
    ::cvflann::save_header(fout, *_index);
    // some compilers may store short enumerations as bytes,
    // so make sure we always write integers (which are 4-byte values in any modern C compiler)
    int idistType = (int)index0->getDistance();
    ::cvflann::save_value<int>(fout, idistType);
    _index->saveIndex(fout);
}

template<typename Distance> void saveIndex(const Index* index0, const void* index, FILE* fout)
{
    saveIndex_< ::cvflann::Index<Distance> >(index0, index, fout);
}

wester committed
676
void Index::save(const std::string& filename) const
wester committed
677 678 679
{
    FILE* fout = fopen(filename.c_str(), "wb");
    if (fout == NULL)
wester committed
680
        CV_Error_( CV_StsError, ("Can not open file %s for writing FLANN index\n", filename.c_str()) );
wester committed
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712

    switch( distType )
    {
    case FLANN_DIST_HAMMING:
        saveIndex< HammingDistance >(this, index, fout);
        break;
    case FLANN_DIST_L2:
        saveIndex< ::cvflann::L2<float> >(this, index, fout);
        break;
    case FLANN_DIST_L1:
        saveIndex< ::cvflann::L1<float> >(this, index, fout);
        break;
#if MINIFLANN_SUPPORT_EXOTIC_DISTANCE_TYPES
    case FLANN_DIST_MAX:
        saveIndex< ::cvflann::MaxDistance<float> >(this, index, fout);
        break;
    case FLANN_DIST_HIST_INTERSECT:
        saveIndex< ::cvflann::HistIntersectionDistance<float> >(this, index, fout);
        break;
    case FLANN_DIST_HELLINGER:
        saveIndex< ::cvflann::HellingerDistance<float> >(this, index, fout);
        break;
    case FLANN_DIST_CHI_SQUARE:
        saveIndex< ::cvflann::ChiSquareDistance<float> >(this, index, fout);
        break;
    case FLANN_DIST_KL:
        saveIndex< ::cvflann::KL_Divergence<float> >(this, index, fout);
        break;
#endif
    default:
        fclose(fout);
        fout = 0;
wester committed
713
        CV_Error(CV_StsBadArg, "Unknown/unsupported distance type");
wester committed
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
    }
    if( fout )
        fclose(fout);
}


template<typename Distance, typename IndexType>
bool loadIndex_(Index* index0, void*& index, const Mat& data, FILE* fin, const Distance& dist=Distance())
{
    typedef typename Distance::ElementType ElementType;
    CV_Assert(DataType<ElementType>::type == data.type() && data.isContinuous());

    ::cvflann::Matrix<ElementType> dataset((ElementType*)data.data, data.rows, data.cols);

    ::cvflann::IndexParams params;
    params["algorithm"] = index0->getAlgorithm();
    IndexType* _index = new IndexType(dataset, params, dist);
    _index->loadIndex(fin);
    index = _index;
    return true;
}

template<typename Distance>
bool loadIndex(Index* index0, void*& index, const Mat& data, FILE* fin, const Distance& dist=Distance())
{
    return loadIndex_<Distance, ::cvflann::Index<Distance> >(index0, index, data, fin, dist);
}

wester committed
742
bool Index::load(InputArray _data, const std::string& filename)
wester committed
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
{
    Mat data = _data.getMat();
    bool ok = true;
    release();
    FILE* fin = fopen(filename.c_str(), "rb");
    if (fin == NULL)
        return false;

    ::cvflann::IndexHeader header = ::cvflann::load_header(fin);
    algo = header.index_type;
    featureType = header.data_type == FLANN_UINT8 ? CV_8U :
                  header.data_type == FLANN_INT8 ? CV_8S :
                  header.data_type == FLANN_UINT16 ? CV_16U :
                  header.data_type == FLANN_INT16 ? CV_16S :
                  header.data_type == FLANN_INT32 ? CV_32S :
                  header.data_type == FLANN_FLOAT32 ? CV_32F :
                  header.data_type == FLANN_FLOAT64 ? CV_64F : -1;

    if( (int)header.rows != data.rows || (int)header.cols != data.cols ||
        featureType != data.type() )
    {
        fprintf(stderr, "Reading FLANN index error: the saved data size (%d, %d) or type (%d) is different from the passed one (%d, %d), %d\n",
                (int)header.rows, (int)header.cols, featureType, data.rows, data.cols, data.type());
        fclose(fin);
        return false;
    }

    int idistType = 0;
    ::cvflann::load_value(fin, idistType);
    distType = (flann_distance_t)idistType;

    if( !((distType == FLANN_DIST_HAMMING && featureType == CV_8U) ||
          (distType != FLANN_DIST_HAMMING && featureType == CV_32F)) )
    {
        fprintf(stderr, "Reading FLANN index error: unsupported feature type %d for the index type %d\n", featureType, algo);
        fclose(fin);
        return false;
    }

    switch( distType )
    {
    case FLANN_DIST_HAMMING:
        loadIndex< HammingDistance >(this, index, data, fin);
        break;
    case FLANN_DIST_L2:
        loadIndex< ::cvflann::L2<float> >(this, index, data, fin);
        break;
    case FLANN_DIST_L1:
        loadIndex< ::cvflann::L1<float> >(this, index, data, fin);
        break;
#if MINIFLANN_SUPPORT_EXOTIC_DISTANCE_TYPES
    case FLANN_DIST_MAX:
        loadIndex< ::cvflann::MaxDistance<float> >(this, index, data, fin);
        break;
    case FLANN_DIST_HIST_INTERSECT:
        loadIndex< ::cvflann::HistIntersectionDistance<float> >(index, data, fin);
        break;
    case FLANN_DIST_HELLINGER:
        loadIndex< ::cvflann::HellingerDistance<float> >(this, index, data, fin);
        break;
    case FLANN_DIST_CHI_SQUARE:
        loadIndex< ::cvflann::ChiSquareDistance<float> >(this, index, data, fin);
        break;
    case FLANN_DIST_KL:
        loadIndex< ::cvflann::KL_Divergence<float> >(this, index, data, fin);
        break;
#endif
    default:
        fprintf(stderr, "Reading FLANN index error: unsupported distance type %d\n", distType);
        ok = false;
    }

    if( fin )
        fclose(fin);
    return ok;
}

}

}