Updated FLANN to version 1.5
authorMarius Muja <no@email>
Tue, 12 Oct 2010 19:47:50 +0000 (19:47 +0000)
committerMarius Muja <no@email>
Tue, 12 Oct 2010 19:47:50 +0000 (19:47 +0000)
62 files changed:
3rdparty/CMakeLists.txt
3rdparty/flann/CMakeLists.txt [deleted file]
3rdparty/flann/common.h [deleted file]
3rdparty/flann/dist.cpp [deleted file]
3rdparty/flann/flann.cpp [deleted file]
3rdparty/flann/flann.h [deleted file]
3rdparty/flann/flann.hpp [deleted file]
3rdparty/flann/index_testing.h [deleted file]
3rdparty/flann/logger.cpp [deleted file]
3rdparty/flann/matrix.h [deleted file]
3rdparty/flann/random.cpp [deleted file]
3rdparty/flann/random.h [deleted file]
3rdparty/flann/saving.cpp [deleted file]
3rdparty/include/flann/common.h [deleted file]
3rdparty/include/flann/constants.h [deleted file]
3rdparty/include/flann/flann.h [deleted file]
3rdparty/include/flann/flann.hpp [deleted file]
3rdparty/include/flann/matrix.h [deleted file]
doc/cxcore_clustering_search.tex
include/opencv/cv.h
modules/CMakeLists.txt
modules/contrib/CMakeLists.txt
modules/core/CMakeLists.txt
modules/core/include/opencv2/core/core.hpp
modules/core/include/opencv2/core/flann.hpp [deleted file]
modules/core/src/flann.cpp [deleted file]
modules/features2d/CMakeLists.txt
modules/features2d/include/opencv2/features2d/features2d.hpp
modules/flann/CMakeLists.txt [new file with mode: 0644]
modules/flann/include/opencv2/flann/all_indices.h [moved from 3rdparty/flann/saving.h with 58% similarity]
modules/flann/include/opencv2/flann/allocator.h [moved from 3rdparty/flann/allocator.h with 97% similarity]
modules/flann/include/opencv2/flann/autotuned_index.h [moved from 3rdparty/flann/autotuned_index.h with 73% similarity]
modules/flann/include/opencv2/flann/composite_index.h [moved from 3rdparty/flann/composite_index.h with 51% similarity]
modules/flann/include/opencv2/flann/dist.h [moved from 3rdparty/flann/dist.h with 56% similarity]
modules/flann/include/opencv2/flann/flann.hpp [new file with mode: 0644]
modules/flann/include/opencv2/flann/flann_base.hpp [new file with mode: 0644]
modules/flann/include/opencv2/flann/general.h [moved from 3rdparty/flann/constants.h with 58% similarity]
modules/flann/include/opencv2/flann/ground_truth.h [moved from 3rdparty/flann/ground_truth.h with 94% similarity]
modules/flann/include/opencv2/flann/hdf5.h [new file with mode: 0644]
modules/flann/include/opencv2/flann/heap.h [moved from 3rdparty/flann/heap.h with 99% similarity]
modules/flann/include/opencv2/flann/index_testing.h [moved from 3rdparty/flann/index_testing.cpp with 74% similarity]
modules/flann/include/opencv2/flann/kdtree_index.h [moved from 3rdparty/flann/kdtree_index.h with 75% similarity]
modules/flann/include/opencv2/flann/kmeans_index.h [moved from 3rdparty/flann/kmeans_index.h with 66% similarity]
modules/flann/include/opencv2/flann/linear_index.h [moved from 3rdparty/flann/linear_index.h with 67% similarity]
modules/flann/include/opencv2/flann/logger.h [moved from 3rdparty/flann/logger.h with 97% similarity]
modules/flann/include/opencv2/flann/matrix.h [new file with mode: 0644]
modules/flann/include/opencv2/flann/nn_index.h [moved from 3rdparty/flann/nn_index.h with 81% similarity]
modules/flann/include/opencv2/flann/object_factory.h [moved from 3rdparty/flann/object_factory.h with 99% similarity]
modules/flann/include/opencv2/flann/random.h [moved from 3rdparty/include/flann/random.h with 99% similarity]
modules/flann/include/opencv2/flann/result_set.h [moved from 3rdparty/flann/result_set.h with 82% similarity]
modules/flann/include/opencv2/flann/sampling.h [new file with mode: 0644]
modules/flann/include/opencv2/flann/saving.h [new file with mode: 0644]
modules/flann/include/opencv2/flann/simplex_downhill.h [moved from 3rdparty/flann/simplex_downhill.h with 99% similarity]
modules/flann/include/opencv2/flann/timer.h [moved from 3rdparty/flann/timer.h with 99% similarity]
modules/flann/src/flann.cpp [new file with mode: 0644]
modules/flann/src/precomp.hpp [new file with mode: 0644]
modules/haartraining/CMakeLists.txt
modules/legacy/CMakeLists.txt
modules/python/CMakeLists.txt
modules/traincascade/CMakeLists.txt
tests/cv/CMakeLists.txt
tests/gpu/CMakeLists.txt

index d06040d..d014172 100644 (file)
@@ -2,7 +2,6 @@ if(ANDROID)
  configure_file("${CMAKE_SOURCE_DIR}/Android.mk.modules.in" "${CMAKE_CURRENT_BINARY_DIR}/Android.mk")
 endif()
 
-add_subdirectory(flann)
 add_subdirectory(lapack)
 add_subdirectory(zlib)
 if(WITH_JASPER AND NOT JASPER_FOUND)
diff --git a/3rdparty/flann/CMakeLists.txt b/3rdparty/flann/CMakeLists.txt
deleted file mode 100644 (file)
index f4bb688..0000000
+++ /dev/null
@@ -1,107 +0,0 @@
-if(ANDROID)
-file(GLOB_RECURSE flann_sources_cpp *.cpp)
-define_android_manual(flann "${flann_sources_cpp}" "$(LOCAL_PATH)/../include $(LOCAL_PATH)/../include/flann")          
-else(ANDROID)
-if (DEFINED OPENCV_VERSION)
-
-# ----------------------------------------------------------------------------
-#  CMake file for libflann. See root CMakeLists.txt
-#
-# ----------------------------------------------------------------------------
-project(flann)
-
-# List of C++ files:
-
-#set(CMAKE_BUILD_TYPE Debug)
-
-include_directories(
-   ${CMAKE_CURRENT_SOURCE_DIR}
-   "${CMAKE_CURRENT_SOURCE_DIR}/../include/flann"
-   )
-
-# The .cpp files:
-file(GLOB flann_sources *.cpp *.h *.hpp)
-file(GLOB flann_h "${CMAKE_CURRENT_SOURCE_DIR}/../include/flann/*.h" "${CMAKE_CURRENT_SOURCE_DIR}/../include/flann/*.hpp")
-
-source_group("Src" FILES ${flann_sources})
-source_group("Include" FILES ${flann_h})
-
-set(flann_sources ${flann_sources} ${flann_h})
-
-# ----------------------------------------------------------------------------------
-#           Define the library target:
-# ----------------------------------------------------------------------------------
-
-set(the_target "flann")
-
-add_library(${the_target} STATIC ${flann_sources})
-add_definitions(-Dflann_EXPORTS)
-
-if(MSVC)
-    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /W3")
-    add_definitions(-DJAS_WIN_MSVC_BUILD)
-endif()
-
-if(UNIX)
-  if(CMAKE_COMPILER_IS_GNUCXX OR CV_ICC)
-     set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC")
-     set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
-  endif()
-endif()
-
-set_target_properties(${the_target}
-   PROPERTIES
-   OUTPUT_NAME "${the_target}"
-   DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}"
-   ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/3rdparty/lib"
-   )
-
-ELSE()
-
-INCLUDE_DIRECTORIES(algorithms util nn .)
-
-ADD_SUBDIRECTORY( tests )
-
-file(GLOB_RECURSE SOURCES *.cpp)
-#SET(SOURCES flann.cpp util/Random.cpp nn/Testing.cpp algorithms/NNIndex.cpp algorithms/dist.cpp util/Logger.cpp util/Saving.cpp)
-
-ADD_LIBRARY(flann ${SOURCES})
-#ADD_LIBRARY(flann SHARED ${SOURCES})   #JL: Why the two versions??
-#ADD_LIBRARY(flann_s STATIC ${SOURCES})
-
-IF(WIN32)
-INSTALL (
-    TARGETS flann
-    RUNTIME DESTINATION matlab 
-)
-INSTALL (
-    TARGETS flann
-    RUNTIME DESTINATION python/pyflann/bindings
-)
-ELSE(WIN32)
-INSTALL (
-    TARGETS flann
-    LIBRARY DESTINATION python/pyflann/bindings
-)
-ENDIF(WIN32)
-
-INSTALL (
-    TARGETS flann  # flann_s
-    RUNTIME DESTINATION bin
-    LIBRARY DESTINATION lib
-    ARCHIVE DESTINATION lib
-)
-
-# INSTALL (
-#     TARGETS flann flann_s
-#     ARCHIVE DESTINATION ${PROJECT_SOURCE_DIR}/python
-#     LIBRARY DESTINATION ${PROJECT_SOURCE_DIR}/python
-# )
-
-INSTALL (
-    FILES flann.h constants.h
-    DESTINATION include
-)
-
-ENDIF()
-endif(ANDROID)#android
diff --git a/3rdparty/flann/common.h b/3rdparty/flann/common.h
deleted file mode 100644 (file)
index e5f9ed0..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-/***********************************************************************
- * Software License Agreement (BSD License)
- *
- * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
- * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
- *
- * THE BSD LICENSE
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *************************************************************************/
-
-#ifndef COMMOM_H
-#define COMMOM_H
-
-
-#define ARRAY_LEN(a) (sizeof(a)/sizeof(a[0]))
-
-#include <stdexcept>
-
-namespace cvflann
-{
-class FLANNException : public std::runtime_error {
- public:
-   FLANNException(const char* message) : std::runtime_error(message) { }
- };
-
-}
-
-#endif //COMMOM_H
diff --git a/3rdparty/flann/dist.cpp b/3rdparty/flann/dist.cpp
deleted file mode 100644 (file)
index c72cf20..0000000
+++ /dev/null
@@ -1,51 +0,0 @@
-/***********************************************************************
- * Software License Agreement (BSD License)
- *
- * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
- * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
- *
- * THE BSD LICENSE
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *************************************************************************/
-
-#include "dist.h"
-
-namespace cvflann
-{
-
-/** Global variable indicating the distance metric
- * to be used.
- */
-flann_distance_t flann_distance_type = EUCLIDEAN;
-
-/**
- * Zero iterator that emulates a zero feature.
- */
-ZeroIterator<float> zero;
-
-/**
- * Order of Minkowski distance to use.
- */
-int flann_minkowski_order;
-
-}
diff --git a/3rdparty/flann/flann.cpp b/3rdparty/flann/flann.cpp
deleted file mode 100644 (file)
index 7297eac..0000000
+++ /dev/null
@@ -1,476 +0,0 @@
-/***********************************************************************
- * Software License Agreement (BSD License)
- *
- * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
- * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
- *
- * THE BSD LICENSE
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *************************************************************************/
-
-#include <stdexcept>
-#include <vector>
-#include "flann.h"
-#include "timer.h"
-#include "common.h"
-#include "logger.h"
-#include "index_testing.h"
-#include "saving.h"
-#include "object_factory.h"
-// index types
-#include "kdtree_index.h"
-#include "kmeans_index.h"
-#include "composite_index.h"
-#include "linear_index.h"
-#include "autotuned_index.h"
-
-#include <typeinfo>
-using namespace std;
-
-
-
-#include "flann.h"
-
-#ifdef WIN32
-#define EXPORTED extern "C" __declspec(dllexport)
-#else
-#define EXPORTED extern "C"
-#endif
-
-
-namespace cvflann
-{
-
-typedef ObjectFactory<IndexParams, flann_algorithm_t> ParamsFactory;
-
-
-IndexParams* IndexParams::createFromParameters(const FLANNParameters& p)
-{
-       IndexParams* params = ParamsFactory::instance().create(p.algorithm);
-       params->fromParameters(p);
-
-       return params;
-}
-
-NNIndex* LinearIndexParams::createIndex(const Matrix<float>& dataset) const
-{
-       return new LinearIndex(dataset, *this);
-}
-
-
-NNIndex* KDTreeIndexParams::createIndex(const Matrix<float>& dataset) const
-{
-       return new KDTreeIndex(dataset, *this);
-}
-
-NNIndex* KMeansIndexParams::createIndex(const Matrix<float>& dataset) const
-{
-       return new KMeansIndex(dataset, *this);
-}
-
-
-NNIndex* CompositeIndexParams::createIndex(const Matrix<float>& dataset) const
-{
-       return new CompositeIndex(dataset, *this);
-}
-
-
-NNIndex* AutotunedIndexParams::createIndex(const Matrix<float>& dataset) const
-{
-       return new AutotunedIndex(dataset, *this);
-}
-
-
-NNIndex* SavedIndexParams::createIndex(const Matrix<float>& dataset) const
-{
-
-       FILE* fin = fopen(filename.c_str(), "rb");
-       if (fin==NULL) {
-               return NULL;
-       }
-       IndexHeader header = load_header(fin);
-       rewind(fin);
-       IndexParams* params = ParamsFactory::instance().create(header.index_type);
-       NNIndex* nnIndex =  params->createIndex(dataset);
-       nnIndex->loadIndex(fin);
-       fclose(fin);
-       delete params; //?
-
-       return nnIndex;
-
-}
-
-class StaticInit
-{
-public:
-       StaticInit()
-       {
-               ParamsFactory::instance().register_<LinearIndexParams>(LINEAR);
-               ParamsFactory::instance().register_<KDTreeIndexParams>(KDTREE);
-               ParamsFactory::instance().register_<KMeansIndexParams>(KMEANS);
-               ParamsFactory::instance().register_<CompositeIndexParams>(COMPOSITE);
-               ParamsFactory::instance().register_<AutotunedIndexParams>(AUTOTUNED);
-               ParamsFactory::instance().register_<SavedIndexParams>(SAVED);
-       }
-};
-StaticInit __init;
-
-
-
-Index::Index(const Matrix<float>& dataset, const IndexParams& params)
-{
-       nnIndex = params.createIndex(dataset);
-       nnIndex->buildIndex();
-}
-
-Index::~Index()
-{
-       delete nnIndex;
-}
-
-
-void Index::knnSearch(const Matrix<float>& queries, Matrix<int>& indices, Matrix<float>& dists, int knn, const SearchParams& searchParams)
-{
-       assert(queries.cols==nnIndex->veclen());
-       assert(indices.rows>=queries.rows);
-       assert(dists.rows>=queries.rows);
-       assert(indices.cols>=knn);
-       assert(dists.cols>=knn);
-
-
-    search_for_neighbors(*nnIndex, queries, indices, dists, searchParams);
-}
-
-int Index::radiusSearch(const Matrix<float>& query, Matrix<int> indices, Matrix<float> dists, float radius, const SearchParams& searchParams)
-{
-       if (query.rows!=1) {
-               printf("I can only search one feature at a time for range search\n");
-               return -1;
-       }
-       assert(query.cols==nnIndex->veclen());
-
-       RadiusResultSet resultSet(radius);
-       resultSet.init(query.data, query.cols);
-       nnIndex->findNeighbors(resultSet,query.data,searchParams);
-
-       // TODO: optimize here
-       int* neighbors = resultSet.getNeighbors();
-       float* distances = resultSet.getDistances();
-       int count_nn = min((long)resultSet.size(), indices.cols);
-
-       assert (dists.cols>=count_nn);
-
-       for (int i=0;i<count_nn;++i) {
-               indices[0][i] = neighbors[i];
-               dists[0][i] = distances[i];
-       }
-
-       return count_nn;
-}
-
-
-void Index::save(string filename)
-{
-       FILE* fout = fopen(filename.c_str(), "wb");
-       if (fout==NULL) {
-               logger.error("Cannot open file: %s", filename.c_str());
-               throw FLANNException("Cannot open file");
-       }
-       nnIndex->saveIndex(fout);
-       fclose(fout);
-}
-
-int Index::size() const
-{
-       return nnIndex->size();
-}
-
-int Index::veclen() const
-{
-       return nnIndex->veclen();
-}
-
-
-int hierarchicalClustering(const Matrix<float>& features, Matrix<float>& centers, const KMeansIndexParams& params)
-{
-    KMeansIndex kmeans(features, params);
-       kmeans.buildIndex();
-
-    int clusterNum = kmeans.getClusterCenters(centers);
-       return clusterNum;
-}
-
-} // namespace FLANN
-
-
-
-using namespace cvflann;
-
-typedef NNIndex* NNIndexPtr;
-typedef Matrix<float>* MatrixPtr;
-
-
-
-void init_flann_parameters(FLANNParameters* p)
-{
-       if (p != NULL) {
-               flann_log_verbosity(p->log_level);
-        if (p->random_seed>0) {
-                 seed_random(p->random_seed);
-        }
-       }
-}
-
-
-EXPORTED void flann_log_verbosity(int level)
-{
-    if (level>=0) {
-        logger.setLevel(level);
-    }
-}
-
-EXPORTED void flann_set_distance_type(flann_distance_t distance_type, int order)
-{
-       flann_distance_type = distance_type;
-       flann_minkowski_order = order;
-}
-
-
-EXPORTED flann_index_t flann_build_index(float* dataset, int rows, int cols, float* /*speedup*/, FLANNParameters* flann_params)
-{
-       try {
-               init_flann_parameters(flann_params);
-               if (flann_params == NULL) {
-                       throw FLANNException("The flann_params argument must be non-null");
-               }
-               IndexParams* params = IndexParams::createFromParameters(*flann_params);
-               Index* index = new Index(Matrix<float>(rows,cols,dataset), *params);
-
-               return index;
-       }
-       catch (runtime_error& e) {
-               logger.error("Caught exception: %s\n",e.what());
-               return NULL;
-       }
-}
-
-
-
-EXPORTED int flann_save_index(flann_index_t index_ptr, char* filename)
-{
-       try {
-               if (index_ptr==NULL) {
-                       throw FLANNException("Invalid index");
-               }
-
-               Index* index = (Index*)index_ptr;
-               index->save(filename);
-
-               return 0;
-       }
-       catch(runtime_error& e) {
-               logger.error("Caught exception: %s\n",e.what());
-               return -1;
-       }
-}
-
-
-EXPORTED FLANN_INDEX flann_load_index(char* filename, float* dataset, int rows, int cols)
-{
-       try {
-               Index* index = new Index(Matrix<float>(rows,cols,dataset), SavedIndexParams(filename));
-               return index;
-       }
-       catch(runtime_error& e) {
-               logger.error("Caught exception: %s\n",e.what());
-               return NULL;
-       }
-}
-
-
-
-EXPORTED int flann_find_nearest_neighbors(float* dataset,  int rows, int cols, float* testset, int tcount, int* result, float* dists, int nn, FLANNParameters* flann_params)
-{
-    int _result = 0;
-       try {
-               init_flann_parameters(flann_params);
-
-               IndexParams* params = IndexParams::createFromParameters(*flann_params);
-               Index* index = new Index(Matrix<float>(rows,cols,dataset), *params);
-               Matrix<int> m_indices(tcount, nn, result);
-               Matrix<float> m_dists(tcount, nn, dists);
-               index->knnSearch(Matrix<float>(tcount, index->veclen(), testset),
-                                               m_indices,
-                                               m_dists, nn, SearchParams(flann_params->checks) );
-       }
-       catch(runtime_error& e) {
-               logger.error("Caught exception: %s\n",e.what());
-        _result = -1;
-       }
-
-       return _result;
-}
-
-
-EXPORTED int flann_find_nearest_neighbors_index(flann_index_t index_ptr, float* testset, int tcount, int* result, float* dists, int nn, int checks, FLANNParameters* flann_params)
-{
-       try {
-               init_flann_parameters(flann_params);
-               if (index_ptr==NULL) {
-                       throw FLANNException("Invalid index");
-               }
-               Index* index = (Index*) index_ptr;
-
-               Matrix<int> m_indices(tcount, nn, result);
-               Matrix<float> m_dists(tcount, nn, dists);
-               index->knnSearch(Matrix<float>(tcount, index->veclen(), testset),
-                                               m_indices,
-                                               m_dists, nn, SearchParams(checks) );
-
-       }
-       catch(runtime_error& e) {
-               logger.error("Caught exception: %s\n",e.what());
-               return -1;
-       }
-
-       return -1;
-}
-
-
-EXPORTED int flann_radius_search(FLANN_INDEX index_ptr,
-                                                                               float* query,
-                                                                               int* indices,
-                                                                               float* dists,
-                                                                               int max_nn,
-                                                                               float radius,
-                                                                               int checks,
-                                                                               FLANNParameters* flann_params)
-{
-       try {
-               init_flann_parameters(flann_params);
-               if (index_ptr==NULL) {
-                       throw FLANNException("Invalid index");
-               }
-               Index* index = (Index*) index_ptr;
-
-               Matrix<int> m_indices(1, max_nn, indices);
-               Matrix<float> m_dists(1, max_nn, dists);
-               int count = index->radiusSearch(Matrix<float>(1, index->veclen(), query),
-                                               m_indices,
-                                               m_dists, radius, SearchParams(checks) );
-
-
-               return count;
-       }
-       catch(runtime_error& e) {
-               logger.error("Caught exception: %s\n",e.what());
-               return -1;
-       }
-
-}
-
-
-EXPORTED int flann_free_index(FLANN_INDEX index_ptr, FLANNParameters* flann_params)
-{
-       try {
-               init_flann_parameters(flann_params);
-        if (index_ptr==NULL) {
-            throw FLANNException("Invalid index");
-        }
-        Index* index = (Index*) index_ptr;
-        delete index;
-
-        return 0;
-       }
-       catch(runtime_error& e) {
-               logger.error("Caught exception: %s\n",e.what());
-        return -1;
-       }
-}
-
-
-EXPORTED int flann_compute_cluster_centers(float* dataset, int rows, int cols, int clusters, float* result, FLANNParameters* flann_params)
-{
-       try {
-               init_flann_parameters(flann_params);
-
-        MatrixPtr inputData = new Matrix<float>(rows,cols,dataset);
-        KMeansIndexParams params(flann_params->branching, flann_params->iterations, flann_params->centers_init, flann_params->cb_index);
-               Matrix<float> centers(clusters, cols, result);
-        int clusterNum = hierarchicalClustering(*inputData,centers, params);
-
-               return clusterNum;
-       } catch (runtime_error& e) {
-               logger.error("Caught exception: %s\n",e.what());
-               return -1;
-       }
-}
-
-
-EXPORTED void compute_ground_truth_float(float* dataset, int dshape[], float* testset, int tshape[], int* match, int mshape[], int skip)
-{
-    assert(dshape[1]==tshape[1]);
-    assert(tshape[0]==mshape[0]);
-
-    Matrix<int> _match(mshape[0], mshape[1], match);
-    compute_ground_truth(Matrix<float>(dshape[0], dshape[1], dataset), Matrix<float>(tshape[0], tshape[1], testset), _match, skip);
-}
-
-
-EXPORTED float test_with_precision(FLANN_INDEX index_ptr, float* dataset, int dshape[], float* testset, int tshape[], int* matches, int mshape[],
-             int nn, float precision, int* checks, int skip = 0)
-{
-    assert(dshape[1]==tshape[1]);
-    assert(tshape[0]==mshape[0]);
-
-    try {
-        if (index_ptr==NULL) {
-            throw FLANNException("Invalid index");
-        }
-        NNIndexPtr index = (NNIndexPtr)index_ptr;
-        return test_index_precision(*index, Matrix<float>(dshape[0], dshape[1],dataset), Matrix<float>(tshape[0], tshape[1], testset),
-                Matrix<int>(mshape[0],mshape[1],matches), precision, *checks, nn, skip);
-    } catch (runtime_error& e) {
-        logger.error("Caught exception: %s\n",e.what());
-        return -1;
-    }
-}
-
-EXPORTED float test_with_checks(FLANN_INDEX index_ptr, float* dataset, int dshape[], float* testset, int tshape[], int* matches, int mshape[],
-             int nn, int checks, float* precision, int skip = 0)
-{
-    assert(dshape[1]==tshape[1]);
-    assert(tshape[0]==mshape[0]);
-
-    try {
-        if (index_ptr==NULL) {
-            throw FLANNException("Invalid index");
-        }
-        NNIndexPtr index = (NNIndexPtr)index_ptr;
-        return test_index_checks(*index, Matrix<float>(dshape[0], dshape[1],dataset), Matrix<float>(tshape[0], tshape[1], testset),
-                Matrix<int>(mshape[0],mshape[1],matches), checks, *precision, nn, skip);
-    } catch (runtime_error& e) {
-        logger.error("Caught exception: %s\n",e.what());
-        return -1;
-    }
-}
diff --git a/3rdparty/flann/flann.h b/3rdparty/flann/flann.h
deleted file mode 100644 (file)
index 068753f..0000000
+++ /dev/null
@@ -1,278 +0,0 @@
-/***********************************************************************
- * Software License Agreement (BSD License)
- *
- * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
- * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
- *
- * THE BSD LICENSE
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *************************************************************************/
-
-#ifndef FLANN_H
-#define FLANN_H
-
-
-#include "constants.h"
-
-
-#ifdef WIN32
-/* win32 dll export/import directives */
-#ifdef flann_EXPORTS
-#define LIBSPEC __declspec(dllexport)
-#else
-#define LIBSPEC __declspec(dllimport)
-#endif
-#else
-/* unix needs nothing */
-#define LIBSPEC
-#endif
-
-
-
-
-
-struct FLANNParameters {
-       flann_algorithm_t algorithm; // the algorithm to use (see constants.h)
-
-       int checks;                // how many leafs (features) to check in one search
-    float cb_index;            // cluster boundary index. Used when searching the kmeans tree
-       int trees;                 // number of randomized trees to use (for kdtree)
-       int branching;             // branching factor (for kmeans tree)
-       int iterations;            // max iterations to perform in one kmeans cluetering (kmeans tree)
-       flann_centers_init_t centers_init;          // algorithm used for picking the initial cluetr centers for kmeans tree
-       float target_precision;    // precision desired (used for autotuning, -1 otherwise)
-       float build_weight;        // build tree time weighting factor
-       float memory_weight;       // index memory weigthing factor
-    float sample_fraction;     // what fraction of the dataset to use for autotuning
-
-    flann_log_level_t log_level;             // determines the verbosity of each flann function
-       char* log_destination;     // file where the output should go, NULL for the console
-       long random_seed;          // random seed to use
-};
-
-
-
-typedef void* FLANN_INDEX; // deprecated
-typedef void* flann_index_t;
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
-Sets the log level used for all flann functions (unless
-specified in FLANNParameters for each call
-
-Params:
-    level = verbosity level (defined in constants.h)
-*/
-LIBSPEC void flann_log_verbosity(int level);
-
-
-/**
- * Sets the distance type to use throughout FLANN.
- * If distance type specified is MINKOWSKI, the second argument
- * specifies which order the minkowski distance should have.
- */
-LIBSPEC void flann_set_distance_type(flann_distance_t distance_type, int order);
-
-
-/**
-Builds and returns an index. It uses autotuning if the target_precision field of index_params
-is between 0 and 1, or the parameters specified if it's -1.
-
-Params:
-    dataset = pointer to a data set stored in row major order
-    rows = number of rows (features) in the dataset
-    cols = number of columns in the dataset (feature dimensionality)
-    speedup = speedup over linear search, estimated if using autotuning, output parameter
-    index_params = index related parameters
-    flann_params = generic flann parameters
-
-Returns: the newly created index or a number <0 for error
-*/
-LIBSPEC FLANN_INDEX flann_build_index(float* dataset,
-                                                                         int rows,
-                                                                         int cols,
-                                                                         float* speedup,
-                                                                         struct FLANNParameters* flann_params);
-
-
-
-
-
-/**
- * Saves the index to a file. Only the index is saved into the file, the dataset corresponding to the index is not saved.
- *
- * @param index_id The index that should be saved
- * @param filename The filename the index should be saved to
- * @return Returns 0 on success, negative value on error.
- */
-LIBSPEC int flann_save_index(FLANN_INDEX index_id,
-                                                        char* filename);
-
-
-/**
- * Loads an index from a file.
- *
- * @param filename File to load the index from.
- * @param dataset The dataset corresponding to the index.
- * @param rows Dataset tors
- * @param cols Dataset columns
- * @return
- */
-LIBSPEC FLANN_INDEX flann_load_index(char* filename,
-                                                                        float* dataset,
-                                                                        int rows,
-                                                                        int cols);
-
-
-
-/**
-Builds an index and uses it to find nearest neighbors.
-
-Params:
-    dataset = pointer to a data set stored in row major order
-    rows = number of rows (features) in the dataset
-    cols = number of columns in the dataset (feature dimensionality)
-    testset = pointer to a query set stored in row major order
-    trows = number of rows (features) in the query dataset (same dimensionality as features in the dataset)
-    indices = pointer to matrix for the indices of the nearest neighbors of the testset features in the dataset
-            (must have trows number of rows and nn number of columns)
-    nn = how many nearest neighbors to return
-    index_params = index related parameters
-    flann_params = generic flann parameters
-
-Returns: zero or -1 for error
-*/
-LIBSPEC int flann_find_nearest_neighbors(float* dataset,
-                                                                                int rows,
-                                                                                int cols,
-                                                                                float* testset,
-                                                                                int trows,
-                                                                                int* indices,
-                                                                                float* dists,
-                                                                                int nn,
-                                                                                struct FLANNParameters* flann_params);
-
-
-
-/**
-Searches for nearest neighbors using the index provided
-
-Params:
-    index_id = the index (constructed previously using flann_build_index).
-    testset = pointer to a query set stored in row major order
-    trows = number of rows (features) in the query dataset (same dimensionality as features in the dataset)
-    indices = pointer to matrix for the indices of the nearest neighbors of the testset features in the dataset
-            (must have trows number of rows and nn number of columns)
-    nn = how many nearest neighbors to return
-    checks = number of checks to perform before the search is stopped
-    flann_params = generic flann parameters
-
-Returns: zero or a number <0 for error
-*/
-LIBSPEC int flann_find_nearest_neighbors_index(FLANN_INDEX index_id,
-                                                                                          float* testset,
-                                                                                          int trows,
-                                                                                          int* indices,
-                                                                                          float* dists,
-                                                                                          int nn,
-                                                                                          int checks,
-                                                                                          struct FLANNParameters* flann_params);
-
-
-
-/**
- * Performs an radius search using an already constructed index.
- *
- * In case of radius search, instead of always returning a predetermined
- * number of nearest neighbours (for example the 10 nearest neighbours), the
- * search will return all the neighbours found within a search radius
- * of the query point.
- *
- * The check parameter in the function below sets the level of approximation
- * for the search by only visiting "checks" number of features in the index
- * (the same way as for the KNN search). A lower value for checks will give
- * a higher search speedup at the cost of potentially not returning all the
- * neighbours in the specified radius.
- */
-LIBSPEC int flann_radius_search(FLANN_INDEX index_ptr, /* the index */
-                                                                               float* query,   /* query point */
-                                                                               int* indices, /* array for storing the indices found (will be modified) */
-                                                                               float* dists, /* similar, but for storing distances */
-                                                                               int max_nn,  /* size of arrays indices and dists */
-                                                                               float radius, /* search radius (squared radius for euclidian metric) */
-                                                                               int checks,  /* number of features to check, sets the level of approximation */
-                                                                               FLANNParameters* flann_params);
-
-
-/**
-Deletes an index and releases the memory used by it.
-
-Params:
-    index_id = the index (constructed previously using flann_build_index).
-    flann_params = generic flann parameters
-
-Returns: zero or a number <0 for error
-*/
-LIBSPEC int flann_free_index(FLANN_INDEX index_id,
-                                    struct FLANNParameters* flann_params);
-
-/**
-Clusters the features in the dataset using a hierarchical kmeans clustering approach.
-This is significantly faster than using a flat kmeans clustering for a large number
-of clusters.
-
-Params:
-    dataset = pointer to a data set stored in row major order
-    rows = number of rows (features) in the dataset
-    cols = number of columns in the dataset (feature dimensionality)
-    clusters = number of cluster to compute
-    result = memory buffer where the output cluster centers are storred
-    index_params = used to specify the kmeans tree parameters (branching factor, max number of iterations to use)
-    flann_params = generic flann parameters
-
-Returns: number of clusters computed or a number <0 for error. This number can be different than the number of clusters requested, due to the
-    way hierarchical clusters are computed. The number of clusters returned will be the highest number of the form
-    (branch_size-1)*K+1 smaller than the number of clusters requested.
-*/
-
-LIBSPEC int flann_compute_cluster_centers(float* dataset,
-                                                                                 int rows,
-                                                                                 int cols,
-                                                                                 int clusters,
-                                                                                 float* result,
-                                                                                 struct FLANNParameters* flann_params);
-
-
-#ifdef __cplusplus
-};
-
-
-#include "flann.hpp"
-
-#endif
-
-
-#endif /*FLANN_H*/
diff --git a/3rdparty/flann/flann.hpp b/3rdparty/flann/flann.hpp
deleted file mode 100644 (file)
index 97df248..0000000
+++ /dev/null
@@ -1,247 +0,0 @@
-/***********************************************************************
- * Software License Agreement (BSD License)
- *
- * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
- * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
- *
- * THE BSD LICENSE
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *************************************************************************/
-
-#ifndef FLANN_HPP_
-#define FLANN_HPP_
-
-#include <vector>
-#include <string>
-
-#include "constants.h"
-#include "common.h"
-#include "matrix.h"
-
-#include "flann.h"
-
-namespace cvflann
-{
-
-class NNIndex;
-
-class IndexFactory
-{
-public:
-    virtual ~IndexFactory() {}
-       virtual NNIndex* createIndex(const Matrix<float>& dataset) const = 0;
-};
-
-struct IndexParams : public IndexFactory {
-protected:
-       IndexParams() {};
-
-public:
-
-       static IndexParams* createFromParameters(const FLANNParameters& p);
-
-       virtual void fromParameters(const FLANNParameters&) {};
-       virtual void toParameters(FLANNParameters&) { };
-};
-
-struct LinearIndexParams : public IndexParams {
-       LinearIndexParams() {};
-
-       NNIndex* createIndex(const Matrix<float>& dataset) const;
-};
-
-
-
-struct KDTreeIndexParams : public IndexParams {
-       KDTreeIndexParams(int trees_ = 4) : trees(trees_) {};
-
-       int trees;                 // number of randomized trees to use (for kdtree)
-
-       NNIndex* createIndex(const Matrix<float>& dataset) const;
-
-       void fromParameters(const FLANNParameters& p)
-       {
-               trees = p.trees;
-       }
-
-       void toParameters(FLANNParameters& p)
-       {
-               p.algorithm = KDTREE;
-               p.trees = trees;
-       };
-
-};
-
-struct KMeansIndexParams : public IndexParams {
-       KMeansIndexParams(int branching_ = 32, int iterations_ = 11,
-                       flann_centers_init_t centers_init_ = CENTERS_RANDOM, float cb_index_ = 0.2 ) :
-               branching(branching_),
-               iterations(iterations_),
-               centers_init(centers_init_),
-               cb_index(cb_index_) {};
-
-       int branching;             // branching factor (for kmeans tree)
-       int iterations;            // max iterations to perform in one kmeans clustering (kmeans tree)
-       flann_centers_init_t centers_init;          // algorithm used for picking the initial cluster centers for kmeans tree
-    float cb_index;            // cluster boundary index. Used when searching the kmeans tree
-
-
-    NNIndex* createIndex(const Matrix<float>& dataset) const;
-
-       void fromParameters(const FLANNParameters& p)
-       {
-               branching = p.branching;
-               iterations = p.iterations;
-               centers_init = p.centers_init;
-               cb_index = p.cb_index;
-       }
-
-       void toParameters(FLANNParameters& p)
-       {
-               p.algorithm = KMEANS;
-               p.branching = branching;
-               p.iterations = iterations;
-               p.centers_init = centers_init;
-               p.cb_index = cb_index;
-       };
-
-};
-
-
-struct CompositeIndexParams : public IndexParams {
-       CompositeIndexParams(int trees_ = 4, int branching_ = 32, int iterations_ = 11,
-                       flann_centers_init_t centers_init_ = CENTERS_RANDOM, float cb_index_ = 0.2 ) :
-               trees(trees_),
-               branching(branching_),
-               iterations(iterations_),
-               centers_init(centers_init_),
-               cb_index(cb_index_) {};
-
-       int trees;                 // number of randomized trees to use (for kdtree)
-       int branching;             // branching factor (for kmeans tree)
-       int iterations;            // max iterations to perform in one kmeans clustering (kmeans tree)
-       flann_centers_init_t centers_init;          // algorithm used for picking the initial cluster centers for kmeans tree
-    float cb_index;            // cluster boundary index. Used when searching the kmeans tree
-
-    NNIndex* createIndex(const Matrix<float>& dataset) const;
-
-       void fromParameters(const FLANNParameters& p)
-       {
-               trees = p.trees;
-               branching = p.branching;
-               iterations = p.iterations;
-               centers_init = p.centers_init;
-               cb_index = p.cb_index;
-       }
-
-       void toParameters(FLANNParameters& p)
-       {
-               p.algorithm = COMPOSITE;
-               p.trees = trees;
-               p.branching = branching;
-               p.iterations = iterations;
-               p.centers_init = centers_init;
-               p.cb_index = cb_index;
-       };
-};
-
-
-struct AutotunedIndexParams : public IndexParams {
-       AutotunedIndexParams( float target_precision_ = 0.9, float build_weight_ = 0.01,
-                       float memory_weight_ = 0, float sample_fraction_ = 0.1) :
-               target_precision(target_precision_),
-               build_weight(build_weight_),
-               memory_weight(memory_weight_),
-               sample_fraction(sample_fraction_) {};
-
-       float target_precision;    // precision desired (used for autotuning, -1 otherwise)
-       float build_weight;        // build tree time weighting factor
-       float memory_weight;       // index memory weighting factor
-    float sample_fraction;     // what fraction of the dataset to use for autotuning
-
-    NNIndex* createIndex(const Matrix<float>& dataset) const;
-
-       void fromParameters(const FLANNParameters& p)
-       {
-               target_precision = p.target_precision;
-               build_weight = p.build_weight;
-               memory_weight = p.memory_weight;
-               sample_fraction = p.sample_fraction;
-       }
-
-       void toParameters(FLANNParameters& p)
-       {
-               p.algorithm = AUTOTUNED;
-               p.target_precision = target_precision;
-               p.build_weight = build_weight;
-               p.memory_weight = memory_weight;
-               p.sample_fraction = sample_fraction;
-       };
-};
-
-
-struct SavedIndexParams : public IndexParams {
-       SavedIndexParams() {
-               throw FLANNException("I don't know which index to load");
-       }
-       SavedIndexParams(std::string filename_) : filename(filename_) {}
-
-       std::string filename;           // filename of the stored index
-
-       NNIndex* createIndex(const Matrix<float>& dataset) const;
-};
-
-
-struct SearchParams {
-       SearchParams(int checks_ = 32) :
-               checks(checks_) {};
-
-       int checks;
-};
-
-
-class Index {
-       NNIndex* nnIndex;
-
-public:
-       Index(const Matrix<float>& features, const IndexParams& params);
-
-       ~Index();
-
-       void knnSearch(const Matrix<float>& queries, Matrix<int>& indices, Matrix<float>& dists, int knn, const SearchParams& params);
-
-       int radiusSearch(const Matrix<float>& query, Matrix<int> indices, Matrix<float> dists, float radius, const SearchParams& params);
-
-       void save(std::string filename);
-
-       int veclen() const;
-
-       int size() const;
-};
-
-
-int hierarchicalClustering(const Matrix<float>& features, Matrix<float>& centers, const KMeansIndexParams& params);
-
-
-}
-#endif /* FLANN_HPP_ */
diff --git a/3rdparty/flann/index_testing.h b/3rdparty/flann/index_testing.h
deleted file mode 100644 (file)
index 7a8278f..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-/***********************************************************************
- * Software License Agreement (BSD License)
- *
- * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
- * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
- *
- * THE BSD LICENSE
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *************************************************************************/
-
-#ifndef TESTING_H
-#define TESTING_H
-
-
-#include "nn_index.h"
-#include "matrix.h"
-
-
-using namespace std;
-
-namespace cvflann
-{
-
-void search_for_neighbors(NNIndex& index, const Matrix<float>& testset, Matrix<int>& result, Matrix<float>& dists, const SearchParams &searchParams, int skip = 0);
-
-float test_index_checks(NNIndex& index, const Matrix<float>& inputData, const Matrix<float>& testData, const Matrix<int>& matches,
-            int checks, float& precision, int nn = 1, int skipMatches = 0);
-
-float test_index_precision(NNIndex& index, const Matrix<float>& inputData, const Matrix<float>& testData, const Matrix<int>& matches,
-             float precision, int& checks, int nn = 1, int skipMatches = 0);
-
-float test_index_precisions(NNIndex& index, const Matrix<float>& inputData, const Matrix<float>& testData, const Matrix<int>& matches,
-                    float* precisions, int precisions_length, int nn = 1, int skipMatches = 0, float maxTime = 0);
-
-}
-
-#endif //TESTING_H
diff --git a/3rdparty/flann/logger.cpp b/3rdparty/flann/logger.cpp
deleted file mode 100644 (file)
index c7e43e1..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-/***********************************************************************
- * Software License Agreement (BSD License)
- *
- * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
- * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
- *
- * THE BSD LICENSE
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *************************************************************************/
-
-#include "logger.h"
-
-#include <cstdio>
-#include <cstdarg>
-#include <sstream>
-
-using namespace std;
-
-namespace cvflann
-{
-
-Logger logger;
-
-int Logger::log(int level, const char* fmt, ...)
-{
-    if (level > logLevel ) return -1;
-
-    int ret;
-    va_list arglist;
-    va_start(arglist, fmt);
-    ret = vfprintf(stream, fmt, arglist);
-    va_end(arglist);
-
-    return ret;
-}
-
-int Logger::log(int level, const char* fmt, va_list arglist)
-{
-    if (level > logLevel ) return -1;
-
-    int ret;
-    ret = vfprintf(stream, fmt, arglist);
-
-    return ret;
-}
-
-
-#define LOG_METHOD(NAME,LEVEL) \
-    int Logger::NAME(const char* fmt, ...) \
-    { \
-        int ret; \
-        va_list ap; \
-        va_start(ap, fmt); \
-        ret = log(LEVEL, fmt, ap); \
-        va_end(ap); \
-        return ret; \
-    }
-
-
-LOG_METHOD(fatal, LOG_FATAL)
-LOG_METHOD(error, LOG_ERROR)
-LOG_METHOD(warn, LOG_WARN)
-LOG_METHOD(info, LOG_INFO)
-
-}
diff --git a/3rdparty/flann/matrix.h b/3rdparty/flann/matrix.h
deleted file mode 100644 (file)
index 94ffb44..0000000
+++ /dev/null
@@ -1,163 +0,0 @@
-/***********************************************************************
- * Software License Agreement (BSD License)
- *
- * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
- * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
- *
- * THE BSD LICENSE
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *************************************************************************/
-
-#ifndef DATASET_H
-#define DATASET_H
-
-#include <stdio.h>
-#include <random.h>
-
-
-namespace cvflann
-{
-/**
-* Class implementing a generic rectangular dataset.
-*/
-template <typename T>
-class Matrix {
-
-    /**
-    * Flag showing if the class owns its data storage.
-    */
-    bool ownData;
-
-    void shallow_copy(const Matrix& rhs)
-    {
-        data = rhs.data;
-        rows = rhs.rows;
-        cols = rhs.cols;
-        ownData = false;
-    }
-
-public:
-    long rows;
-    long cols;
-    T* data;
-
-
-    Matrix(long rows_, long cols_, T* data_ = NULL) :
-        ownData(false), rows(rows_), cols(cols_), data(data_)
-       {
-        if (data_==NULL) {
-                   data = new T[rows*cols];
-            ownData = true;
-        }
-       }
-
-    Matrix(const Matrix& d)
-    {
-        shallow_copy(d);
-    }
-
-    const Matrix& operator=(const Matrix& rhs)
-    {
-        if (this!=&rhs) {
-            shallow_copy(rhs);
-        }
-        return *this;
-    }
-
-       ~Matrix()
-       {
-        if (ownData) {
-                 delete[] data;
-        }
-       }
-
-    /**
-    * Operator that return a (pointer to a) row of the data.
-    */
-    T* operator[](long index)
-    {
-        return data+index*cols;
-    }
-
-    T* operator[](long index) const
-    {
-        return data+index*cols;
-    }
-
-
-
-    Matrix<T>* sample(long size, bool remove = false)
-    {
-        UniqueRandom rand(rows);
-        Matrix<T> *newSet = new Matrix<T>(size,cols);
-
-        T *src,*dest;
-        for (long i=0;i<size;++i) {
-            long r = rand.next();
-            dest = (*newSet)[i];
-            src = (*this)[r];
-            for (long j=0;j<cols;++j) {
-                dest[j] = src[j];
-            }
-            if (remove) {
-                dest = (*this)[rows-i-1];
-                src = (*this)[r];
-                for (long j=0;j<cols;++j) {
-                    swap(*src,*dest);
-                    src++;
-                    dest++;
-                }
-            }
-        }
-
-        if (remove) {
-            rows -= size;
-        }
-
-        return newSet;
-    }
-
-    Matrix<T>* sample(long size) const
-    {
-        UniqueRandom rand(rows);
-        Matrix<T> *newSet = new Matrix<T>(size,cols);
-
-        T *src,*dest;
-        for (long i=0;i<size;++i) {
-            long r = rand.next();
-            dest = (*newSet)[i];
-            src = (*this)[r];
-            for (long j=0;j<cols;++j) {
-                dest[j] = src[j];
-            }
-        }
-
-        return newSet;
-    }
-
-};
-
-
-}
-
-#endif //DATASET_H
diff --git a/3rdparty/flann/random.cpp b/3rdparty/flann/random.cpp
deleted file mode 100644 (file)
index 33cbe47..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-/***********************************************************************
- * Software License Agreement (BSD License)
- *
- * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
- * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
- *
- * THE BSD LICENSE
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *************************************************************************/
-
-#include "random.h"
-
-
-namespace cvflann
-{
-
-void seed_random(unsigned int seed)
-{
-    srand(seed);
-}
-
-double rand_double(double high, double low)
-{
-    return low + ((high-low) * (std::rand() / (RAND_MAX + 1.0)));
-}
-
-
-int rand_int(int high, int low)
-{
-    return low + (int) ( double(high-low) * (std::rand() / (RAND_MAX + 1.0)));
-}
-
-}
diff --git a/3rdparty/flann/random.h b/3rdparty/flann/random.h
deleted file mode 100644 (file)
index 74d5a56..0000000
+++ /dev/null
@@ -1,134 +0,0 @@
-/***********************************************************************
- * Software License Agreement (BSD License)
- *
- * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
- * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
- *
- * THE BSD LICENSE
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *************************************************************************/
-
-#ifndef RANDOM_H
-#define RANDOM_H
-
-#include <algorithm>
-#include <cstdlib>
-#include <cassert>
-
-using namespace std;
-
-namespace cvflann
-{
-
-/**
- * Seeds the random number generator
- */
-void seed_random(unsigned int seed);
-
-/*
- * Generates a random double value.
- */
-double rand_double(double high = 1.0, double low=0);
-
-/*
- * Generates a random integer value.
- */
-int rand_int(int high = RAND_MAX, int low = 0);
-
-
-/**
- * Random number generator that returns a distinct number from
- * the [0,n) interval each time.
- *
- * TODO: improve on this to use a generator function instead of an
- * array of randomly permuted numbers
- */
-class UniqueRandom
-{
-       int* vals;
-    int size;
-       int counter;
-
-public:
-       /**
-        * Constructor.
-        * Params:
-        *     n = the size of the interval from which to generate
-        *              random numbers.
-        */
-       UniqueRandom(int n) : vals(NULL) {
-               init(n);
-       }
-
-       ~UniqueRandom()
-       {
-               delete[] vals;
-       }
-
-       /**
-        * Initializes the number generator.
-        * Params:
-        *              n = the size of the interval from which to generate
-        *              random numbers.
-        */
-       void init(int n)
-       {
-       // create and initialize an array of size n
-               if (vals == NULL || n!=size) {
-            delete[] vals;
-               size = n;
-            vals = new int[size];
-       }
-       for(int i=0;i<size;++i) {
-                       vals[i] = i;
-               }
-
-               // shuffle the elements in the array
-        // Fisher-Yates shuffle
-               for (int i=size;i>0;--i) {
-//                     int rand = cast(int) (drand48() * n);
-                       int rnd = rand_int(i);
-                       assert(rnd >=0 && rnd < i);
-                       swap(vals[i-1], vals[rnd]);
-               }
-
-               counter = 0;
-       }
-
-       /**
-        * Return a distinct random integer in greater or equal to 0 and less
-        * than 'n' on each call. It should be called maximum 'n' times.
-        * Returns: a random integer
-        */
-       int next() {
-               if (counter==size) {
-                       return -1;
-               } else {
-                       return vals[counter++];
-               }
-       }
-};
-
-}
-
-#endif //RANDOM_H
diff --git a/3rdparty/flann/saving.cpp b/3rdparty/flann/saving.cpp
deleted file mode 100644 (file)
index a599788..0000000
+++ /dev/null
@@ -1,73 +0,0 @@
-/***********************************************************************
- * Software License Agreement (BSD License)
- *
- * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
- * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
- *
- * THE BSD LICENSE
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *************************************************************************/
-
-#include "common.h"
-#include "saving.h"
-#include "nn_index.h"
-#include <cstdio>
-
-namespace cvflann
-{
-
-const char FLANN_SIGNATURE[] = "FLANN_INDEX";
-
-void save_header(FILE* stream, const NNIndex& index)
-{
-       IndexHeader header;
-       memset(header.signature, 0 , sizeof(header.signature));
-       strcpy(header.signature, FLANN_SIGNATURE);
-       header.flann_version = (int)FLANN_VERSION;
-       header.index_type = index.getType();
-       header.rows = index.size();
-       header.cols = index.veclen();
-
-       std::fwrite(&header, sizeof(header),1,stream);
-}
-
-
-
-IndexHeader load_header(FILE* stream)
-{
-       IndexHeader header;
-       int read_size = (int)fread(&header,sizeof(header),1,stream);
-
-       if (read_size!=1) {
-               throw FLANNException("Invalid index file, cannot read");
-       }
-
-       if (strcmp(header.signature,FLANN_SIGNATURE)!=0) {
-               throw FLANNException("Invalid index file, wrong signature");
-       }
-
-       return header;
-
-}
-
-}
diff --git a/3rdparty/include/flann/common.h b/3rdparty/include/flann/common.h
deleted file mode 100644 (file)
index e5f9ed0..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-/***********************************************************************
- * Software License Agreement (BSD License)
- *
- * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
- * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
- *
- * THE BSD LICENSE
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *************************************************************************/
-
-#ifndef COMMOM_H
-#define COMMOM_H
-
-
-#define ARRAY_LEN(a) (sizeof(a)/sizeof(a[0]))
-
-#include <stdexcept>
-
-namespace cvflann
-{
-class FLANNException : public std::runtime_error {
- public:
-   FLANNException(const char* message) : std::runtime_error(message) { }
- };
-
-}
-
-#endif //COMMOM_H
diff --git a/3rdparty/include/flann/constants.h b/3rdparty/include/flann/constants.h
deleted file mode 100644 (file)
index 2332348..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
-/***********************************************************************
- * Software License Agreement (BSD License)
- *
- * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
- * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
- *
- * THE BSD LICENSE
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *************************************************************************/
-
-#ifndef CONSTANTS_H
-#define CONSTANTS_H
-
-
-const double FLANN_VERSION = 1.20;
-
-/* Nearest neighbor index algorithms */
-enum flann_algorithm_t {
-       LINEAR = 0,
-       KDTREE = 1,
-       KMEANS = 2,
-       COMPOSITE = 3,
-       SAVED = 254,
-       AUTOTUNED = 255,
-};
-
-enum flann_centers_init_t {
-       CENTERS_RANDOM = 0,
-       CENTERS_GONZALES = 1,
-       CENTERS_KMEANSPP = 2
-};
-
-
-enum flann_log_level_t {
-       LOG_NONE = 0,
-       LOG_FATAL = 1,
-       LOG_ERROR = 2,
-       LOG_WARN = 3,
-       LOG_INFO = 4
-};
-
-enum flann_distance_t {
-       EUCLIDEAN = 1,
-       MANHATTAN = 2,
-       MINKOWSKI = 3
-};
-
-#endif  // CONSTANTS_H
diff --git a/3rdparty/include/flann/flann.h b/3rdparty/include/flann/flann.h
deleted file mode 100644 (file)
index 068753f..0000000
+++ /dev/null
@@ -1,278 +0,0 @@
-/***********************************************************************
- * Software License Agreement (BSD License)
- *
- * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
- * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
- *
- * THE BSD LICENSE
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *************************************************************************/
-
-#ifndef FLANN_H
-#define FLANN_H
-
-
-#include "constants.h"
-
-
-#ifdef WIN32
-/* win32 dll export/import directives */
-#ifdef flann_EXPORTS
-#define LIBSPEC __declspec(dllexport)
-#else
-#define LIBSPEC __declspec(dllimport)
-#endif
-#else
-/* unix needs nothing */
-#define LIBSPEC
-#endif
-
-
-
-
-
-struct FLANNParameters {
-       flann_algorithm_t algorithm; // the algorithm to use (see constants.h)
-
-       int checks;                // how many leafs (features) to check in one search
-    float cb_index;            // cluster boundary index. Used when searching the kmeans tree
-       int trees;                 // number of randomized trees to use (for kdtree)
-       int branching;             // branching factor (for kmeans tree)
-       int iterations;            // max iterations to perform in one kmeans cluetering (kmeans tree)
-       flann_centers_init_t centers_init;          // algorithm used for picking the initial cluetr centers for kmeans tree
-       float target_precision;    // precision desired (used for autotuning, -1 otherwise)
-       float build_weight;        // build tree time weighting factor
-       float memory_weight;       // index memory weigthing factor
-    float sample_fraction;     // what fraction of the dataset to use for autotuning
-
-    flann_log_level_t log_level;             // determines the verbosity of each flann function
-       char* log_destination;     // file where the output should go, NULL for the console
-       long random_seed;          // random seed to use
-};
-
-
-
-typedef void* FLANN_INDEX; // deprecated
-typedef void* flann_index_t;
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
-Sets the log level used for all flann functions (unless
-specified in FLANNParameters for each call
-
-Params:
-    level = verbosity level (defined in constants.h)
-*/
-LIBSPEC void flann_log_verbosity(int level);
-
-
-/**
- * Sets the distance type to use throughout FLANN.
- * If distance type specified is MINKOWSKI, the second argument
- * specifies which order the minkowski distance should have.
- */
-LIBSPEC void flann_set_distance_type(flann_distance_t distance_type, int order);
-
-
-/**
-Builds and returns an index. It uses autotuning if the target_precision field of index_params
-is between 0 and 1, or the parameters specified if it's -1.
-
-Params:
-    dataset = pointer to a data set stored in row major order
-    rows = number of rows (features) in the dataset
-    cols = number of columns in the dataset (feature dimensionality)
-    speedup = speedup over linear search, estimated if using autotuning, output parameter
-    index_params = index related parameters
-    flann_params = generic flann parameters
-
-Returns: the newly created index or a number <0 for error
-*/
-LIBSPEC FLANN_INDEX flann_build_index(float* dataset,
-                                                                         int rows,
-                                                                         int cols,
-                                                                         float* speedup,
-                                                                         struct FLANNParameters* flann_params);
-
-
-
-
-
-/**
- * Saves the index to a file. Only the index is saved into the file, the dataset corresponding to the index is not saved.
- *
- * @param index_id The index that should be saved
- * @param filename The filename the index should be saved to
- * @return Returns 0 on success, negative value on error.
- */
-LIBSPEC int flann_save_index(FLANN_INDEX index_id,
-                                                        char* filename);
-
-
-/**
- * Loads an index from a file.
- *
- * @param filename File to load the index from.
- * @param dataset The dataset corresponding to the index.
- * @param rows Dataset tors
- * @param cols Dataset columns
- * @return
- */
-LIBSPEC FLANN_INDEX flann_load_index(char* filename,
-                                                                        float* dataset,
-                                                                        int rows,
-                                                                        int cols);
-
-
-
-/**
-Builds an index and uses it to find nearest neighbors.
-
-Params:
-    dataset = pointer to a data set stored in row major order
-    rows = number of rows (features) in the dataset
-    cols = number of columns in the dataset (feature dimensionality)
-    testset = pointer to a query set stored in row major order
-    trows = number of rows (features) in the query dataset (same dimensionality as features in the dataset)
-    indices = pointer to matrix for the indices of the nearest neighbors of the testset features in the dataset
-            (must have trows number of rows and nn number of columns)
-    nn = how many nearest neighbors to return
-    index_params = index related parameters
-    flann_params = generic flann parameters
-
-Returns: zero or -1 for error
-*/
-LIBSPEC int flann_find_nearest_neighbors(float* dataset,
-                                                                                int rows,
-                                                                                int cols,
-                                                                                float* testset,
-                                                                                int trows,
-                                                                                int* indices,
-                                                                                float* dists,
-                                                                                int nn,
-                                                                                struct FLANNParameters* flann_params);
-
-
-
-/**
-Searches for nearest neighbors using the index provided
-
-Params:
-    index_id = the index (constructed previously using flann_build_index).
-    testset = pointer to a query set stored in row major order
-    trows = number of rows (features) in the query dataset (same dimensionality as features in the dataset)
-    indices = pointer to matrix for the indices of the nearest neighbors of the testset features in the dataset
-            (must have trows number of rows and nn number of columns)
-    nn = how many nearest neighbors to return
-    checks = number of checks to perform before the search is stopped
-    flann_params = generic flann parameters
-
-Returns: zero or a number <0 for error
-*/
-LIBSPEC int flann_find_nearest_neighbors_index(FLANN_INDEX index_id,
-                                                                                          float* testset,
-                                                                                          int trows,
-                                                                                          int* indices,
-                                                                                          float* dists,
-                                                                                          int nn,
-                                                                                          int checks,
-                                                                                          struct FLANNParameters* flann_params);
-
-
-
-/**
- * Performs an radius search using an already constructed index.
- *
- * In case of radius search, instead of always returning a predetermined
- * number of nearest neighbours (for example the 10 nearest neighbours), the
- * search will return all the neighbours found within a search radius
- * of the query point.
- *
- * The check parameter in the function below sets the level of approximation
- * for the search by only visiting "checks" number of features in the index
- * (the same way as for the KNN search). A lower value for checks will give
- * a higher search speedup at the cost of potentially not returning all the
- * neighbours in the specified radius.
- */
-LIBSPEC int flann_radius_search(FLANN_INDEX index_ptr, /* the index */
-                                                                               float* query,   /* query point */
-                                                                               int* indices, /* array for storing the indices found (will be modified) */
-                                                                               float* dists, /* similar, but for storing distances */
-                                                                               int max_nn,  /* size of arrays indices and dists */
-                                                                               float radius, /* search radius (squared radius for euclidian metric) */
-                                                                               int checks,  /* number of features to check, sets the level of approximation */
-                                                                               FLANNParameters* flann_params);
-
-
-/**
-Deletes an index and releases the memory used by it.
-
-Params:
-    index_id = the index (constructed previously using flann_build_index).
-    flann_params = generic flann parameters
-
-Returns: zero or a number <0 for error
-*/
-LIBSPEC int flann_free_index(FLANN_INDEX index_id,
-                                    struct FLANNParameters* flann_params);
-
-/**
-Clusters the features in the dataset using a hierarchical kmeans clustering approach.
-This is significantly faster than using a flat kmeans clustering for a large number
-of clusters.
-
-Params:
-    dataset = pointer to a data set stored in row major order
-    rows = number of rows (features) in the dataset
-    cols = number of columns in the dataset (feature dimensionality)
-    clusters = number of cluster to compute
-    result = memory buffer where the output cluster centers are storred
-    index_params = used to specify the kmeans tree parameters (branching factor, max number of iterations to use)
-    flann_params = generic flann parameters
-
-Returns: number of clusters computed or a number <0 for error. This number can be different than the number of clusters requested, due to the
-    way hierarchical clusters are computed. The number of clusters returned will be the highest number of the form
-    (branch_size-1)*K+1 smaller than the number of clusters requested.
-*/
-
-LIBSPEC int flann_compute_cluster_centers(float* dataset,
-                                                                                 int rows,
-                                                                                 int cols,
-                                                                                 int clusters,
-                                                                                 float* result,
-                                                                                 struct FLANNParameters* flann_params);
-
-
-#ifdef __cplusplus
-};
-
-
-#include "flann.hpp"
-
-#endif
-
-
-#endif /*FLANN_H*/
diff --git a/3rdparty/include/flann/flann.hpp b/3rdparty/include/flann/flann.hpp
deleted file mode 100644 (file)
index 83231df..0000000
+++ /dev/null
@@ -1,246 +0,0 @@
-/***********************************************************************
- * Software License Agreement (BSD License)
- *
- * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
- * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
- *
- * THE BSD LICENSE
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *************************************************************************/
-
-#ifndef FLANN_HPP_
-#define FLANN_HPP_
-
-#include <vector>
-#include <string>
-
-#include "constants.h"
-#include "common.h"
-#include "matrix.h"
-
-#include "flann.h"
-
-namespace cvflann
-{
-
-class NNIndex;
-
-class IndexFactory
-{
-public:
-    virtual ~IndexFactory() {}
-       virtual NNIndex* createIndex(const Matrix<float>& dataset) const = 0;
-};
-
-struct IndexParams : public IndexFactory {
-protected:
-       IndexParams() {};
-public:
-
-       static IndexParams* createFromParameters(const FLANNParameters& p);
-
-       void fromParameters(const FLANNParameters&) {};
-       void toParameters(FLANNParameters&) { };
-};
-
-struct LinearIndexParams : public IndexParams {
-       LinearIndexParams() {};
-
-       NNIndex* createIndex(const Matrix<float>& dataset) const;
-};
-
-
-
-struct KDTreeIndexParams : public IndexParams {
-       KDTreeIndexParams(int trees_ = 4) : trees(trees_) {};
-
-       int trees;                 // number of randomized trees to use (for kdtree)
-
-       NNIndex* createIndex(const Matrix<float>& dataset) const;
-
-       void fromParameters(const FLANNParameters& p)
-       {
-               trees = p.trees;
-       }
-
-       void toParameters(FLANNParameters& p)
-       {
-               p.algorithm = KDTREE;
-               p.trees = trees;
-       };
-
-};
-
-struct KMeansIndexParams : public IndexParams {
-       KMeansIndexParams(int branching_ = 32, int iterations_ = 11,
-                       flann_centers_init_t centers_init_ = CENTERS_RANDOM, float cb_index_ = 0.2 ) :
-               branching(branching_),
-               iterations(iterations_),
-               centers_init(centers_init_),
-               cb_index(cb_index_) {};
-
-       int branching;             // branching factor (for kmeans tree)
-       int iterations;            // max iterations to perform in one kmeans clustering (kmeans tree)
-       flann_centers_init_t centers_init;          // algorithm used for picking the initial cluster centers for kmeans tree
-    float cb_index;            // cluster boundary index. Used when searching the kmeans tree
-
-
-    NNIndex* createIndex(const Matrix<float>& dataset) const;
-
-       void fromParameters(const FLANNParameters& p)
-       {
-               branching = p.branching;
-               iterations = p.iterations;
-               centers_init = p.centers_init;
-               cb_index = p.cb_index;
-       }
-
-       void toParameters(FLANNParameters& p)
-       {
-               p.algorithm = KMEANS;
-               p.branching = branching;
-               p.iterations = iterations;
-               p.centers_init = centers_init;
-               p.cb_index = cb_index;
-       };
-
-};
-
-
-struct CompositeIndexParams : public IndexParams {
-       CompositeIndexParams(int trees_ = 4, int branching_ = 32, int iterations_ = 11,
-                       flann_centers_init_t centers_init_ = CENTERS_RANDOM, float cb_index_ = 0.2 ) :
-               trees(trees_),
-               branching(branching_),
-               iterations(iterations_),
-               centers_init(centers_init_),
-               cb_index(cb_index_) {};
-
-       int trees;                 // number of randomized trees to use (for kdtree)
-       int branching;             // branching factor (for kmeans tree)
-       int iterations;            // max iterations to perform in one kmeans clustering (kmeans tree)
-       flann_centers_init_t centers_init;          // algorithm used for picking the initial cluster centers for kmeans tree
-    float cb_index;            // cluster boundary index. Used when searching the kmeans tree
-
-    NNIndex* createIndex(const Matrix<float>& dataset) const;
-
-       void fromParameters(const FLANNParameters& p)
-       {
-               trees = p.trees;
-               branching = p.branching;
-               iterations = p.iterations;
-               centers_init = p.centers_init;
-               cb_index = p.cb_index;
-       }
-
-       void toParameters(FLANNParameters& p)
-       {
-               p.algorithm = COMPOSITE;
-               p.trees = trees;
-               p.branching = branching;
-               p.iterations = iterations;
-               p.centers_init = centers_init;
-               p.cb_index = cb_index;
-       };
-};
-
-
-struct AutotunedIndexParams : public IndexParams {
-       AutotunedIndexParams( float target_precision_ = 0.9, float build_weight_ = 0.01,
-                       float memory_weight_ = 0, float sample_fraction_ = 0.1) :
-               target_precision(target_precision_),
-               build_weight(build_weight_),
-               memory_weight(memory_weight_),
-               sample_fraction(sample_fraction_) {};
-
-       float target_precision;    // precision desired (used for autotuning, -1 otherwise)
-       float build_weight;        // build tree time weighting factor
-       float memory_weight;       // index memory weighting factor
-    float sample_fraction;     // what fraction of the dataset to use for autotuning
-
-    NNIndex* createIndex(const Matrix<float>& dataset) const;
-
-       void fromParameters(const FLANNParameters& p)
-       {
-               target_precision = p.target_precision;
-               build_weight = p.build_weight;
-               memory_weight = p.memory_weight;
-               sample_fraction = p.sample_fraction;
-       }
-
-       void toParameters(FLANNParameters& p)
-       {
-               p.algorithm = AUTOTUNED;
-               p.target_precision = target_precision;
-               p.build_weight = build_weight;
-               p.memory_weight = memory_weight;
-               p.sample_fraction = sample_fraction;
-       };
-};
-
-
-struct SavedIndexParams : public IndexParams {
-       SavedIndexParams() {
-               throw FLANNException("I don't know which index to load");
-       }
-       SavedIndexParams(std::string filename_) : filename(filename_) {}
-
-       std::string filename;           // filename of the stored index
-
-       NNIndex* createIndex(const Matrix<float>& dataset) const;
-};
-
-
-struct SearchParams {
-       SearchParams(int checks_ = 32) :
-               checks(checks_) {};
-
-       int checks;
-};
-
-
-class Index {
-       NNIndex* nnIndex;
-
-public:
-       Index(const Matrix<float>& features, const IndexParams& params);
-
-       ~Index();
-
-       void knnSearch(const Matrix<float>& queries, Matrix<int>& indices, Matrix<float>& dists, int knn, const SearchParams& params);
-
-       int radiusSearch(const Matrix<float>& query, Matrix<int> indices, Matrix<float> dists, float radius, const SearchParams& params);
-
-       void save(std::string filename);
-
-       int veclen() const;
-
-       int size() const;
-};
-
-
-int hierarchicalClustering(const Matrix<float>& features, Matrix<float>& centers, const KMeansIndexParams& params);
-
-
-}
-#endif /* FLANN_HPP_ */
diff --git a/3rdparty/include/flann/matrix.h b/3rdparty/include/flann/matrix.h
deleted file mode 100644 (file)
index d2ad915..0000000
+++ /dev/null
@@ -1,163 +0,0 @@
-/***********************************************************************
- * Software License Agreement (BSD License)
- *
- * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
- * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
- *
- * THE BSD LICENSE
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *************************************************************************/
-
-#ifndef DATASET_H
-#define DATASET_H
-
-#include <stdio.h>
-#include "random.h"
-
-
-namespace cvflann
-{
-/**
-* Class implementing a generic rectangular dataset.
-*/
-template <typename T>
-class Matrix {
-
-    /**
-    * Flag showing if the class owns its data storage.
-    */
-    bool ownData;
-
-    void shallow_copy(const Matrix& rhs)
-    {
-        data = rhs.data;
-        rows = rhs.rows;
-        cols = rhs.cols;
-        ownData = false;
-    }
-
-public:
-    long rows;
-    long cols;
-    T* data;
-
-
-    Matrix(long rows_, long cols_, T* data_ = NULL) :
-        ownData(false), rows(rows_), cols(cols_), data(data_)
-       {
-        if (data_==NULL) {
-                   data = new T[rows*cols];
-            ownData = true;
-        }
-       }
-
-    Matrix(const Matrix& d)
-    {
-        shallow_copy(d);
-    }
-
-    const Matrix& operator=(const Matrix& rhs)
-    {
-        if (this!=&rhs) {
-            shallow_copy(rhs);
-        }
-        return *this;
-    }
-
-       ~Matrix()
-       {
-        if (ownData) {
-                 delete[] data;
-        }
-       }
-
-    /**
-    * Operator that return a (pointer to a) row of the data.
-    */
-    T* operator[](long index)
-    {
-        return data+index*cols;
-    }
-
-    T* operator[](long index) const
-    {
-        return data+index*cols;
-    }
-
-
-
-    Matrix<T>* sample(long size, bool remove = false)
-    {
-        UniqueRandom rand(rows);
-        Matrix<T> *newSet = new Matrix<T>(size,cols);
-
-        T *src,*dest;
-        for (long i=0;i<size;++i) {
-            long r = rand.next();
-            dest = (*newSet)[i];
-            src = (*this)[r];
-            for (long j=0;j<cols;++j) {
-                dest[j] = src[j];
-            }
-            if (remove) {
-                dest = (*this)[rows-i-1];
-                src = (*this)[r];
-                for (long j=0;j<cols;++j) {
-                    swap(*src,*dest);
-                    src++;
-                    dest++;
-                }
-            }
-        }
-
-        if (remove) {
-            rows -= size;
-        }
-
-        return newSet;
-    }
-
-    Matrix<T>* sample(long size) const
-    {
-        UniqueRandom rand(rows);
-        Matrix<T> *newSet = new Matrix<T>(size,cols);
-
-        T *src,*dest;
-        for (long i=0;i<size;++i) {
-            long r = rand.next();
-            dest = (*newSet)[i];
-            src = (*this)[r];
-            for (long j=0;j<cols;++j) {
-                dest[j] = src[j];
-            }
-        }
-
-        return newSet;
-    }
-
-};
-
-
-}
-
-#endif //DATASET_H
index 9d8ffb5..6e88502 100644 (file)
@@ -293,18 +293,23 @@ This section documents OpenCV's interface to the FLANN\footnote{http://people.cs
 contains a collection of algorithms optimized for fast nearest neighbor search in large datasets and for high dimensional features. More 
 information about FLANN can be found in \cite{muja_flann_2009}.
 
-\cvclass{cvflann::Index}
-The FLANN nearest neighbor index class.
+\cvclass{cv::flann::Index_}
+The FLANN nearest neighbor index class. This class is templated with the type of elements for which the index is built.
 
 \begin{lstlisting}
-namespace cvflann
+namespace cv
 {
-    class Index 
+namespace flann
+{
+    template <typename T>
+    class Index_ 
     {
     public:
-           Index(const Mat& features, const IndexParams& params);
+           Index_(const Mat& features, const IndexParams& params);
+
+           ~Index_();
 
-           void knnSearch(const vector<float>& query, 
+           void knnSearch(const vector<T>& query, 
                           vector<int>& indices, 
                           vector<float>& dists, 
                           int knn, 
@@ -315,7 +320,7 @@ namespace cvflann
                            int knn, 
                           const SearchParams& params);
 
-           int radiusSearch(const vector<float>& query, 
+           int radiusSearch(const vector<T>& query, 
                             vector<int>& indices, 
                             vector<float>& dists, 
                             float radius, 
@@ -331,16 +336,22 @@ namespace cvflann
            int veclen() const;
 
            int size() const;
+
+           const IndexParams* getIndexParameters();
     };
-}
+
+    typedef Index_<float> Index;
+
+} } // namespace cv::flann
 \end{lstlisting}
 
-\cvCppFunc{cvflann::Index::Index}
+\cvCppFunc{cv::flann::Index_<T>::Index_}
 Constructs a nearest neighbor search index for a given dataset.
 
-\cvdefCpp{Index::Index(const Mat\& features, const IndexParams\& params);}
+\cvdefCpp{Index_<T>::Index_(const Mat\& features, const IndexParams\& params);}
 \begin{description}
-\cvarg{features}{ Matrix of type CV\_32F containing the features(points) to index. The size of the matrix is num\_features x feature\_dimensionality.}
+\cvarg{features}{ Matrix of containing the features(points) to index. The size of the matrix is num\_features x feature\_dimensionality and 
+the data type of the elements in the matrix must coincide with the type of the index.}
 \cvarg{params}{Structure containing the index parameters. The type of index that will be constructed depends on the type of this parameter.
 The possible parameter types are:}
 
@@ -428,9 +439,9 @@ struct SavedIndexParams : public IndexParams
 \end{description}
 \end{description}
 
-\cvCppFunc{cvflann::Index::knnSearch}
+\cvCppFunc{cv::flann::Index_<T>::knnSearch}
 Performs a K-nearest neighbor search for a given query point using the index.
-\cvdefCpp{void Index::knnSearch(const vector<float>\& query, \par
+\cvdefCpp{void Index_<T>::knnSearch(const vector<T>\& query, \par
                vector<int>\& indices, \par
                vector<float>\& dists, \par
                int knn, \par
@@ -451,15 +462,15 @@ Performs a K-nearest neighbor search for a given query point using the index.
 \end{description}
 \end{description}
 
-\cvCppFunc{cvflann::Index::knnSearch}
+\cvCppFunc{cv::flann::Index_<T>::knnSearch}
 Performs a K-nearest neighbor search for multiple query points.
 
-\cvdefCpp{void Index::knnSearch(const Mat\& queries,\par
+\cvdefCpp{void Index_<T>::knnSearch(const Mat\& queries,\par
                Mat\& indices, Mat\& dists,\par
                int knn, const SearchParams\& params);}
 
 \begin{description}
-\cvarg{queries}{The query points, one per row}
+\cvarg{queries}{The query points, one per row. The type of queries must match the index type.}
 \cvarg{indices}{Indices of the nearest neighbors found }
 \cvarg{dists}{Distances to the nearest neighbors found}
 \cvarg{knn}{Number of nearest neighbors to search for}
@@ -467,9 +478,9 @@ Performs a K-nearest neighbor search for multiple query points.
 \end{description}
 
 
-\cvCppFunc{cvflann::Index::radiusSearch}
+\cvCppFunc{cv::flann::Index_<T>::radiusSearch}
 Performs a radius nearest neighbor search for a given query point.
-\cvdefCpp{int Index::radiusSearch(const vector<float>\& query, \par
+\cvdefCpp{int Index_<T>::radiusSearch(const vector<T>\& query, \par
                  vector<int>\& indices, \par
                  vector<float>\& dists, \par
                  float radius, \par
@@ -483,9 +494,9 @@ Performs a radius nearest neighbor search for a given query point.
 \end{description}
 
 
-\cvCppFunc{cvflann::Index::radiusSearch}
+\cvCppFunc{cv::flann::Index_<T>::radiusSearch}
 Performs a radius nearest neighbor search for multiple query points.
-\cvdefCpp{int Index::radiusSearch(const Mat\& query, \par
+\cvdefCpp{int Index_<T>::radiusSearch(const Mat\& query, \par
                  Mat\& indices, \par
                  Mat\& dists, \par
                  float radius, \par
@@ -499,21 +510,25 @@ Performs a radius nearest neighbor search for multiple query points.
 \end{description}
 
 
-\cvCppFunc{cvflann::Index::save}
+\cvCppFunc{cv::flann::Index_<T>::save}
 Saves the index to a file.
-\cvdefCpp{void Index::save(std::string filename);}
+\cvdefCpp{void Index_<T>::save(std::string filename);}
 \begin{description}
 \cvarg{filename}{The file to save the index to}
 \end{description}
 
+\cvCppFunc{cv::flann::Index_<T>::getIndexParameters}
+Returns the index paramreters. This is usefull in case of autotuned indices, when the parameters computed can be retrived using this method.
+\cvdefCpp{const IndexParams* Index_<T>::getIndexParameters();}
+
 
-\cvCppFunc{cvflann::hierarchicalClustering}
+\cvCppFunc{cv::flann::hierarchicalClustering<ET,DT>}
 Clusters the given points by constructing a hierarchical k-means tree and choosing a cut in the tree that minimizes the cluster's variance.
-\cvdefCpp{int hierarchicalClustering(const Mat\& features, Mat\& centers,\par
+\cvdefCpp{int hierarchicalClustering<ET,DT>(const Mat\& features, Mat\& centers,\par
                                       const KMeansIndexParams\& params);}
 \begin{description}
-\cvarg{features}{The points to be clustered}
-\cvarg{centers}{The centers of the clusters obtained. The number of rows in this matrix represents the number of clusters desired, however, because of the way the cut in the hierarchical tree is chosen, the number of clusters computed will be the highest number of the form \texttt{(branching-1)*k+1} that's lower than the number of clusters desired, where \texttt{branching} is the tree's branching factor (see description of the KMeansIndexParams).}
+\cvarg{features}{The points to be clustered. The matrix must have elements of type ET.}
+\cvarg{centers}{The centers of the clusters obtained. The matrix must have type DT. The number of rows in this matrix represents the number of clusters desired, however, because of the way the cut in the hierarchical tree is chosen, the number of clusters computed will be the highest number of the form \texttt{(branching-1)*k+1} that's lower than the number of clusters desired, where \texttt{branching} is the tree's branching factor (see description of the KMeansIndexParams).}
 \cvarg{params}{Parameters used in the construction of the hierarchical k-means tree}
 \end{description}
 The function returns the number of clusters computed.
index f5e53c3..0cd9dd2 100644 (file)
@@ -66,6 +66,7 @@
 #include "opencv2/imgproc/imgproc.hpp"
 #include "opencv2/video/tracking.hpp"
 #include "opencv2/features2d/features2d.hpp"
+#include "opencv2/flann/flann.hpp"
 #include "opencv2/calib3d/calib3d.hpp"
 #include "opencv2/objdetect/objdetect.hpp"
 
index 7273e16..53a0f2f 100644 (file)
@@ -5,6 +5,7 @@ endif()
 add_subdirectory(calib3d)
 add_subdirectory(core)
 add_subdirectory(features2d)
+add_subdirectory(flann)
 
 if(MSVC OR MINGW)
    if(NOT CMAKE_CL_64)
index b834651..2255f8e 100644 (file)
@@ -1 +1 @@
-define_opencv_module(contrib opencv_core opencv_imgproc opencv_calib3d opencv_features2d opencv_highgui opencv_ml opencv_video opencv_objdetect)
+define_opencv_module(contrib opencv_core opencv_imgproc opencv_calib3d opencv_features2d opencv_highgui opencv_ml opencv_video opencv_objdetect opencv_flann)
index 45fcf04..b50a407 100644 (file)
@@ -1,3 +1,3 @@
 include_directories("${CMAKE_CURRENT_SOURCE_DIR}/../../3rdparty/include")
-set(deps opencv_lapack zlib flann)
+set(deps opencv_lapack zlib)
 define_opencv_module(core ${deps})
index b65a018..d5690f0 100644 (file)
@@ -3985,6 +3985,5 @@ public:
 
 #include "opencv2/core/operations.hpp"
 #include "opencv2/core/mat.hpp"
-#include "opencv2/core/flann.hpp"      // FLANN (Fast Library for Approximate Nearest Neighbors)
 
 #endif /*__OPENCV_CORE_HPP__*/
diff --git a/modules/core/include/opencv2/core/flann.hpp b/modules/core/include/opencv2/core/flann.hpp
deleted file mode 100644 (file)
index 8a8fa47..0000000
+++ /dev/null
@@ -1,220 +0,0 @@
-/*M///////////////////////////////////////////////////////////////////////////////////////
-//
-//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
-//
-//  By downloading, copying, installing or using the software you agree to this license.
-//  If you do not agree to this license, do not download, install,
-//  copy or use the software.
-//
-//
-//                           License Agreement
-//                For Open Source Computer Vision Library
-//
-// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
-// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
-// Third party copyrights are property of their respective owners.
-//
-// Redistribution and use in source and binary forms, with or without modification,
-// are permitted provided that the following conditions are met:
-//
-//   * Redistribution's of source code must retain the above copyright notice,
-//     this list of conditions and the following disclaimer.
-//
-//   * Redistribution's in binary form must reproduce the above copyright notice,
-//     this list of conditions and the following disclaimer in the documentation
-//     and/or other materials provided with the distribution.
-//
-//   * The name of the copyright holders may not be used to endorse or promote products
-//     derived from this software without specific prior written permission.
-//
-// This software is provided by the copyright holders and contributors "as is" and
-// any express or implied warranties, including, but not limited to, the implied
-// warranties of merchantability and fitness for a particular purpose are disclaimed.
-// In no event shall the Intel Corporation or contributors be liable for any direct,
-// indirect, incidental, special, exemplary, or consequential damages
-// (including, but not limited to, procurement of substitute goods or services;
-// loss of use, data, or profits; or business interruption) however caused
-// and on any theory of liability, whether in contract, strict liability,
-// or tort (including negligence or otherwise) arising in any way out of
-// the use of this software, even if advised of the possibility of such damage.
-//
-//M*/
-
-#ifndef __OPENCV_CORE_FLANN_HPP__
-#define __OPENCV_CORE_FLANN_HPP__
-
-#ifdef __cplusplus
-
-namespace cvflann
-{
-       class Index;
-}
-
-namespace cv {
-
-namespace flann {
-
-/* Nearest neighbor index algorithms */
-enum flann_algorithm_t {
-       LINEAR = 0,
-       KDTREE = 1,
-       KMEANS = 2,
-       COMPOSITE = 3,
-       SAVED = 254,
-       AUTOTUNED = 255
-};
-
-enum flann_centers_init_t {
-       CENTERS_RANDOM = 0,
-       CENTERS_GONZALES = 1,
-       CENTERS_KMEANSPP = 2
-};
-
-
-enum flann_log_level_t {
-       LOG_NONE = 0,
-       LOG_FATAL = 1,
-       LOG_ERROR = 2,
-       LOG_WARN = 3,
-       LOG_INFO = 4
-};
-
-enum flann_distance_t {
-       EUCLIDEAN = 1,
-       MANHATTAN = 2,
-       MINKOWSKI = 3
-};
-
-class CV_EXPORTS IndexFactory
-{
-public:
-    virtual ~IndexFactory() {}
-       virtual ::cvflann::Index* createIndex(const Mat& dataset) const = 0;
-};
-
-struct CV_EXPORTS IndexParams : public IndexFactory {
-protected:
-       IndexParams() {};
-
-};
-
-struct CV_EXPORTS LinearIndexParams : public IndexParams {
-       LinearIndexParams() {};
-
-       ::cvflann::Index* createIndex(const Mat& dataset) const;
-};
-
-
-
-struct CV_EXPORTS KDTreeIndexParams : public IndexParams {
-       KDTreeIndexParams(int trees_ = 4) : trees(trees_) {};
-
-       int trees;                 // number of randomized trees to use (for kdtree)
-
-       ::cvflann::Index* createIndex(const Mat& dataset) const;
-};
-
-struct CV_EXPORTS KMeansIndexParams : public IndexParams {
-       KMeansIndexParams(int branching_ = 32, int iterations_ = 11,
-                       flann_centers_init_t centers_init_ = CENTERS_RANDOM, float cb_index_ = 0.2 ) :
-               branching(branching_),
-               iterations(iterations_),
-               centers_init(centers_init_),
-               cb_index(cb_index_) {};
-
-       int branching;             // branching factor (for kmeans tree)
-       int iterations;            // max iterations to perform in one kmeans clustering (kmeans tree)
-       flann_centers_init_t centers_init;          // algorithm used for picking the initial cluster centers for kmeans tree
-    float cb_index;            // cluster boundary index. Used when searching the kmeans tree
-
-    ::cvflann::Index* createIndex(const Mat& dataset) const;
-};
-
-
-struct CV_EXPORTS CompositeIndexParams : public IndexParams {
-       CompositeIndexParams(int trees_ = 4, int branching_ = 32, int iterations_ = 11,
-                       flann_centers_init_t centers_init_ = CENTERS_RANDOM, float cb_index_ = 0.2 ) :
-               trees(trees_),
-               branching(branching_),
-               iterations(iterations_),
-               centers_init(centers_init_),
-               cb_index(cb_index_) {};
-
-       int trees;                 // number of randomized trees to use (for kdtree)
-       int branching;             // branching factor (for kmeans tree)
-       int iterations;            // max iterations to perform in one kmeans clustering (kmeans tree)
-       flann_centers_init_t centers_init;          // algorithm used for picking the initial cluster centers for kmeans tree
-    float cb_index;            // cluster boundary index. Used when searching the kmeans tree
-
-    ::cvflann::Index* createIndex(const Mat& dataset) const;
-};
-
-
-struct CV_EXPORTS AutotunedIndexParams : public IndexParams {
-       AutotunedIndexParams( float target_precision_ = 0.9, float build_weight_ = 0.01,
-                       float memory_weight_ = 0, float sample_fraction_ = 0.1) :
-               target_precision(target_precision_),
-               build_weight(build_weight_),
-               memory_weight(memory_weight_),
-               sample_fraction(sample_fraction_) {};
-
-       float target_precision;    // precision desired (used for autotuning, -1 otherwise)
-       float build_weight;        // build tree time weighting factor
-       float memory_weight;       // index memory weighting factor
-    float sample_fraction;     // what fraction of the dataset to use for autotuning
-
-    ::cvflann::Index* createIndex(const Mat& dataset) const;
-};
-
-
-struct CV_EXPORTS SavedIndexParams : public IndexParams {
-       SavedIndexParams() {}
-       SavedIndexParams(std::string filename_) : filename(filename_) {}
-
-       std::string filename;           // filename of the stored index
-
-       ::cvflann::Index* createIndex(const Mat& dataset) const;
-};
-
-
-struct CV_EXPORTS SearchParams {
-       SearchParams(int checks_ = 32) :
-               checks(checks_) {};
-
-       int checks;
-};
-
-
-
-class CV_EXPORTS Index {
-       ::cvflann::Index* nnIndex;
-
-public:
-       Index(const Mat& features, const IndexParams& params);
-
-       ~Index();
-
-       void knnSearch(const vector<float>& queries, vector<int>& indices, vector<float>& dists, int knn, const SearchParams& params);
-       void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const SearchParams& params);
-
-       int radiusSearch(const vector<float>& query, vector<int>& indices, vector<float>& dists, float radius, const SearchParams& params);
-       int radiusSearch(const Mat& query, Mat& indices, Mat& dists, float radius, const SearchParams& params);
-
-       void save(std::string filename);
-
-       int veclen() const;
-
-       int size() const;
-};
-
-
-CV_EXPORTS int hierarchicalClustering(const Mat& features, Mat& centers,
-                                      const KMeansIndexParams& params);
-
-}
-
-}
-
-#endif // __cplusplus
-
-#endif
diff --git a/modules/core/src/flann.cpp b/modules/core/src/flann.cpp
deleted file mode 100644 (file)
index b439a26..0000000
+++ /dev/null
@@ -1,211 +0,0 @@
-/*********************************************************************
-* Software License Agreement (BSD License)
-*
-*  Copyright (c) 2009, Willow Garage, Inc.
-*  All rights reserved.
-*
-*  Redistribution and use in source and binary forms, with or without
-*  modification, are permitted provided that the following conditions
-*  are met:
-*
-*   * Redistributions of source code must retain the above copyright
-*     notice, this list of conditions and the following disclaimer.
-*   * Redistributions in binary form must reproduce the above
-*     copyright notice, this list of conditions and the following
-*     disclaimer in the documentation and/or other materials provided
-*     with the distribution.
-*   * Neither the name of the Willow Garage nor the names of its
-*     contributors may be used to endorse or promote products derived
-*     from this software without specific prior written permission.
-*
-*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
-*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
-*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
-*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
-*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-*  POSSIBILITY OF SUCH DAMAGE.
-*********************************************************************/
-
-#include "precomp.hpp"
-#include "flann/flann.hpp"
-
-namespace cv
-{
-
-namespace flann {
-
-::cvflann::Index* LinearIndexParams::createIndex(const Mat& dataset) const
-{
-       CV_Assert(dataset.type() == CV_32F);
-       CV_Assert(dataset.isContinuous());
-
-       // TODO: fix ::cvflann::Matrix class so it can be constructed with a const float*
-       ::cvflann::Matrix<float> mat(dataset.rows, dataset.cols, (float*)dataset.ptr<float>(0));
-
-       return new ::cvflann::Index(mat, ::cvflann::LinearIndexParams());
-}
-
-::cvflann::Index* KDTreeIndexParams::createIndex(const Mat& dataset) const
-{
-       CV_Assert(dataset.type() == CV_32F);
-       CV_Assert(dataset.isContinuous());
-
-       // TODO: fix ::cvflann::Matrix class so it can be constructed with a const float*
-       ::cvflann::Matrix<float> mat(dataset.rows, dataset.cols, (float*)dataset.ptr<float>(0));
-
-       return new ::cvflann::Index(mat, ::cvflann::KDTreeIndexParams(trees));
-}
-
-::cvflann::Index* KMeansIndexParams::createIndex(const Mat& dataset) const
-{
-       CV_Assert(dataset.type() == CV_32F);
-       CV_Assert(dataset.isContinuous());
-
-       // TODO: fix ::cvflann::Matrix class so it can be constructed with a const float*
-       ::cvflann::Matrix<float> mat(dataset.rows, dataset.cols, (float*)dataset.ptr<float>(0));
-
-       return new ::cvflann::Index(mat, ::cvflann::KMeansIndexParams(branching,iterations, (::flann_centers_init_t)centers_init, cb_index));
-}
-
-::cvflann::Index* CompositeIndexParams::createIndex(const Mat& dataset) const
-{
-       CV_Assert(dataset.type() == CV_32F);
-       CV_Assert(dataset.isContinuous());
-
-       // TODO: fix ::cvflann::Matrix class so it can be constructed with a const float*
-       ::cvflann::Matrix<float> mat(dataset.rows, dataset.cols, (float*)dataset.ptr<float>(0));
-
-       return new ::cvflann::Index(mat, ::cvflann::CompositeIndexParams(trees, branching, iterations, (::flann_centers_init_t)centers_init, cb_index));
-}
-
-::cvflann::Index* AutotunedIndexParams::createIndex(const Mat& dataset) const
-{
-       CV_Assert(dataset.type() == CV_32F);
-       CV_Assert(dataset.isContinuous());
-
-       // TODO: fix ::cvflann::Matrix class so it can be constructed with a const float*
-       ::cvflann::Matrix<float> mat(dataset.rows, dataset.cols, (float*)dataset.ptr<float>(0));
-
-       return new ::cvflann::Index(mat, ::cvflann::AutotunedIndexParams(target_precision, build_weight, memory_weight, sample_fraction));
-}
-
-::cvflann::Index* SavedIndexParams::createIndex(const Mat& dataset) const
-{
-       CV_Assert(dataset.type() == CV_32F);
-       CV_Assert(dataset.isContinuous());
-
-       // TODO: fix ::cvflann::Matrix class so it can be constructed with a const float*
-       ::cvflann::Matrix<float> mat(dataset.rows, dataset.cols, (float*)dataset.ptr<float>(0));
-
-       return new ::cvflann::Index(mat, ::cvflann::SavedIndexParams(filename));
-}
-
-
-
-Index::Index(const Mat& dataset, const IndexParams& params)
-{
-       nnIndex = params.createIndex(dataset);
-}
-
-Index::~Index()
-{
-       delete nnIndex;
-}
-
-void Index::knnSearch(const vector<float>& query, vector<int>& indices, vector<float>& dists, int knn, const SearchParams& searchParams)
-{
-
-       ::cvflann::Matrix<float> m_query(1, (int)query.size(), (float*)&query[0]);
-       ::cvflann::Matrix<int> m_indices(1, (int)indices.size(), &indices[0]);
-       ::cvflann::Matrix<float> m_dists(1, (int)dists.size(), &dists[0]);
-
-       nnIndex->knnSearch(m_query,m_indices,m_dists,knn,::cvflann::SearchParams(searchParams.checks));
-}
-
-
-void Index::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const SearchParams& searchParams)
-{
-
-       CV_Assert(queries.type() == CV_32F);
-       CV_Assert(queries.isContinuous());
-       ::cvflann::Matrix<float> m_queries(queries.rows, queries.cols, (float*)queries.ptr<float>(0));
-
-       CV_Assert(indices.type() == CV_32S);
-       CV_Assert(indices.isContinuous());
-       ::cvflann::Matrix<int> m_indices(indices.rows, indices.cols, (int*)indices.ptr<int>(0));
-
-       CV_Assert(dists.type() == CV_32F);
-       CV_Assert(dists.isContinuous());
-       ::cvflann::Matrix<float> m_dists(dists.rows, dists.cols, (float*)dists.ptr<float>(0));
-
-       nnIndex->knnSearch(m_queries,m_indices,m_dists,knn,::cvflann::SearchParams(searchParams.checks));
-}
-
-int Index::radiusSearch(const vector<float>& query, vector<int>& indices, vector<float>& dists, float radius, const SearchParams& searchParams)
-{
-       ::cvflann::Matrix<float> m_query(1, (int)query.size(), (float*)&query[0]);
-       ::cvflann::Matrix<int> m_indices(1, (int)indices.size(), &indices[0]);
-       ::cvflann::Matrix<float> m_dists(1, (int)dists.size(), &dists[0]);
-
-       return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,::cvflann::SearchParams(searchParams.checks));
-}
-
-
-int Index::radiusSearch(const Mat& query, Mat& indices, Mat& dists, float radius, const SearchParams& searchParams)
-{
-       CV_Assert(query.type() == CV_32F);
-       CV_Assert(query.isContinuous());
-       ::cvflann::Matrix<float> m_query(query.rows, query.cols, (float*)query.ptr<float>(0));
-
-       CV_Assert(indices.type() == CV_32S);
-       CV_Assert(indices.isContinuous());
-       ::cvflann::Matrix<int> m_indices(indices.rows, indices.cols, (int*)indices.ptr<int>(0));
-
-       CV_Assert(dists.type() == CV_32F);
-       CV_Assert(dists.isContinuous());
-       ::cvflann::Matrix<float> m_dists(dists.rows, dists.cols, (float*)dists.ptr<float>(0));
-
-       return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,::cvflann::SearchParams(searchParams.checks));
-}
-
-
-void Index::save(string filename)
-{
-       nnIndex->save(filename);
-}
-
-int Index::size() const
-{
-       return nnIndex->size();
-}
-
-int Index::veclen() const
-{
-       return nnIndex->veclen();
-}
-
-
-int hierarchicalClustering(const Mat& features, Mat& centers, const KMeansIndexParams& params)
-{
-       CV_Assert(features.type() == CV_32F);
-       CV_Assert(features.isContinuous());
-       ::cvflann::Matrix<float> m_features(features.rows, features.cols, (float*)features.ptr<float>(0));
-
-       CV_Assert(features.type() == CV_32F);
-       CV_Assert(features.isContinuous());
-       ::cvflann::Matrix<float> m_centers(centers.rows, centers.cols, (float*)centers.ptr<float>(0));
-
-       return ::cvflann::hierarchicalClustering(m_features, m_centers, ::cvflann::KMeansIndexParams(params.branching, params.iterations,
-                       (::flann_centers_init_t)params.centers_init, params.cb_index));
-}
-
-
-}
-
-}
index 7ab8c9a..ebfd436 100644 (file)
@@ -1,2 +1,2 @@
-define_opencv_module(features2d opencv_core opencv_imgproc opencv_calib3d opencv_highgui)
+define_opencv_module(features2d opencv_core opencv_imgproc opencv_calib3d opencv_highgui opencv_flann)
 
index 2adefb6..d7d1fd4 100644 (file)
@@ -44,6 +44,7 @@
 #define __OPENCV_FEATURES_2D_HPP__
 
 #include "opencv2/core/core.hpp"
+#include "opencv2/flann/flann.hpp"
 
 #ifdef __cplusplus
 #include <limits>
diff --git a/modules/flann/CMakeLists.txt b/modules/flann/CMakeLists.txt
new file mode 100644 (file)
index 0000000..79fbf0d
--- /dev/null
@@ -0,0 +1,2 @@
+define_opencv_module(flann opencv_core)
+
similarity index 58%
rename from 3rdparty/flann/saving.h
rename to modules/flann/include/opencv2/flann/all_indices.h
index 9373641..b1a826f 100644 (file)
@@ -4,8 +4,6 @@
  * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
  * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
  *
- * THE BSD LICENSE
- *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *************************************************************************/
 
-#ifndef SAVING_H_
-#define SAVING_H_
 
-#include "constants.h"
-#include "nn_index.h"
+#ifndef ALL_INDICES_H_
+#define ALL_INDICES_H_
 
+#include "opencv2/flann/general.h"
 
-namespace cvflann
-{
+#include "opencv2/flann/nn_index.h"
+#include "opencv2/flann/kdtree_index.h"
+#include "opencv2/flann/kmeans_index.h"
+#include "opencv2/flann/composite_index.h"
+#include "opencv2/flann/linear_index.h"
+#include "opencv2/flann/autotuned_index.h"
 
-/**
- * Structure representing the index header.
- */
-struct IndexHeader
+namespace cvflann 
 {
-       char signature[16];
-       int flann_version;
-       flann_algorithm_t index_type;
-       int rows;
-       int cols;
-};
-
-/**
- * Saves index header to stream
- *
- * @param stream - Stream to save to
- * @param index - The index to save
- */
-void save_header(FILE* stream, const NNIndex& index);
-
-
-/**
- *
- * @param stream - Stream to load from
- * @return Index header
- */
-IndexHeader load_header(FILE* stream);
-
 
 template<typename T>
-void save_value(FILE* stream, const T& value, int count = 1)
+NNIndex<T>* create_index_by_type(const Matrix<T>& dataset, const IndexParams& params)
 {
-       fwrite(&value, sizeof(value),count, stream);
-}
-
+       flann_algorithm_t index_type = params.getIndexType();
 
-template<typename T>
-void load_value(FILE* stream, T& value, int count = 1)
-{
-       int read_cnt = (int)fread(&value, sizeof(value),count, stream);
-       if (read_cnt!=count) {
-               throw FLANNException("Cannot read from file");
+       NNIndex<T>* nnIndex;
+       switch (index_type) {
+       case LINEAR:
+               nnIndex = new LinearIndex<T>(dataset, (const LinearIndexParams&)params);
+               break;
+       case KDTREE:
+               nnIndex = new KDTreeIndex<T>(dataset, (const KDTreeIndexParams&)params);
+               break;
+       case KMEANS:
+               nnIndex = new KMeansIndex<T>(dataset, (const KMeansIndexParams&)params);
+               break;
+       case COMPOSITE:
+               nnIndex = new CompositeIndex<T>(dataset, (const CompositeIndexParams&) params);
+               break;
+       case AUTOTUNED:
+               nnIndex = new AutotunedIndex<T>(dataset, (const AutotunedIndexParams&) params);
+               break;
+       default:
+               throw FLANNException("Unknown index type");
        }
+
+       return nnIndex;
 }
-}
 
-#endif /* SAVING_H_ */
+} //namespace cvflann
+
+#endif /* ALL_INDICES_H_ */
similarity index 97%
rename from 3rdparty/flann/allocator.h
rename to modules/flann/include/opencv2/flann/allocator.h
index 5b30a28..a7e357e 100644 (file)
@@ -34,7 +34,6 @@
 #include <stdlib.h>
 #include <stdio.h>
 
-
 namespace cvflann
 {
 
@@ -144,7 +143,7 @@ public:
                        // use the standard C malloc to allocate memory
                        void* m = ::malloc(blocksize);
                        if (!m) {
-                fprintf(stderr,"Failed to allocate memory.");
+                fprintf(stderr,"Failed to allocate memory.\n");
                 exit(1);
                        }
 
@@ -177,12 +176,12 @@ public:
     template <typename T>
        T* allocate(size_t count = 1)
        {
-               T* mem = (T*) this->malloc((int)(sizeof(T)*count));
+               T* mem = (T*) this->malloc(sizeof(T)*count);
                return mem;
        }
 
 };
 
-}
+} // namespace cvflann
 
 #endif //ALLOCATOR_H
similarity index 73%
rename from 3rdparty/flann/autotuned_index.h
rename to modules/flann/include/opencv2/flann/autotuned_index.h
index aea36ef..d7e8a71 100644 (file)
 #ifndef AUTOTUNEDINDEX_H_
 #define AUTOTUNEDINDEX_H_
 
-#include "constants.h"
-#include "nn_index.h"
-#include "ground_truth.h"
-#include "index_testing.h"
+#include "opencv2/flann/general.h"
+#include "opencv2/flann/nn_index.h"
+#include "opencv2/flann/ground_truth.h"
+#include "opencv2/flann/index_testing.h"
+#include "opencv2/flann/sampling.h"
+#include "opencv2/flann/all_indices.h"
 
 namespace cvflann
 {
 
-class AutotunedIndex : public NNIndex
+struct AutotunedIndexParams : public IndexParams {
+       AutotunedIndexParams( float target_precision_ = 0.8, float build_weight_ = 0.01,
+                       float memory_weight_ = 0, float sample_fraction_ = 0.1) :
+               IndexParams(AUTOTUNED),
+               target_precision(target_precision_),
+               build_weight(build_weight_),
+               memory_weight(memory_weight_),
+               sample_fraction(sample_fraction_) {};
+
+       float target_precision;    // precision desired (used for autotuning, -1 otherwise)
+       float build_weight;        // build tree time weighting factor
+       float memory_weight;       // index memory weighting factor
+    float sample_fraction;     // what fraction of the dataset to use for autotuning
+
+       flann_algorithm_t getIndexType() const { return algorithm; }
+
+       void print() const
+       {
+               logger.info("Index type: %d\n",(int)algorithm);
+               logger.info("Target precision: %g\n", target_precision);
+               logger.info("Build weight: %g\n", build_weight);
+               logger.info("Memory weight: %g\n", memory_weight);
+               logger.info("Sample fraction: %g\n", sample_fraction);
+       }
+};
+
+
+template <typename ELEM_TYPE, typename DIST_TYPE = typename DistType<ELEM_TYPE>::type >
+class AutotunedIndex : public NNIndex<ELEM_TYPE>
 {
-       NNIndex* bestIndex;
+       NNIndex<ELEM_TYPE>* bestIndex;
+
        IndexParams* bestParams;
        SearchParams bestSearchParams;
 
-    Matrix<float>* sampledDataset;
-    Matrix<float>* testDataset;
-    Matrix<int>* gt_matches;
+    Matrix<ELEM_TYPE> sampledDataset;
+    Matrix<ELEM_TYPE> testDataset;
+    Matrix<int> gt_matches;
 
     float speedup;
 
        /**
         * The dataset used by this index
         */
-    const Matrix<float> dataset;
+    const Matrix<ELEM_TYPE> dataset;
 
     /**
      * Index parameters
      */
-    const AutotunedIndexParams& params;
-
-    /**
-    * Number of features in the dataset.
-    */
-    int size_;
-
-    /**
-    * Length of each feature.
-    */
-    int veclen_;
-
+    const AutotunedIndexParams& index_params;
 
 public:
 
-    AutotunedIndex(const Matrix<float>& inputData, const AutotunedIndexParams& params_ = AutotunedIndexParams() ) :
-       dataset(inputData), params(params_)
+    AutotunedIndex(const Matrix<ELEM_TYPE>& inputData, const AutotunedIndexParams& params = AutotunedIndexParams() ) :
+       dataset(inputData), index_params(params)
        {
-        size_ = dataset.rows;
-        veclen_ = dataset.cols;
-
         bestIndex = NULL;
-
+        bestParams = NULL;
        }
 
     virtual ~AutotunedIndex()
     {
-       delete bestIndex;
-       delete bestParams;
+       if (bestIndex!=NULL) {
+               delete bestIndex;
+       }
+       if (bestParams!=NULL) {
+               delete bestParams;
+       }
     };
 
-       /**
+    /**
                Method responsible with building the index.
        */
        virtual void buildIndex()
        {
                bestParams = estimateBuildParams();
-               bestIndex = bestParams->createIndex(dataset);
+               logger.info("----------------------------------------------------\n");
+               logger.info("Autotuned parameters:\n");
+               bestParams->print();
+               logger.info("----------------------------------------------------\n");
+       flann_algorithm_t index_type = bestParams->getIndexType();
+       switch (index_type) {
+       case LINEAR:
+               bestIndex = new LinearIndex<ELEM_TYPE>(dataset, (const LinearIndexParams&)*bestParams);
+               break;
+       case KDTREE:
+               bestIndex = new KDTreeIndex<ELEM_TYPE>(dataset, (const KDTreeIndexParams&)*bestParams);
+               break;
+       case KMEANS:
+               bestIndex = new KMeansIndex<ELEM_TYPE>(dataset, (const KMeansIndexParams&)*bestParams);
+               break;
+       default:
+               throw FLANNException("Unknown algorithm choosen by the autotuning, most likely a bug.");
+       }
                bestIndex->buildIndex();
                speedup = estimateSearchParams(bestSearchParams);
        }
@@ -106,7 +144,9 @@ public:
     */
     virtual void saveIndex(FILE* stream)
     {
+       save_value(stream, (int)bestIndex->getType());
        bestIndex->saveIndex(stream);
+       save_value(stream, bestSearchParams);
     }
 
     /**
@@ -114,21 +154,38 @@ public:
     */
     virtual void loadIndex(FILE* stream)
     {
+       int index_type;
+       load_value(stream,index_type);
+       IndexParams* params = ParamsFactory::instance().create((flann_algorithm_t)index_type);
+       bestIndex = create_index_by_type(dataset, *params);
        bestIndex->loadIndex(stream);
+       load_value(stream, bestSearchParams);
     }
 
        /**
                Method that searches for nearest-neighbors
        */
-       virtual void findNeighbors(ResultSet& result, const float* vec, const SearchParams& /*searchParams*/)
+       virtual void findNeighbors(ResultSet<ELEM_TYPE>& result, const ELEM_TYPE* vec, const SearchParams& searchParams)
+       {
+               if (searchParams.checks==-2) {
+                       bestIndex->findNeighbors(result, vec, bestSearchParams);
+               }
+               else {
+                       bestIndex->findNeighbors(result, vec, searchParams);
+               }
+       }
+
+
+       const IndexParams* getParameters() const
        {
-               bestIndex->findNeighbors(result, vec, bestSearchParams);
+               return bestIndex->getParameters();
        }
 
+
        /**
                Number of features in this index.
        */
-       virtual int size() const
+       virtual size_t size() const
        {
                return bestIndex->size();
        }
@@ -136,7 +193,7 @@ public:
        /**
                The length of each vector in this index.
        */
-       virtual int veclen() const
+       virtual size_t veclen() const
        {
                return bestIndex->veclen();
        }
@@ -154,19 +211,9 @@ public:
     */
     virtual flann_algorithm_t getType() const
     {
-       return bestIndex->getType();
+       return AUTOTUNED;
     }
 
-    /**
-      Estimates the search parameters required in order to get a certain precision.
-      If testset is not given it uses cross-validation.
-    */
-//    virtual Params estimateSearchParams(float precision, Dataset<float>* testset = NULL)
-//    {
-//        Params params;
-//
-//        return params;
-//    }
 private:
 
     struct CostData {
@@ -188,22 +235,22 @@ private:
         const int nn = 1;
 
         logger.info("KMeansTree using params: max_iterations=%d, branching=%d\n", kmeans_params.iterations, kmeans_params.branching);
-        KMeansIndex kmeans(*sampledDataset, kmeans_params);
+        KMeansIndex<ELEM_TYPE> kmeans(sampledDataset, kmeans_params);
         // measure index build time
         t.start();
         kmeans.buildIndex();
         t.stop();
-        float buildTime = (float)t.value;
+        float buildTime = t.value;
 
         // measure search time
-        float searchTime = test_index_precision(kmeans, *sampledDataset, *testDataset, *gt_matches, params.target_precision, checks, nn);;
+        float searchTime = test_index_precision(kmeans, sampledDataset, testDataset, gt_matches, index_params.target_precision, checks, nn);;
 
-        float datasetMemory = (float)(sampledDataset->rows*sampledDataset->cols*sizeof(float));
+        float datasetMemory = sampledDataset.rows*sampledDataset.cols*sizeof(float);
         cost.memoryCost = (kmeans.usedMemory()+datasetMemory)/datasetMemory;
         cost.searchTimeCost = searchTime;
         cost.buildTimeCost = buildTime;
-        cost.timeCost = (buildTime*params.build_weight+searchTime);
-        logger.info("KMeansTree buildTime=%g, searchTime=%g, timeCost=%g, buildTimeFactor=%g\n",buildTime, searchTime, cost.timeCost, params.build_weight);
+        cost.timeCost = (buildTime*index_params.build_weight+searchTime);
+        logger.info("KMeansTree buildTime=%g, searchTime=%g, timeCost=%g, buildTimeFactor=%g\n",buildTime, searchTime, cost.timeCost, index_params.build_weight);
     }
 
 
@@ -214,21 +261,21 @@ private:
         const int nn = 1;
 
         logger.info("KDTree using params: trees=%d\n",kdtree_params.trees);
-        KDTreeIndex kdtree(*sampledDataset, kdtree_params);
+        KDTreeIndex<ELEM_TYPE> kdtree(sampledDataset, kdtree_params);
 
         t.start();
         kdtree.buildIndex();
         t.stop();
-        float buildTime = (float)t.value;
+        float buildTime = t.value;
 
         //measure search time
-        float searchTime = test_index_precision(kdtree, *sampledDataset, *testDataset, *gt_matches, params.target_precision, checks, nn);
+        float searchTime = test_index_precision(kdtree, sampledDataset, testDataset, gt_matches, index_params.target_precision, checks, nn);
 
-        float datasetMemory = (float)(sampledDataset->rows*sampledDataset->cols*sizeof(float));
+        float datasetMemory = sampledDataset.rows*sampledDataset.cols*sizeof(float);
         cost.memoryCost = (kdtree.usedMemory()+datasetMemory)/datasetMemory;
         cost.searchTimeCost = searchTime;
         cost.buildTimeCost = buildTime;
-        cost.timeCost = (buildTime*params.build_weight+searchTime);
+        cost.timeCost = (buildTime*index_params.build_weight+searchTime);
         logger.info("KDTree buildTime=%g, searchTime=%g, timeCost=%g\n",buildTime, searchTime, cost.timeCost);
     }
 
@@ -301,8 +348,8 @@ private:
             for (size_t j=0; j<ARRAY_LEN(branchingFactors); ++j) {
 
                kmeansCosts[cnt].second.centers_init = CENTERS_RANDOM;
+               kmeansCosts[cnt].second.iterations = maxIterations[i];
                kmeansCosts[cnt].second.branching = branchingFactors[j];
-               kmeansCosts[cnt].second.iterations = maxIterations[j];
 
                 evaluate_kmeans(kmeansCosts[cnt].first, kmeansCosts[cnt].second);
 
@@ -340,7 +387,7 @@ private:
         float optTimeCost = kmeansCosts[0].first.timeCost;
         // recompute total costs factoring in the memory costs
         for (int i=0;i<kmeansParamSpaceSize;++i) {
-            kmeansCosts[i].first.totalCost = (kmeansCosts[i].first.timeCost/optTimeCost + params.memory_weight * kmeansCosts[i].first.memoryCost);
+            kmeansCosts[i].first.totalCost = (kmeansCosts[i].first.timeCost/optTimeCost + index_params.memory_weight * kmeansCosts[i].first.memoryCost);
 
             int k = i;
             while (k>0 && kmeansCosts[k].first.totalCost < kmeansCosts[k-1].first.totalCost) {
@@ -410,7 +457,7 @@ private:
         float optTimeCost = kdtreeCosts[0].first.timeCost;
         // recompute costs for kd-tree factoring in memory cost
         for (size_t i=0;i<kdtreeParamSpaceSize;++i) {
-            kdtreeCosts[i].first.totalCost = (kdtreeCosts[i].first.timeCost/optTimeCost + params.memory_weight * kdtreeCosts[i].first.memoryCost);
+            kdtreeCosts[i].first.totalCost = (kdtreeCosts[i].first.timeCost/optTimeCost + index_params.memory_weight * kdtreeCosts[i].first.memoryCost);
 
             int k = i;
             while (k>0 && kdtreeCosts[k].first.totalCost < kdtreeCosts[k-1].first.totalCost) {
@@ -436,7 +483,7 @@ private:
     */
     IndexParams* estimateBuildParams()
     {
-        int sampleSize = int(params.sample_fraction*dataset.rows);
+        int sampleSize = int(index_params.sample_fraction*dataset.rows);
         int testSampleSize = min(sampleSize/10, 1000);
 
         logger.info("Entering autotuning, dataset size: %d, sampleSize: %d, testSampleSize: %d\n",dataset.rows, sampleSize, testSampleSize);
@@ -449,18 +496,18 @@ private:
         }
 
         // We use a fraction of the original dataset to speedup the autotune algorithm
-        sampledDataset = dataset.sample(sampleSize);
+        sampledDataset = random_sample(dataset,sampleSize);
         // We use a cross-validation approach, first we sample a testset from the dataset
-        testDataset = sampledDataset->sample(testSampleSize,true);
+        testDataset = random_sample(sampledDataset,testSampleSize,true);
 
         // We compute the ground truth using linear search
         logger.info("Computing ground truth... \n");
-        gt_matches = new Matrix<int>(testDataset->rows, 1);
+        gt_matches = Matrix<int>(new int[testDataset.rows],testDataset.rows, 1);
         StartStopTimer t;
         t.start();
-        compute_ground_truth(*sampledDataset, *testDataset, *gt_matches, 0);
+        compute_ground_truth(sampledDataset, testDataset, gt_matches, 0);
         t.stop();
-        float bestCost = (float)t.value;
+        float bestCost = t.value;
         IndexParams* bestParams = new LinearIndexParams();
 
         // Start parameter autotune process
@@ -468,7 +515,6 @@ private:
 
 
         KMeansCostData kmeansCost = optimizeKMeans();
-
         if (kmeansCost.first.totalCost<bestCost) {
             bestParams = new KMeansIndexParams(kmeansCost.second);
             bestCost = kmeansCost.first.totalCost;
@@ -481,10 +527,9 @@ private:
             bestCost = kdtreeCost.first.totalCost;
         }
 
-        // free the memory used by the datasets we sampled
-        delete sampledDataset;
-        delete testDataset;
-        delete gt_matches;
+        gt_matches.free();
+        sampledDataset.free();
+        testDataset.free();
 
         return bestParams;
     }
@@ -499,7 +544,7 @@ private:
     float estimateSearchParams(SearchParams& searchParams)
     {
         const int nn = 1;
-        const long SAMPLE_COUNT = 1000;
+        const size_t SAMPLE_COUNT = 1000;
 
         assert(bestIndex!=NULL);   // must have a valid index
 
@@ -507,17 +552,17 @@ private:
 
         int samples = min(dataset.rows/10, SAMPLE_COUNT);
         if (samples>0) {
-            Matrix<float>* testDataset = dataset.sample(samples);
+            Matrix<ELEM_TYPE> testDataset = random_sample(dataset,samples);
 
             logger.info("Computing ground truth\n");
 
             // we need to compute the ground truth first
-            Matrix<int> gt_matches(testDataset->rows,1);
+            Matrix<int> gt_matches(new int[testDataset.rows],testDataset.rows,1);
             StartStopTimer t;
             t.start();
-            compute_ground_truth(dataset, *testDataset, gt_matches,1);
+            compute_ground_truth(dataset, testDataset, gt_matches,1);
             t.stop();
-            float linear = (float)t.value;
+            float linear = t.value;
 
             int checks;
             logger.info("Estimating number of checks\n");
@@ -525,15 +570,14 @@ private:
             float searchTime;
             float cb_index;
             if (bestIndex->getType() == KMEANS) {
-
                 logger.info("KMeans algorithm, estimating cluster border factor\n");
-                KMeansIndex* kmeans = (KMeansIndex*)bestIndex;
+                KMeansIndex<ELEM_TYPE>* kmeans = (KMeansIndex<ELEM_TYPE>*)bestIndex;
                 float bestSearchTime = -1;
                 float best_cb_index = -1;
                 int best_checks = -1;
-                for (cb_index = 0;cb_index<1.1f; cb_index+=0.2f) {
+                for (cb_index = 0;cb_index<1.1; cb_index+=0.2) {
                     kmeans->set_cb_index(cb_index);
-                    searchTime = test_index_precision(*kmeans, dataset, *testDataset, gt_matches, params.target_precision, checks, nn, 1);
+                    searchTime = test_index_precision(*kmeans, dataset, testDataset, gt_matches, index_params.target_precision, checks, nn, 1);
                     if (searchTime<bestSearchTime || bestSearchTime == -1) {
                         bestSearchTime = searchTime;
                         best_cb_index = cb_index;
@@ -549,23 +593,22 @@ private:
                 ((KMeansIndexParams*)bestParams)->cb_index = cb_index;
             }
             else {
-                searchTime = test_index_precision(*bestIndex, dataset, *testDataset, gt_matches, params.target_precision, checks, nn, 1);
+                searchTime = test_index_precision(*bestIndex, dataset, testDataset, gt_matches, index_params.target_precision, checks, nn, 1);
             }
 
             logger.info("Required number of checks: %d \n",checks);;
             searchParams.checks = checks;
-            delete testDataset;
 
             speedup = linear/searchTime;
+
+            gt_matches.free();
         }
 
         return speedup;
     }
 
-
-
 };
 
-}
+} // namespace cvflann
 
 #endif /* AUTOTUNEDINDEX_H_ */
similarity index 51%
rename from 3rdparty/flann/composite_index.h
rename to modules/flann/include/opencv2/flann/composite_index.h
index 312ef4a..d3eccd1 100644 (file)
 #ifndef COMPOSITETREE_H
 #define COMPOSITETREE_H
 
-#include "constants.h"
-#include "nn_index.h"
+#include "opencv2/flann/general.h"
+#include "opencv2/flann/nn_index.h"
 
 namespace cvflann
 {
 
-class CompositeIndex : public NNIndex
+
+struct CompositeIndexParams : public IndexParams {
+       CompositeIndexParams(int trees_ = 4, int branching_ = 32, int iterations_ = 11,
+                       flann_centers_init_t centers_init_ = CENTERS_RANDOM, float cb_index_ = 0.2 ) :
+               IndexParams(COMPOSITE),
+               trees(trees_),
+               branching(branching_),
+               iterations(iterations_),
+               centers_init(centers_init_),
+               cb_index(cb_index_) {};
+
+       int trees;                 // number of randomized trees to use (for kdtree)
+       int branching;             // branching factor (for kmeans tree)
+       int iterations;            // max iterations to perform in one kmeans clustering (kmeans tree)
+       flann_centers_init_t centers_init;          // algorithm used for picking the initial cluster centers for kmeans tree
+    float cb_index;            // cluster boundary index. Used when searching the kmeans tree
+
+       flann_algorithm_t getIndexType() const { return algorithm; }
+
+       void print() const
+       {
+               logger.info("Index type: %d\n",(int)algorithm);
+               logger.info("Trees: %d\n", trees);
+               logger.info("Branching: %d\n", branching);
+               logger.info("Iterations: %d\n", iterations);
+               logger.info("Centres initialisation: %d\n", centers_init);
+               logger.info("Cluster boundary weight: %g\n", cb_index);
+       }
+};
+
+
+
+template <typename ELEM_TYPE, typename DIST_TYPE = typename DistType<ELEM_TYPE>::type >
+class CompositeIndex : public NNIndex<ELEM_TYPE>
 {
-       KMeansIndex* kmeans;
-       KDTreeIndex* kdtree;
+       KMeansIndex<ELEM_TYPE, DIST_TYPE>* kmeans;
+       KDTreeIndex<ELEM_TYPE, DIST_TYPE>* kdtree;
 
-    const Matrix<float> dataset;
+    const Matrix<ELEM_TYPE> dataset;
+
+    const IndexParams& index_params;
 
 
 public:
 
-       CompositeIndex(const Matrix<float>& inputData, const CompositeIndexParams& params = CompositeIndexParams() ) : dataset(inputData)
+       CompositeIndex(const Matrix<ELEM_TYPE>& inputData, const CompositeIndexParams& params = CompositeIndexParams() ) :
+               dataset(inputData), index_params(params)
        {
                KDTreeIndexParams kdtree_params(params.trees);
                KMeansIndexParams kmeans_params(params.branching, params.iterations, params.centers_init, params.cb_index);
 
-               kdtree = new KDTreeIndex(inputData,kdtree_params);
-               kmeans = new KMeansIndex(inputData,kmeans_params);
+               kdtree = new KDTreeIndex<ELEM_TYPE, DIST_TYPE>(inputData,kdtree_params);
+               kmeans = new KMeansIndex<ELEM_TYPE, DIST_TYPE>(inputData,kmeans_params);
 
        }
 
@@ -70,12 +106,12 @@ public:
     }
 
 
-       int size() const
+    size_t size() const
        {
                return dataset.rows;
        }
 
-       int veclen() const
+       size_t veclen() const
        {
                return dataset.cols;
        }
@@ -95,34 +131,33 @@ public:
        }
 
 
-    void saveIndex(FILE* /*stream*/)
+    void saveIndex(FILE* stream)
     {
-
+       kmeans->saveIndex(stream);
+       kdtree->saveIndex(stream);
     }
 
 
-    void loadIndex(FILE* /*stream*/)
+    void loadIndex(FILE* stream)
     {
-
+       kmeans->loadIndex(stream);
+       kdtree->loadIndex(stream);
     }
 
-       void findNeighbors(ResultSet& result, const float* vec, const SearchParams& searchParams)
+       void findNeighbors(ResultSet<ELEM_TYPE>& result, const ELEM_TYPE* vec, const SearchParams& searchParams)
        {
                kmeans->findNeighbors(result,vec,searchParams);
                kdtree->findNeighbors(result,vec,searchParams);
        }
 
-
-//    Params estimateSearchParams(float precision, Dataset<float>* testset = NULL)
-//    {
-//        Params params;
-//
-//        return params;
-//    }
+       const IndexParams* getParameters() const
+       {
+               return &index_params;
+       }
 
 
 };
 
-}
+} // namespace cvflann
 
 #endif //COMPOSITETREE_H
similarity index 56%
rename from 3rdparty/flann/dist.h
rename to modules/flann/include/opencv2/flann/dist.h
index 444508d..5de56e5 100644 (file)
@@ -34,7 +34,7 @@
 #include <cmath>
 using namespace std;
 
-#include "constants.h"
+#include "opencv2/flann/general.h"
 
 namespace cvflann
 {
@@ -82,6 +82,9 @@ double euclidean_dist(Iterator1 first1, Iterator1 last1, Iterator2 first2, doubl
        return distsq;
 }
 
+double euclidean_dist(const unsigned char* first1, const unsigned char* last1, unsigned char* first2, double acc);
+
+
 /**
  *  Compute the Manhattan (L_1) distance between two vectors.
  *
@@ -152,6 +155,142 @@ double minkowski_dist(Iterator1 first1, Iterator1 last1, Iterator2 first2, doubl
 }
 
 
+// L_infinity distance (NOT A VALID KD-TREE DISTANCE - NOT DIMENSIONWISE ADDITIVE)
+template <typename Iterator1, typename Iterator2>
+double max_dist(Iterator1 first1, Iterator1 last1, Iterator2 first2, double acc = 0)
+{
+       double dist = acc;
+       Iterator1 lastgroup = last1 - 3;
+       double diff0, diff1, diff2, diff3;
+
+       /* Process 4 items with each loop for efficiency. */
+       while (first1 < lastgroup) {
+               diff0 = fabs(first1[0] - first2[0]);
+               diff1 = fabs(first1[1] - first2[1]);
+               diff2 = fabs(first1[2] - first2[2]);
+               diff3 = fabs(first1[3] - first2[3]);
+               if (diff0 > dist) dist = diff0;
+               if (diff1 > dist) dist = diff1;
+               if (diff2 > dist) dist = diff2;
+               if (diff3 > dist) dist = diff3;
+               first1 += 4;
+               first2 += 4;
+       }
+       /* Process last 0-3 pixels.  Not needed for standard vector lengths. */
+       while (first1 < last1) {
+               diff0 = fabs(*first1++ - *first2++);
+               dist = (diff0 > dist) ? diff0 : dist;
+       }
+       return dist;
+}
+
+
+template <typename Iterator1, typename Iterator2>
+double hist_intersection_kernel(Iterator1 first1, Iterator1 last1, Iterator2 first2)
+{
+       double kernel = 0;
+       Iterator1 lastgroup = last1 - 3;
+       double min0, min1, min2, min3;
+
+       /* Process 4 items with each loop for efficiency. */
+       while (first1 < lastgroup) {
+               min0 = first1[0] < first2[0] ? first1[0] : first2[0];
+               min1 = first1[1] < first2[1] ? first1[1] : first2[1];
+               min2 = first1[2] < first2[2] ? first1[2] : first2[2];
+               min3 = first1[3] < first2[3] ? first1[3] : first2[3];
+               kernel += min0 + min1 + min2 + min3;
+               first1 += 4;
+               first2 += 4;
+       }
+       /* Process last 0-3 pixels.  Not needed for standard vector lengths. */
+       while (first1 < last1) {
+               min0 = first1[0] < first2[0] ? first1[0] : first2[0];
+               kernel += min0;
+               first1++;
+               first2++;
+       }
+       return kernel;
+}
+
+template <typename Iterator1, typename Iterator2>
+double hist_intersection_dist_sq(Iterator1 first1, Iterator1 last1, Iterator2 first2, double acc = 0)
+{
+       double dist_sq = acc - 2 * hist_intersection_kernel(first1, last1, first2);
+       while (first1 < last1) {
+               dist_sq += *first1 + *first2;
+               first1++;
+               first2++;
+       }
+       return dist_sq;
+}
+
+
+// Hellinger distance
+template <typename Iterator1, typename Iterator2>
+double hellinger_dist(Iterator1 first1, Iterator1 last1, Iterator2 first2, double acc = 0)
+{
+       double distsq = acc;
+       double diff0, diff1, diff2, diff3;
+       Iterator1 lastgroup = last1 - 3;
+
+       /* Process 4 items with each loop for efficiency. */
+       while (first1 < lastgroup) {
+               diff0 = sqrt(first1[0]) - sqrt(first2[0]);
+               diff1 = sqrt(first1[1]) - sqrt(first2[1]);
+               diff2 = sqrt(first1[2]) - sqrt(first2[2]);
+               diff3 = sqrt(first1[3]) - sqrt(first2[3]);
+               distsq += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3;
+               first1 += 4;
+               first2 += 4;
+       }
+       /* Process last 0-3 pixels.  Not needed for standard vector lengths. */
+       while (first1 < last1) {
+               diff0 = sqrt(*first1++) - sqrt(*first2++);
+               distsq += diff0 * diff0;
+       }
+       return distsq;
+}
+
+
+// chi-dsquare distance
+template <typename Iterator1, typename Iterator2>
+double chi_square_dist(Iterator1 first1, Iterator1 last1, Iterator2 first2, double acc = 0)
+{
+       double dist = acc;
+
+       while (first1 < last1) {
+               double sum = *first1 + *first2;
+               if (sum > 0) {
+                       double diff = *first1 - *first2;
+                       dist += diff * diff / sum;
+               }
+               first1++;
+               first2++;
+       }
+       return dist;
+}
+
+
+// Kullback–Leibler divergence (NOT SYMMETRIC)
+template <typename Iterator1, typename Iterator2>
+double kl_divergence(Iterator1 first1, Iterator1 last1, Iterator2 first2, double acc = 0)
+{
+       double div = acc;
+
+       while (first1 < last1) {
+               if (*first2 != 0) {
+                       double ratio = *first1 / *first2;
+                       if (ratio > 0) {
+                               div += *first1 * log(ratio);
+                       }
+               }
+               first1++;
+               first2++;
+       }
+       return div;
+}
+
+
 
 
 extern flann_distance_t flann_distance_type;
@@ -163,17 +302,27 @@ extern flann_distance_t flann_distance_type;
  * of this argument.
  */
 template <typename Iterator1, typename Iterator2>
-float custom_dist(Iterator1 first1, Iterator1 last1, Iterator2 first2, double acc = 0)
+double custom_dist(Iterator1 first1, Iterator1 last1, Iterator2 first2, double acc = 0)
 {
        switch (flann_distance_type) {
        case EUCLIDEAN:
-               return (float)euclidean_dist(first1, last1, first2, acc);
+               return euclidean_dist(first1, last1, first2, acc);
        case MANHATTAN:
-               return (float)manhattan_dist(first1, last1, first2, acc);
+               return manhattan_dist(first1, last1, first2, acc);
        case MINKOWSKI:
-               return (float)minkowski_dist(first1, last1, first2, acc);
+               return minkowski_dist(first1, last1, first2, acc);
+       case MAX_DIST:
+               return max_dist(first1, last1, first2, acc);
+       case HIK:
+               return hist_intersection_dist_sq(first1, last1, first2, acc);
+       case HELLINGER:
+               return hellinger_dist(first1, last1, first2, acc);
+       case CS:
+               return chi_square_dist(first1, last1, first2, acc);
+       case KL:
+               return kl_divergence(first1, last1, first2, acc);
        default:
-               return (float)euclidean_dist(first1, last1, first2, acc);
+               return euclidean_dist(first1, last1, first2, acc);
        }
 }
 
@@ -191,7 +340,7 @@ struct ZeroIterator {
                return 0;
        }
 
-       T operator[](int /*index*/) {
+       T operator[](int index) {
                return 0;
        }
 
@@ -206,6 +355,6 @@ struct ZeroIterator {
 };
 extern ZeroIterator<float> zero;
 
-}
+} // namespace cvflann
 
 #endif //DIST_H
diff --git a/modules/flann/include/opencv2/flann/flann.hpp b/modules/flann/include/opencv2/flann/flann.hpp
new file mode 100644 (file)
index 0000000..15484c8
--- /dev/null
@@ -0,0 +1,196 @@
+/*M///////////////////////////////////////////////////////////////////////////////////////
+//
+//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
+//
+//  By downloading, copying, installing or using the software you agree to this license.
+//  If you do not agree to this license, do not download, install,
+//  copy or use the software.
+//
+//
+//                           License Agreement
+//                For Open Source Computer Vision Library
+//
+// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
+// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
+// Third party copyrights are property of their respective owners.
+//
+// Redistribution and use in source and binary forms, with or without modification,
+// are permitted provided that the following conditions are met:
+//
+//   * Redistribution's of source code must retain the above copyright notice,
+//     this list of conditions and the following disclaimer.
+//
+//   * Redistribution's in binary form must reproduce the above copyright notice,
+//     this list of conditions and the following disclaimer in the documentation
+//     and/or other materials provided with the distribution.
+//
+//   * The name of the copyright holders may not be used to endorse or promote products
+//     derived from this software without specific prior written permission.
+//
+// This software is provided by the copyright holders and contributors "as is" and
+// any express or implied warranties, including, but not limited to, the implied
+// warranties of merchantability and fitness for a particular purpose are disclaimed.
+// In no event shall the Intel Corporation or contributors be liable for any direct,
+// indirect, incidental, special, exemplary, or consequential damages
+// (including, but not limited to, procurement of substitute goods or services;
+// loss of use, data, or profits; or business interruption) however caused
+// and on any theory of liability, whether in contract, strict liability,
+// or tort (including negligence or otherwise) arising in any way out of
+// the use of this software, even if advised of the possibility of such damage.
+//
+//M*/
+
+#ifndef __OPENCV_FLANN_HPP__
+#define __OPENCV_FLANN_HPP__
+
+#ifdef __cplusplus
+
+#include "opencv2/flann/flann_base.hpp"
+
+namespace cv
+{
+namespace flann
+{
+
+template <typename T> struct CvType {};
+template <> struct CvType<unsigned char> { static int type() { return CV_8U; } };
+template <> struct CvType<char> { static int type() { return CV_8S; } };
+template <> struct CvType<unsigned short> { static int type() { return CV_16U; } };
+template <> struct CvType<short> { static int type() { return CV_16S; } };
+template <> struct CvType<int> { static int type() { return CV_32S; } };
+template <> struct CvType<float> { static int type() { return CV_32F; } };
+template <> struct CvType<double> { static int type() { return CV_64F; } };
+
+    
+using ::cvflann::IndexParams;
+using ::cvflann::LinearIndexParams;
+using ::cvflann::KDTreeIndexParams;
+using ::cvflann::KMeansIndexParams;
+using ::cvflann::CompositeIndexParams;
+using ::cvflann::AutotunedIndexParams;
+using ::cvflann::SavedIndexParams;
+
+using ::cvflann::SearchParams;
+
+
+template <typename T>
+class Index_ {
+       ::cvflann::Index<T>* nnIndex;
+
+public:
+       Index_(const Mat& features, const IndexParams& params);
+
+       ~Index_();
+
+       void knnSearch(const vector<T>& query, vector<int>& indices, vector<float>& dists, int knn, const SearchParams& params);
+       void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const SearchParams& params);
+
+       int radiusSearch(const vector<T>& query, vector<int>& indices, vector<float>& dists, float radius, const SearchParams& params);
+       int radiusSearch(const Mat& query, Mat& indices, Mat& dists, float radius, const SearchParams& params);
+
+       void save(std::string filename) { nnIndex->save(filename); }
+
+       int veclen() const { return nnIndex->veclen(); }
+
+       int size() const { return nnIndex->size(); }
+
+       const IndexParams* getIndexParameters() { return nnIndex->getParameters(); }
+
+};
+
+
+template <typename T>
+Index_<T>::Index_(const Mat& dataset, const IndexParams& params)
+{
+    CV_Assert(dataset.type() == CvType<T>::type());
+    CV_Assert(dataset.isContinuous());
+    ::cvflann::Matrix<float> m_dataset((T*)dataset.ptr<T>(0), dataset.rows, dataset.cols);
+    
+    nnIndex = new ::cvflann::Index<T>(m_dataset, params);
+    nnIndex->buildIndex();
+}
+
+template <typename T>
+Index_<T>::~Index_()
+{
+    delete nnIndex;
+}
+
+template <typename T>
+void Index_<T>::knnSearch(const vector<T>& query, vector<int>& indices, vector<float>& dists, int knn, const SearchParams& searchParams)
+{
+    ::cvflann::Matrix<T> m_query((T*)&query[0], 1, (int)query.size());
+    ::cvflann::Matrix<int> m_indices(&indices[0], 1, (int)indices.size());
+    ::cvflann::Matrix<float> m_dists(&dists[0], 1, (int)dists.size());
+    
+    nnIndex->knnSearch(m_query,m_indices,m_dists,knn,searchParams);
+}
+
+
+template <typename T>
+void Index_<T>::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const SearchParams& searchParams)
+{
+    CV_Assert(queries.type() == CvType<T>::type());
+    CV_Assert(queries.isContinuous());
+    ::cvflann::Matrix<T> m_queries((T*)queries.ptr<T>(0), queries.rows, queries.cols);
+    
+    CV_Assert(indices.type() == CV_32S);
+    CV_Assert(indices.isContinuous());
+    ::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
+    
+    CV_Assert(dists.type() == CV_32F);
+    CV_Assert(dists.isContinuous());
+    ::cvflann::Matrix<float> m_dists((float*)dists.ptr<float>(0), dists.rows, dists.cols);
+    
+    nnIndex->knnSearch(m_queries,m_indices,m_dists,knn, searchParams);
+}
+
+template <typename T>
+int Index_<T>::radiusSearch(const vector<T>& query, vector<int>& indices, vector<float>& dists, float radius, const SearchParams& searchParams)
+{
+    ::cvflann::Matrix<T> m_query((T*)&query[0], 1, (int)query.size());
+    ::cvflann::Matrix<int> m_indices(&indices[0], 1, (int)indices.size());
+    ::cvflann::Matrix<float> m_dists(&dists[0], 1, (int)dists.size());
+    
+    return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
+}
+
+template <typename T>
+int Index_<T>::radiusSearch(const Mat& query, Mat& indices, Mat& dists, float radius, const SearchParams& searchParams)
+{
+    CV_Assert(query.type() == CvType<T>::type());
+    CV_Assert(query.isContinuous());
+    ::cvflann::Matrix<T> m_query((T*)query.ptr<T>(0), query.rows, query.cols);
+    
+    CV_Assert(indices.type() == CV_32S);
+    CV_Assert(indices.isContinuous());
+    ::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
+    
+    CV_Assert(dists.type() == CV_32F);
+    CV_Assert(dists.isContinuous());
+    ::cvflann::Matrix<float> m_dists((float*)dists.ptr<float>(0), dists.rows, dists.cols);
+    
+    return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
+}
+
+typedef Index_<float> Index;
+
+template <typename ELEM_TYPE, typename DIST_TYPE>
+int hierarchicalClustering(const Mat& features, Mat& centers, const KMeansIndexParams& params)
+{
+    CV_Assert(features.type() == CvType<ELEM_TYPE>::type());
+    CV_Assert(features.isContinuous());
+    ::cvflann::Matrix<ELEM_TYPE> m_features((ELEM_TYPE*)features.ptr<ELEM_TYPE>(0), features.rows, features.cols);
+    
+    CV_Assert(centers.type() == CvType<DIST_TYPE>::type());
+    CV_Assert(centers.isContinuous());
+    ::cvflann::Matrix<DIST_TYPE> m_centers((DIST_TYPE*)centers.ptr<DIST_TYPE>(0), centers.rows, centers.cols);
+    
+    return ::cvflann::hierarchicalClustering<ELEM_TYPE,DIST_TYPE>(m_features, m_centers, params);
+}
+
+} } // namespace cv::flann
+
+#endif // __cplusplus
+
+#endif
diff --git a/modules/flann/include/opencv2/flann/flann_base.hpp b/modules/flann/include/opencv2/flann/flann_base.hpp
new file mode 100644 (file)
index 0000000..5e85f79
--- /dev/null
@@ -0,0 +1,261 @@
+/***********************************************************************
+ * Software License Agreement (BSD License)
+ *
+ * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
+ * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
+ *
+ * THE BSD LICENSE
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *************************************************************************/
+
+#ifndef FLANN_HPP_
+#define FLANN_HPP_
+
+#include <vector>
+#include <string>
+#include <cassert>
+#include <cstdio>
+
+#include "opencv2/flann/general.h"
+#include "opencv2/flann/matrix.h"
+#include "opencv2/flann/result_set.h"
+#include "opencv2/flann/index_testing.h"
+#include "opencv2/flann/object_factory.h"
+#include "opencv2/flann/saving.h"
+
+#include "opencv2/flann/all_indices.h"
+
+namespace cvflann
+{
+
+
+/**
+Sets the log level used for all flann functions
+
+Params:
+    level = verbosity level
+*/
+void log_verbosity(int level);
+
+
+/**
+ * Sets the distance type to use throughout FLANN.
+ * If distance type specified is MINKOWSKI, the second argument
+ * specifies which order the minkowski distance should have.
+ */
+void set_distance_type(flann_distance_t distance_type, int order);
+
+
+struct SavedIndexParams : public IndexParams {
+       SavedIndexParams(std::string filename_) : IndexParams(SAVED), filename(filename_) {}
+
+       std::string filename;           // filename of the stored index
+
+       flann_algorithm_t getIndexType() const { return algorithm; }
+
+       void print() const
+       {
+               logger.info("Index type: %d\n",(int)algorithm);
+               logger.info("Filename: %s\n", filename.c_str());
+       }
+};
+
+template<typename T>
+class Index {
+       NNIndex<T>* nnIndex;
+    bool built;
+
+public:
+       Index(const Matrix<T>& features, const IndexParams& params);
+
+       ~Index();
+
+       void buildIndex();
+
+       void knnSearch(const Matrix<T>& queries, Matrix<int>& indices, Matrix<float>& dists, int knn, const SearchParams& params);
+
+       int radiusSearch(const Matrix<T>& query, Matrix<int>& indices, Matrix<float>& dists, float radius, const SearchParams& params);
+
+       void save(std::string filename);
+
+       int veclen() const;
+
+       int size() const;
+
+       NNIndex<T>* getIndex() { return nnIndex; }
+
+       const IndexParams* getIndexParameters() { return nnIndex->getParameters(); }
+};
+
+
+template<typename T>
+NNIndex<T>* load_saved_index(const Matrix<T>& dataset, const string& filename)
+{
+       FILE* fin = fopen(filename.c_str(), "rb");
+       if (fin==NULL) {
+               return NULL;
+       }
+       IndexHeader header = load_header(fin);
+       if (header.data_type!=Datatype<T>::type()) {
+               throw FLANNException("Datatype of saved index is different than of the one to be created.");
+       }
+       if (size_t(header.rows)!=dataset.rows || size_t(header.cols)!=dataset.cols) {
+               throw FLANNException("The index saved belongs to a different dataset");
+       }
+
+       IndexParams* params = ParamsFactory::instance().create(header.index_type);
+       NNIndex<T>* nnIndex = create_index_by_type(dataset, *params);
+       nnIndex->loadIndex(fin);
+       fclose(fin);
+
+       return nnIndex;
+}
+
+
+template<typename T>
+Index<T>::Index(const Matrix<T>& dataset, const IndexParams& params)
+{
+       flann_algorithm_t index_type = params.getIndexType();
+    built = false;
+
+       if (index_type==SAVED) {
+               nnIndex = load_saved_index(dataset, ((const SavedIndexParams&)params).filename);
+        built = true;
+       }
+       else {
+               nnIndex = create_index_by_type(dataset, params);
+       }
+}
+
+template<typename T>
+Index<T>::~Index()
+{
+       delete nnIndex;
+}
+
+template<typename T>
+void Index<T>::buildIndex()
+{
+       if (!built)     {
+               nnIndex->buildIndex();
+               built = true;
+       }
+}
+
+template<typename T>
+void Index<T>::knnSearch(const Matrix<T>& queries, Matrix<int>& indices, Matrix<float>& dists, int knn, const SearchParams& searchParams)
+{
+    if (!built) {
+        throw FLANNException("You must build the index before searching.");
+    }
+       assert(queries.cols==nnIndex->veclen());
+       assert(indices.rows>=queries.rows);
+       assert(dists.rows>=queries.rows);
+       assert(int(indices.cols)>=knn);
+       assert(int(dists.cols)>=knn);
+
+    KNNResultSet<T> resultSet(knn);
+
+    for (size_t i = 0; i < queries.rows; i++) {
+        T* target = queries[i];
+        resultSet.init(target, queries.cols);
+
+        nnIndex->findNeighbors(resultSet, target, searchParams);
+
+        int* neighbors = resultSet.getNeighbors();
+        float* distances = resultSet.getDistances();
+        memcpy(indices[i], neighbors, knn*sizeof(int));
+        memcpy(dists[i], distances, knn*sizeof(float));
+    }
+}
+
+template<typename T>
+int Index<T>::radiusSearch(const Matrix<T>& query, Matrix<int>& indices, Matrix<float>& dists, float radius, const SearchParams& searchParams)
+{
+    if (!built) {
+        throw FLANNException("You must build the index before searching.");
+    }
+       if (query.rows!=1) {
+           fprintf(stderr, "I can only search one feature at a time for range search\n");
+               return -1;
+       }
+       assert(query.cols==nnIndex->veclen());
+
+       RadiusResultSet<T> resultSet(radius);
+       resultSet.init(query.data, query.cols);
+       nnIndex->findNeighbors(resultSet,query.data,searchParams);
+
+       // TODO: optimise here
+       int* neighbors = resultSet.getNeighbors();
+       float* distances = resultSet.getDistances();
+       size_t count_nn = min(resultSet.size(), indices.cols);
+
+       assert (dists.cols>=count_nn);
+
+       for (size_t i=0;i<count_nn;++i) {
+               indices[0][i] = neighbors[i];
+               dists[0][i] = distances[i];
+       }
+
+       return count_nn;
+}
+
+
+template<typename T>
+void Index<T>::save(string filename)
+{
+       FILE* fout = fopen(filename.c_str(), "wb");
+       if (fout==NULL) {
+               throw FLANNException("Cannot open file");
+       }
+       save_header(fout, *nnIndex);
+       nnIndex->saveIndex(fout);
+       fclose(fout);
+}
+
+
+template<typename T>
+int Index<T>::size() const
+{
+       return nnIndex->size();
+}
+
+template<typename T>
+int Index<T>::veclen() const
+{
+       return nnIndex->veclen();
+}
+
+
+template <typename ELEM_TYPE, typename DIST_TYPE>
+int hierarchicalClustering(const Matrix<ELEM_TYPE>& features, Matrix<DIST_TYPE>& centers, const KMeansIndexParams& params)
+{
+    KMeansIndex<ELEM_TYPE, DIST_TYPE> kmeans(features, params);
+       kmeans.buildIndex();
+
+    int clusterNum = kmeans.getClusterCenters(centers);
+       return clusterNum;
+}
+
+} // namespace cvflann
+#endif /* FLANN_HPP_ */
similarity index 58%
rename from 3rdparty/flann/constants.h
rename to modules/flann/include/opencv2/flann/general.h
index 2332348..b75e529 100644 (file)
 #ifndef CONSTANTS_H
 #define CONSTANTS_H
 
+#define ARRAY_LEN(a) (sizeof(a)/sizeof(a[0]))
 
-const double FLANN_VERSION = 1.20;
 
-/* Nearest neighbor index algorithms */
+
+/* Nearest neighbour index algorithms */
 enum flann_algorithm_t {
        LINEAR = 0,
        KDTREE = 1,
        KMEANS = 2,
        COMPOSITE = 3,
        SAVED = 254,
-       AUTOTUNED = 255,
+       AUTOTUNED = 255
 };
 
 enum flann_centers_init_t {
@@ -50,7 +51,6 @@ enum flann_centers_init_t {
        CENTERS_KMEANSPP = 2
 };
 
-
 enum flann_log_level_t {
        LOG_NONE = 0,
        LOG_FATAL = 1,
@@ -62,7 +62,92 @@ enum flann_log_level_t {
 enum flann_distance_t {
        EUCLIDEAN = 1,
        MANHATTAN = 2,
-       MINKOWSKI = 3
+       MINKOWSKI = 3,
+       MAX_DIST   = 4,
+       HIK       = 5,
+       HELLINGER = 6,
+       CS        = 7,
+       CHI_SQUARE = 7,
+       KL        = 8,
+       KULLBACK_LEIBLER        = 8
 };
 
-#endif  // CONSTANTS_H
+enum flann_datatype_t {
+       INT8 = 0,
+       INT16 = 1,
+       INT32 = 2,
+       INT64 = 3,
+       UINT8 = 4,
+       UINT16 = 5,
+       UINT32 = 6,
+       UINT64 = 7,
+       FLOAT32 = 8,
+       FLOAT64 = 9
+};
+
+
+
+#ifdef __cplusplus
+
+#include <stdexcept>
+#include <cassert>
+#include "opencv2/flann/object_factory.h"
+
+namespace cvflann {
+
+
+template <typename ELEM_TYPE>
+struct DistType
+{
+       typedef ELEM_TYPE type;
+};
+
+template <>
+struct DistType<unsigned char>
+{
+       typedef float type;
+};
+
+template <>
+struct DistType<int>
+{
+       typedef float type;
+};
+
+
+class FLANNException : public std::runtime_error {
+ public:
+   FLANNException(const char* message) : std::runtime_error(message) { }
+
+   FLANNException(const std::string& message) : std::runtime_error(message) { }
+ };
+
+
+struct IndexParams {
+protected:
+       IndexParams(flann_algorithm_t algorithm_) : algorithm(algorithm_) {};
+
+public:
+       virtual flann_algorithm_t getIndexType() const = 0;
+
+       virtual void print() const = 0;
+
+       flann_algorithm_t algorithm;
+};
+
+
+typedef ObjectFactory<IndexParams, flann_algorithm_t> ParamsFactory;
+
+
+struct SearchParams {
+       SearchParams(int checks_ = 32) :
+               checks(checks_) {};
+
+       int checks;
+};
+
+} // namespace cvflann
+
+#endif
+
+#endif  /* CONSTANTS_H */
similarity index 94%
rename from 3rdparty/flann/ground_truth.h
rename to modules/flann/include/opencv2/flann/ground_truth.h
index 790aa70..f76f500 100644 (file)
@@ -31,8 +31,8 @@
 #ifndef GROUND_TRUTH_H
 #define GROUND_TRUTH_H
 
-#include "matrix.h"
-#include "dist.h"
+#include "opencv2/flann/dist.h"
+#include "opencv2/flann/matrix.h"
 
 namespace cvflann
 {
@@ -51,7 +51,7 @@ void find_nearest(const Matrix<T>& dataset, T* query, int* matches, int nn, int
     match[0] = 0;
     int dcnt = 1;
 
-    for (int i=1;i<dataset.rows;++i) {
+    for (size_t i=1;i<dataset.rows;++i) {
         T tmp = flann_dist(query, query_end, dataset[i]);
 
         if (dcnt<n) {
@@ -84,12 +84,12 @@ void find_nearest(const Matrix<T>& dataset, T* query, int* matches, int nn, int
 template <typename T>
 void compute_ground_truth(const Matrix<T>& dataset, const Matrix<T>& testset, Matrix<int>& matches, int skip=0)
 {
-    for (int i=0;i<testset.rows;++i) {
+    for (size_t i=0;i<testset.rows;++i) {
         find_nearest(dataset, testset[i], matches[i], matches.cols, skip);
     }
 }
 
 
-}
+} // namespace cvflann
 
 #endif //GROUND_TRUTH_H
diff --git a/modules/flann/include/opencv2/flann/hdf5.h b/modules/flann/include/opencv2/flann/hdf5.h
new file mode 100644 (file)
index 0000000..646c6b4
--- /dev/null
@@ -0,0 +1,163 @@
+/***********************************************************************
+ * Software License Agreement (BSD License)
+ *
+ * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
+ * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *************************************************************************/
+
+
+#ifndef IO_H_
+#define IO_H_
+
+#include <H5Cpp.h>
+
+#include "opencv2/flann/matrix.h"
+
+
+
+#ifndef H5_NO_NAMESPACE
+    using namespace H5;
+#endif
+
+namespace cvflann 
+{
+
+
+namespace {
+
+template<typename T>
+PredType get_hdf5_type()
+{
+       throw FLANNException("Unsupported type for IO operations");
+}
+
+template<> PredType get_hdf5_type<char>() { return PredType::NATIVE_CHAR; }
+template<> PredType get_hdf5_type<unsigned char>() { return PredType::NATIVE_UCHAR; }
+template<> PredType get_hdf5_type<short int>() { return PredType::NATIVE_SHORT; }
+template<> PredType get_hdf5_type<unsigned short int>() { return PredType::NATIVE_USHORT; }
+template<> PredType get_hdf5_type<int>() { return PredType::NATIVE_INT; }
+template<> PredType get_hdf5_type<unsigned int>() { return PredType::NATIVE_UINT; }
+template<> PredType get_hdf5_type<long>() { return PredType::NATIVE_LONG; }
+template<> PredType get_hdf5_type<unsigned long>() { return PredType::NATIVE_ULONG; }
+template<> PredType get_hdf5_type<float>() { return PredType::NATIVE_FLOAT; }
+template<> PredType get_hdf5_type<double>() { return PredType::NATIVE_DOUBLE; }
+template<> PredType get_hdf5_type<long double>() { return PredType::NATIVE_LDOUBLE; }
+
+}
+
+
+template<typename T>
+void save_to_file(const cvflann::Matrix<T>& flann_dataset, const std::string& filename, const std::string& name)
+{
+       // Try block to detect exceptions raised by any of the calls inside it
+       try
+       {
+               /*
+                * Turn off the auto-printing when failure occurs so that we can
+                * handle the errors appropriately
+                */
+               Exception::dontPrint();
+
+               /*
+                * Create a new file using H5F_ACC_TRUNC access,
+                * default file creation properties, and default file
+                * access properties.
+                */
+               H5File file( filename, H5F_ACC_TRUNC );
+
+               /*
+                * Define the size of the array and create the data space for fixed
+                * size dataset.
+                */
+               hsize_t     dimsf[2];              // dataset dimensions
+               dimsf[0] = flann_dataset.rows;
+               dimsf[1] = flann_dataset.cols;
+               DataSpace dataspace( 2, dimsf );
+
+               /*
+                * Create a new dataset within the file using defined dataspace and
+                * datatype and default dataset creation properties.
+                */
+               DataSet dataset = file.createDataSet( name, get_hdf5_type<T>(), dataspace );
+
+               /*
+                * Write the data to the dataset using default memory space, file
+                * space, and transfer properties.
+                */
+               dataset.write( flann_dataset.data, get_hdf5_type<T>() );
+       }  // end of try block
+       catch( H5::Exception& error )
+       {
+               error.printError();
+               throw FLANNException(error.getDetailMsg());
+       }
+}
+
+
+template<typename T>
+void load_from_file(cvflann::Matrix<T>& flann_dataset, const std::string& filename, const std::string& name)
+{
+       try
+       {
+               Exception::dontPrint();
+
+               H5File file( filename, H5F_ACC_RDONLY );
+               DataSet dataset = file.openDataSet( name );
+
+               /*
+                * Check the type used by the dataset matches
+                */
+               if ( !(dataset.getDataType()==get_hdf5_type<T>())) {
+                       throw FLANNException("Dataset matrix type does not match the type to be read.");
+               }
+
+               /*
+                * Get dataspace of the dataset.
+                */
+               DataSpace dataspace = dataset.getSpace();
+
+               /*
+                * Get the dimension size of each dimension in the dataspace and
+                * display them.
+                */
+               hsize_t dims_out[2];
+               dataspace.getSimpleExtentDims( dims_out, NULL);
+               
+               flann_dataset.rows = dims_out[0];
+               flann_dataset.cols = dims_out[1];
+               flann_dataset.data = new T[flann_dataset.rows*flann_dataset.cols];
+
+               dataset.read( flann_dataset.data, get_hdf5_type<T>() );
+       }  // end of try block
+       catch( H5::Exception &error )
+       {
+               error.printError();
+               throw FLANNException(error.getDetailMsg());
+       }
+}
+
+
+} // namespace cvflann
+
+#endif /* IO_H_ */
similarity index 99%
rename from 3rdparty/flann/heap.h
rename to modules/flann/include/opencv2/flann/heap.h
index 9cc835c..d158017 100644 (file)
@@ -204,6 +204,6 @@ public:
 
 };
 
-}
+} // namespace cvflann
 
 #endif //HEAP_H
similarity index 74%
rename from 3rdparty/flann/index_testing.cpp
rename to modules/flann/include/opencv2/flann/index_testing.h
index e05662b..40a957f 100644 (file)
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *************************************************************************/
 
-#include "index_testing.h"
-#include "result_set.h"
-#include "timer.h"
-#include "logger.h"
-#include "dist.h"
-#include "common.h"
-
-#include <algorithm>
-#include <math.h>
-#include <string.h>
-#include <stdlib.h>
+#ifndef TESTING_H
+#define TESTING_H
+
+#include <cstring>
+#include <cassert>
+
+#include "opencv2/flann/matrix.h"
+#include "opencv2/flann/nn_index.h"
+#include "opencv2/flann/result_set.h"
+#include "opencv2/flann/logger.h"
+#include "opencv2/flann/timer.h"
 
-namespace cvflann
-{
 
-const float SEARCH_EPS = 0.001f;
+using namespace std;
 
-int countCorrectMatches(int* neighbors, int* groundTruth, int n)
+namespace cvflann
 {
-    int count = 0;
-    for (int i=0;i<n;++i) {
-        for (int k=0;k<n;++k) {
-            if (neighbors[i]==groundTruth[k]) {
-                count++;
-                break;
-            }
-        }
-    }
-    return count;
-}
+
+int countCorrectMatches(int* neighbors, int* groundTruth, int n);
 
 
-float computeDistanceRaport(const Matrix<float>& inputData, float* target, int* neighbors, int* groundTruth, int veclen, int n)
+template <typename ELEM_TYPE>
+float computeDistanceRaport(const Matrix<ELEM_TYPE>& inputData, ELEM_TYPE* target, int* neighbors, int* groundTruth, int veclen, int n)
 {
-       float* target_end = target + veclen;
+       ELEM_TYPE* target_end = target + veclen;
     float ret = 0;
     for (int i=0;i<n;++i) {
-        float den = (float)flann_dist(target,target_end, inputData[groundTruth[i]]);
-        float num = (float)flann_dist(target,target_end, inputData[neighbors[i]]);
-
-//        printf("den=%g,num=%g\n",den,num);
+        float den = flann_dist(target,target_end, inputData[groundTruth[i]]);
+        float num = flann_dist(target,target_end, inputData[neighbors[i]]);
 
         if (den==0 && num==0) {
             ret += 1;
-        } else {
+        }
+        else {
             ret += num/den;
         }
     }
@@ -80,19 +69,20 @@ float computeDistanceRaport(const Matrix<float>& inputData, float* target, int*
     return ret;
 }
 
-float search_with_ground_truth(NNIndex& index, const Matrix<float>& inputData, const Matrix<float>& testData, const Matrix<int>& matches, int nn, int checks, float& time, float& dist, int skipMatches)
+template <typename ELEM_TYPE>
+float search_with_ground_truth(NNIndex<ELEM_TYPE>& index, const Matrix<ELEM_TYPE>& inputData, const Matrix<ELEM_TYPE>& testData, const Matrix<int>& matches, int nn, int checks, float& time, float& dist, int skipMatches)
 {
-    if (matches.cols<nn) {
+    if (matches.cols<size_t(nn)) {
         logger.info("matches.cols=%d, nn=%d\n",matches.cols,nn);
 
         throw FLANNException("Ground truth is not computed for as many neighbors as requested");
     }
 
-    KNNResultSet resultSet(nn+skipMatches);
+    KNNResultSet<ELEM_TYPE> resultSet(nn+skipMatches);
     SearchParams searchParams(checks);
 
-    int correct = 0;
-    float distR = 0;
+    int correct;
+    float distR;
     StartStopTimer t;
     int repeats = 0;
     while (t.value<0.2) {
@@ -100,8 +90,8 @@ float search_with_ground_truth(NNIndex& index, const Matrix<float>& inputData, c
         t.start();
         correct = 0;
         distR = 0;
-        for (int i = 0; i < testData.rows; i++) {
-            float* target = testData[i];
+        for (size_t i = 0; i < testData.rows; i++) {
+            ELEM_TYPE* target = testData[i];
             resultSet.init(target, testData.cols);
             index.findNeighbors(resultSet,target, searchParams);
             int* neighbors = resultSet.getNeighbors();
@@ -112,7 +102,7 @@ float search_with_ground_truth(NNIndex& index, const Matrix<float>& inputData, c
         }
         t.stop();
     }
-    time = (float)(t.value/repeats);
+    time = t.value/repeats;
 
 
     float precicion = (float)correct/(nn*testData.rows);
@@ -125,29 +115,10 @@ float search_with_ground_truth(NNIndex& index, const Matrix<float>& inputData, c
     return precicion;
 }
 
-void search_for_neighbors(NNIndex& index, const Matrix<float>& testset, Matrix<int>& result,  Matrix<float>& dists, const SearchParams& searchParams, int skip)
-{
-    assert(testset.rows == result.rows);
-
-    int nn = result.cols;
-    KNNResultSet resultSet(nn+skip);
-
-
-    for (int i = 0; i < testset.rows; i++) {
-        float* target = testset[i];
-        resultSet.init(target, testset.cols);
-
-        index.findNeighbors(resultSet,target, searchParams);
-
-        int* neighbors = resultSet.getNeighbors();
-        float* distances = resultSet.getDistances();
-        memcpy(result[i], neighbors+skip, nn*sizeof(int));
-        memcpy(dists[i], distances+skip, nn*sizeof(float));
-    }
 
-}
-
-float test_index_checks(NNIndex& index, const Matrix<float>& inputData, const Matrix<float>& testData, const Matrix<int>& matches, int checks, float& precision, int nn, int skipMatches)
+template <typename ELEM_TYPE>
+float test_index_checks(NNIndex<ELEM_TYPE>& index, const Matrix<ELEM_TYPE>& inputData, const Matrix<ELEM_TYPE>& testData, const Matrix<int>& matches,
+            int checks, float& precision, int nn = 1, int skipMatches = 0)
 {
     logger.info("  Nodes  Precision(%)   Time(s)   Time/vec(ms)  Mean dist\n");
     logger.info("---------------------------------------------------------\n");
@@ -159,10 +130,12 @@ float test_index_checks(NNIndex& index, const Matrix<float>& inputData, const Ma
     return time;
 }
 
-
-float test_index_precision(NNIndex& index, const Matrix<float>& inputData, const Matrix<float>& testData, const Matrix<int>& matches,
-             float precision, int& checks, int nn, int skipMatches)
+template <typename ELEM_TYPE>
+float test_index_precision(NNIndex<ELEM_TYPE>& index, const Matrix<ELEM_TYPE>& inputData, const Matrix<ELEM_TYPE>& testData, const Matrix<int>& matches,
+             float precision, int& checks, int nn = 1, int skipMatches = 0)
 {
+       const float SEARCH_EPS = 0.001;
+
     logger.info("  Nodes  Precision(%)   Time(s)   Time/vec(ms)  Mean dist\n");
     logger.info("---------------------------------------------------------\n");
 
@@ -227,9 +200,12 @@ float test_index_precision(NNIndex& index, const Matrix<float>& inputData, const
 }
 
 
-float test_index_precisions(NNIndex& index, const Matrix<float>& inputData, const Matrix<float>& testData, const Matrix<int>& matches,
-                    float* precisions, int precisions_length, int nn, int skipMatches, float maxTime)
+template <typename ELEM_TYPE>
+float test_index_precisions(NNIndex<ELEM_TYPE>& index, const Matrix<ELEM_TYPE>& inputData, const Matrix<ELEM_TYPE>& testData, const Matrix<int>& matches,
+                    float* precisions, int precisions_length, int nn = 1, int skipMatches = 0, float maxTime = 0)
 {
+       const float SEARCH_EPS = 0.001;
+
     // make sure precisions array is sorted
     sort(precisions, precisions+precisions_length);
 
@@ -311,4 +287,6 @@ float test_index_precisions(NNIndex& index, const Matrix<float>& inputData, cons
     return time;
 }
 
-}
+} // namespace cvflann
+
+#endif //TESTING_H
similarity index 75%
rename from 3rdparty/flann/kdtree_index.h
rename to modules/flann/include/opencv2/flann/kdtree_index.h
index d8be441..3286f02 100644 (file)
 #include <algorithm>
 #include <map>
 #include <cassert>
+#include <cstring>
 
-#include "heap.h"
-#include "common.h"
-#include "constants.h"
-#include "allocator.h"
-#include "matrix.h"
-#include "result_set.h"
-#include "random.h"
-#include "nn_index.h"
-#include "saving.h"
+#include "opencv2/flann/general.h"
+#include "opencv2/flann/nn_index.h"
+#include "opencv2/flann/matrix.h"
+#include "opencv2/flann/result_set.h"
+#include "opencv2/flann/heap.h"
+#include "opencv2/flann/allocator.h"
+#include "opencv2/flann/random.h"
+#include "opencv2/flann/saving.h"
 
 using namespace std;
 
@@ -51,6 +51,21 @@ using namespace std;
 namespace cvflann
 {
 
+struct KDTreeIndexParams : public IndexParams {
+       KDTreeIndexParams(int trees_ = 4) : IndexParams(KDTREE), trees(trees_) {};
+
+       int trees;                 // number of randomized trees to use (for kdtree)
+
+       flann_algorithm_t getIndexType() const { return algorithm; }
+
+       void print() const
+       {
+               logger.info("Index type: %d\n",(int)algorithm);
+               logger.info("Trees: %d\n", trees);
+       }
+
+};
+
 
 /**
  * Randomized kd-tree index
@@ -58,7 +73,8 @@ namespace cvflann
  * Contains the k-d trees and other information for indexing a set of points
  * for nearest-neighbor matching.
  */
-class KDTreeIndex : public NNIndex
+template <typename ELEM_TYPE, typename DIST_TYPE = typename DistType<ELEM_TYPE>::type >
+class KDTreeIndex : public NNIndex<ELEM_TYPE>
 {
 
        enum {
@@ -85,27 +101,24 @@ class KDTreeIndex : public NNIndex
        int numTrees;
 
        /**
-        *  Array of indices to vectors in the dataset.  When doing lookup,
-        *  this is used instead to mark checkID.
+        *  Array of indices to vectors in the dataset.
         */
        int* vind;
 
-       /**
-        * An unique ID for each lookup.
-        */
-       int checkID;
 
        /**
         * The dataset used by this index
         */
-       const Matrix<float> dataset;
+       const Matrix<ELEM_TYPE> dataset;
+
+    const IndexParams& index_params;
 
-    int size_;
-    int veclen_;
+       size_t size_;
+       size_t veclen_;
 
 
-    float* mean;
-    float* var;
+    DIST_TYPE* mean;
+    DIST_TYPE* var;
 
 
        /*--------------------- Internal Data Structures --------------------------*/
@@ -126,7 +139,7 @@ class KDTreeIndex : public NNIndex
                /**
                 * The value used for subdivision.
                 */
-               float divval;
+               DIST_TYPE divval;
                /**
                 * The child nodes.
                 */
@@ -135,16 +148,11 @@ class KDTreeIndex : public NNIndex
        typedef TreeSt* Tree;
 
     /**
-     * Array of k-d trees used to find neighbors.
+     * Array of k-d trees used to find neighbours.
      */
     Tree* trees;
     typedef BranchStruct<Tree> BranchSt;
     typedef BranchSt* Branch;
-    /**
-     * Priority queue storing intermediate branches in the best-bin-first search
-     */
-    Heap<BranchSt>* heap;
-
 
        /**
         * Pooled memory allocator.
@@ -171,7 +179,8 @@ public:
         *              inputData = dataset with the input features
         *              params = parameters passed to the kdtree algorithm
         */
-       KDTreeIndex(const Matrix<float>& inputData, const KDTreeIndexParams& params = KDTreeIndexParams() ) : dataset(inputData)
+       KDTreeIndex(const Matrix<ELEM_TYPE>& inputData, const KDTreeIndexParams& params = KDTreeIndexParams() ) :
+               dataset(inputData), index_params(params)
        {
         size_ = dataset.rows;
         veclen_ = dataset.cols;
@@ -188,17 +197,15 @@ public:
 //             numTrees = -1;
 //             trees = NULL;
 //        }
-               heap = new Heap<BranchSt>(size_);
-               checkID = -1000;
 
                // Create a permutable array of indices to the input vectors.
                vind = new int[size_];
-               for (int i = 0; i < size_; i++) {
+               for (size_t i = 0; i < size_; i++) {
                        vind[i] = i;
                }
 
-        mean = new float[veclen_];
-        var = new float[veclen_];
+        mean = new DIST_TYPE[veclen_];
+        var = new DIST_TYPE[veclen_];
        }
 
        /**
@@ -210,8 +217,7 @@ public:
                if (trees!=NULL) {
                        delete[] trees;
                }
-               delete heap;
-        delete[] mean;
+               delete[] mean;
         delete[] var;
        }
 
@@ -225,13 +231,10 @@ public:
                for (int i = 0; i < numTrees; i++) {
                        /* Randomize the order of vectors to allow for unbiased sampling. */
                        for (int j = size_; j > 0; --j) {
-//                             int rand = cast(int) (drand48() * size);
                                int rnd = rand_int(j);
-                               assert(rnd >=0 && rnd < size_);
                                swap(vind[j-1], vind[rnd]);
                        }
-                       trees[i] = NULL;
-                       divideTree(&trees[i], 0, size_ - 1);
+                       trees[i] = divideTree(0, size_ - 1);
                }
        }
 
@@ -239,7 +242,6 @@ public:
 
     void saveIndex(FILE* stream)
     {
-       save_header(stream, *this);
        save_value(stream, numTrees);
        for (int i=0;i<numTrees;++i) {
                save_tree(stream, trees[i]);
@@ -250,11 +252,6 @@ public:
 
     void loadIndex(FILE* stream)
     {
-       IndexHeader header = load_header(stream);
-
-       if (header.rows!=size() || header.cols!=veclen()) {
-               throw FLANNException("The index saved belongs to a different dataset");
-       }
        load_value(stream, numTrees);
 
        if (trees!=NULL) {
@@ -267,11 +264,10 @@ public:
     }
 
 
-
     /**
     *  Returns size of index.
     */
-    int size() const
+    size_t size() const
     {
         return size_;
     }
@@ -279,7 +275,7 @@ public:
     /**
     * Returns the length of an index feature.
     */
-    int veclen() const
+    size_t veclen() const
     {
         return veclen_;
     }
@@ -304,7 +300,7 @@ public:
      *     vec = the vector for which to search the nearest neighbors
      *     maxCheck = the maximum number of restarts (in a best-bin-first manner)
      */
-    void findNeighbors(ResultSet& result, const float* vec, const SearchParams& searchParams)
+    void findNeighbors(ResultSet<ELEM_TYPE>& result, const ELEM_TYPE* vec, const SearchParams& searchParams)
     {
         int maxChecks = searchParams.checks;
 
@@ -315,30 +311,11 @@ public:
         }
     }
 
-
-       void continueSearch(ResultSet& result, float* vec, int maxCheck)
+       const IndexParams* getParameters() const
        {
-               BranchSt branch;
-
-               int checkCount = 0;
-
-               /* Keep searching other branches from heap until finished. */
-               while ( heap->popMin(branch) && (checkCount < maxCheck || !result.full() )) {
-                       searchLevel(result, vec, branch.node,branch.mindistsq, checkCount, maxCheck);
-               }
-
-               assert(result.full());
+               return &index_params;
        }
 
-
-//    Params estimateSearchParams(float precision, Dataset<float>* testset = NULL)
-//    {
-//        Params params;
-//
-//        return params;
-//    }
-
-
 private:
 
 
@@ -376,24 +353,22 @@ private:
         *                      first = index of the first vector
         *                      last = index of the last vector
         */
-       void divideTree(Tree* pTree, int first, int last)
+       Tree divideTree(int first, int last)
        {
-               Tree node;
-
-               node = pool.allocate<TreeSt>(); // allocate memory
-               *pTree = node;
+               Tree node = pool.allocate<TreeSt>(); // allocate memory
 
                /* If only one exemplar remains, then make this a leaf node. */
                if (first == last) {
                        node->child1 = node->child2 = NULL;    /* Mark as leaf node. */
                        node->divfeat = vind[first];    /* Store index of this vec. */
-               } else {
+               }
+               else {
                        chooseDivision(node, first, last);
                        subdivide(node, first, last);
                }
-       }
-
 
+               return node;
+       }
 
 
        /**
@@ -403,29 +378,28 @@ private:
         */
        void chooseDivision(Tree node, int first, int last)
        {
-        memset(mean,0,veclen_*sizeof(float));
-        memset(var,0,veclen_*sizeof(float));
+        memset(mean,0,veclen_*sizeof(DIST_TYPE));
+        memset(var,0,veclen_*sizeof(DIST_TYPE));
 
                /* Compute mean values.  Only the first SAMPLE_MEAN values need to be
                        sampled to get a good estimate.
                */
                int end = min(first + SAMPLE_MEAN, last);
-               int count = end - first + 1;
                for (int j = first; j <= end; ++j) {
-                       float* v = dataset[vind[j]];
-            for (int k=0; k<veclen_; ++k) {
+                       ELEM_TYPE* v = dataset[vind[j]];
+            for (size_t k=0; k<veclen_; ++k) {
                 mean[k] += v[k];
             }
                }
-        for (int k=0; k<veclen_; ++k) {
-            mean[k] /= count;
+        for (size_t k=0; k<veclen_; ++k) {
+            mean[k] /= (end - first + 1);
         }
 
                /* Compute variances (no need to divide by count). */
                for (int j = first; j <= end; ++j) {
-                       float* v = dataset[vind[j]];
-            for (int k=0; k<veclen_; ++k) {
-                float dist = v[k] - mean[k];
+                       ELEM_TYPE* v = dataset[vind[j]];
+            for (size_t k=0; k<veclen_; ++k) {
+                DIST_TYPE dist = v[k] - mean[k];
                 var[k] += dist * dist;
             }
                }
@@ -440,13 +414,13 @@ private:
         * Select the top RAND_DIM largest values from v and return the index of
         * one of these selected at random.
         */
-       int selectDivision(float* v)
+       int selectDivision(DIST_TYPE* v)
        {
                int num = 0;
                int topind[RAND_DIM];
 
                /* Create a list of the indices of the top RAND_DIM values. */
-               for (int i = 0; i < veclen_; ++i) {
+               for (size_t i = 0; i < veclen_; ++i) {
                        if (num < RAND_DIM  ||  v[i] > v[topind[num-1]]) {
                                /* Put this element at end of topind. */
                                if (num < RAND_DIM) {
@@ -464,9 +438,7 @@ private:
                        }
                }
                /* Select a random integer in range [0,num-1], and return that index. */
-//             int rand = cast(int) (drand48() * num);
                int rnd = rand_int(num);
-               assert(rnd >=0 && rnd < num);
                return topind[rnd];
        }
 
@@ -482,7 +454,7 @@ private:
                int j = last;
                while (i <= j) {
                        int ind = vind[i];
-                       float val = dataset[ind][node->divfeat];
+                       ELEM_TYPE val = dataset[ind][node->divfeat];
                        if (val < node->divval) {
                                ++i;
                        } else {
@@ -499,8 +471,8 @@ private:
             i = (first+last+1)/2;
                }
 
-               divideTree(& node->child1, first, i - 1);
-               divideTree(& node->child2, i, last);
+               node->child1 = divideTree(first, i - 1);
+               node->child2 = divideTree(i, last);
        }
 
 
@@ -509,9 +481,9 @@ private:
         * Performs an exact nearest neighbor search. The exact search performs a full
         * traversal of the tree.
         */
-       void getExactNeighbors(ResultSet& result, const float* vec)
+       void getExactNeighbors(ResultSet<ELEM_TYPE>& result, const ELEM_TYPE* vec)
        {
-               checkID -= 1;  /* Set a different unique ID for each search. */
+//             checkID -= 1;  /* Set a different unique ID for each search. */
 
                if (numTrees > 1) {
             fprintf(stderr,"It doesn't make any sense to use more than one tree for exact search");
@@ -527,25 +499,27 @@ private:
         * because the tree traversal is abandoned after a given number of descends in
         * the tree.
         */
-       void getNeighbors(ResultSet& result, const float* vec, int maxCheck)
+       void getNeighbors(ResultSet<ELEM_TYPE>& result, const ELEM_TYPE* vec, int maxCheck)
        {
                int i;
                BranchSt branch;
 
                int checkCount = 0;
-               heap->clear();
-               checkID -= 1;  /* Set a different unique ID for each search. */
+               Heap<BranchSt>* heap = new Heap<BranchSt>(size_);
+               vector<bool> checked(size_,false);
 
                /* Search once through each tree down to root. */
                for (i = 0; i < numTrees; ++i) {
-                       searchLevel(result, vec, trees[i], 0.0, checkCount, maxCheck);
+                       searchLevel(result, vec, trees[i], 0.0, checkCount, maxCheck, heap, checked);
                }
 
                /* Keep searching other branches from heap until finished. */
                while ( heap->popMin(branch) && (checkCount < maxCheck || !result.full() )) {
-                       searchLevel(result, vec, branch.node,branch.mindistsq, checkCount, maxCheck);
+                       searchLevel(result, vec, branch.node, branch.mindistsq, checkCount, maxCheck, heap, checked);
                }
 
+               delete heap;
+
                assert(result.full());
        }
 
@@ -555,16 +529,14 @@ private:
         *  higher levels, all exemplars below this level must have a distance of
         *  at least "mindistsq".
        */
-       void searchLevel(ResultSet& result, const float* vec, Tree node, float mindistsq, int& checkCount, int maxCheck)
+       void searchLevel(ResultSet<ELEM_TYPE>& result, const ELEM_TYPE* vec, Tree node, float mindistsq, int& checkCount, int maxCheck,
+                       Heap<BranchSt>* heap, vector<bool>& checked)
        {
                if (result.worstDist()<mindistsq) {
 //                     printf("Ignoring branch, too far\n");
                        return;
                }
 
-               float val, diff;
-               Tree bestChild, otherChild;
-
                /* If this is a leaf node, then do check and return. */
                if (node->child1 == NULL  &&  node->child2 == NULL) {
 
@@ -572,21 +544,21 @@ private:
                                Once a vector is checked, we set its location in vind to the
                                current checkID.
                        */
-                       if (vind[node->divfeat] == checkID || checkCount>=maxCheck) {
+                       if (checked[node->divfeat] == true || checkCount>=maxCheck) {
                                if (result.full()) return;
                        }
             checkCount++;
-                       vind[node->divfeat] = checkID;
+                       checked[node->divfeat] = true;
 
                        result.addPoint(dataset[node->divfeat],node->divfeat);
                        return;
                }
 
                /* Which child branch should be taken first? */
-               val = vec[node->divfeat];
-               diff = val - node->divval;
-               bestChild = (diff < 0) ? node->child1 : node->child2;
-               otherChild = (diff < 0) ? node->child2 : node->child1;
+               ELEM_TYPE val = vec[node->divfeat];
+               DIST_TYPE diff = val - node->divval;
+               Tree bestChild = (diff < 0) ? node->child1 : node->child2;
+               Tree otherChild = (diff < 0) ? node->child2 : node->child1;
 
                /* Create a branch record for the branch not taken.  Add distance
                        of this feature boundary (we don't attempt to correct for any
@@ -596,28 +568,25 @@ private:
                        adding exceeds their value.
                */
 
-               float new_distsq = flann_dist(&val, &val+1, &node->divval, mindistsq);
+               DIST_TYPE new_distsq = flann_dist(&val, &val+1, &node->divval, mindistsq);
 //             if (2 * checkCount < maxCheck  ||  !result.full()) {
                if (new_distsq < result.worstDist() ||  !result.full()) {
                        heap->insert( BranchSt::make_branch(otherChild, new_distsq) );
                }
 
                /* Call recursively to search next level down. */
-               searchLevel(result, vec, bestChild, mindistsq, checkCount, maxCheck);
+               searchLevel(result, vec, bestChild, mindistsq, checkCount, maxCheck, heap, checked);
        }
 
        /**
         * Performs an exact search in the tree starting from a node.
         */
-       void searchLevelExact(ResultSet& result, const float* vec, Tree node, float mindistsq)
+       void searchLevelExact(ResultSet<ELEM_TYPE>& result, const ELEM_TYPE* vec, Tree node, float mindistsq)
        {
                if (mindistsq>result.worstDist()) {
                        return;
                }
 
-               float val, diff;
-               Tree bestChild, otherChild;
-
                /* If this is a leaf node, then do check and return. */
                if (node->child1 == NULL  &&  node->child2 == NULL) {
 
@@ -625,29 +594,29 @@ private:
                                Once a vector is checked, we set its location in vind to the
                                current checkID.
                        */
-                       if (vind[node->divfeat] == checkID)
-                               return;
-                       vind[node->divfeat] = checkID;
+//                     if (vind[node->divfeat] == checkID)
+//                             return;
+//                     vind[node->divfeat] = checkID;
 
                        result.addPoint(dataset[node->divfeat],node->divfeat);
                        return;
                }
 
                /* Which child branch should be taken first? */
-               val = vec[node->divfeat];
-               diff = val - node->divval;
-               bestChild = (diff < 0) ? node->child1 : node->child2;
-               otherChild = (diff < 0) ? node->child2 : node->child1;
+               ELEM_TYPE val = vec[node->divfeat];
+               DIST_TYPE diff = val - node->divval;
+               Tree bestChild = (diff < 0) ? node->child1 : node->child2;
+               Tree otherChild = (diff < 0) ? node->child2 : node->child1;
 
 
                /* Call recursively to search next level down. */
                searchLevelExact(result, vec, bestChild, mindistsq);
-               float new_distsq = flann_dist(&val, &val+1, &node->divval, mindistsq);
+               DIST_TYPE new_distsq = flann_dist(&val, &val+1, &node->divval, mindistsq);
                searchLevelExact(result, vec, otherChild, new_distsq);
        }
 
 };   // class KDTree
 
-}
+} // namespace cvflann
 
 #endif //KDTREE_H
similarity index 66%
rename from 3rdparty/flann/kmeans_index.h
rename to modules/flann/include/opencv2/flann/kmeans_index.h
index f8d3c15..dc519e5 100644 (file)
 
 #include <algorithm>
 #include <string>
-#include <cstdlib>
 #include <map>
 #include <cassert>
 #include <limits>
 #include <cmath>
-#include "constants.h"
-#include "common.h"
-#include "heap.h"
-#include "allocator.h"
-#include "matrix.h"
-#include "result_set.h"
-#include "random.h"
-#include "nn_index.h"
 
-using namespace std;
+#include "opencv2/flann/general.h"
+#include "opencv2/flann/nn_index.h"
+#include "opencv2/flann/matrix.h"
+#include "opencv2/flann/result_set.h"
+#include "opencv2/flann/heap.h"
+#include "opencv2/flann/allocator.h"
+#include "opencv2/flann/random.h"
 
+using namespace std;
 
 namespace cvflann
 {
 
-/**
-* Chooses the initial centers in the k-means clustering in a random manner.
-*
-* Params:
-*     k = number of centers
-*     vecs = the dataset of points
-*     indices = indices in the dataset
-*     indices_length = length of indices vector
-*
-*/
-void chooseCentersRandom(int k, const Matrix<float>& vecs, int* indices, int indices_length, float** centers, int& centers_length)
-{
-    UniqueRandom r(indices_length);
-
-    int index;
-    for (index=0;index<k;++index) {
-        bool duplicate = true;
-        int rnd;
-        while (duplicate) {
-            duplicate = false;
-            rnd = r.next();
-            if (rnd<0) {
-                centers_length = index;
-                return;
-            }
-
-            centers[index] = vecs[indices[rnd]];
-
-            for (int j=0;j<index;++j) {
-                float sq = flann_dist(centers[index],centers[index]+vecs.cols,centers[j]);
-                if (sq<1e-16) {
-                    duplicate = true;
-                }
-            }
-        }
-    }
-
-    centers_length = index;
-}
-
-
-/**
-* Chooses the initial centers in the k-means using Gonzales' algorithm
-* so that the centers are spaced apart from each other.
-*
-* Params:
-*     k = number of centers
-*     vecs = the dataset of points
-*     indices = indices in the dataset
-* Returns:
-*/
-void chooseCentersGonzales(int k, const Matrix<float>& vecs, int* indices, int indices_length, float** centers, int& centers_length)
-{
-    int n = indices_length;
-
-
-    int rnd = rand_int(n);
-    assert(rnd >=0 && rnd < n);
-
-    centers[0] = vecs[indices[rnd]];
-
-    int index;
-    for (index=1; index<k; ++index) {
-
-        int best_index = -1;
-        float best_val = 0;
-        for (int j=0;j<n;++j) {
-            float dist = flann_dist(centers[0],centers[0]+vecs.cols,vecs[indices[j]]);
-            for (int i=1;i<index;++i) {
-                    float tmp_dist = flann_dist(centers[i],centers[i]+vecs.cols,vecs[indices[j]]);
-                if (tmp_dist<dist) {
-                    dist = tmp_dist;
-                }
-            }
-            if (dist>best_val) {
-                best_val = dist;
-                best_index = j;
-            }
-        }
-        if (best_index!=-1) {
-            centers[index] = vecs[indices[best_index]];
-        }
-        else {
-            break;
-        }
-    }
-    centers_length = index;
-}
-
-
-/**
-* Chooses the initial centers in the k-means using the algorithm
-* proposed in the KMeans++ paper:
-* Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding
-*
-* Implementation of this function was converted from the one provided in Arthur's code.
-*
-* Params:
-*     k = number of centers
-*     vecs = the dataset of points
-*     indices = indices in the dataset
-* Returns:
-*/
-void chooseCentersKMeanspp(int k, const Matrix<float>& vecs, int* indices, int indices_length, float** centers, int& centers_length)
-{
-    int n = indices_length;
-
-    double currentPot = 0;
-    double* closestDistSq = new double[n];
-
-    // Choose one random center and set the closestDistSq values
-    int index = rand_int(n);
-    assert(index >=0 && index < n);
-    centers[0] = vecs[indices[index]];
-
-    for (int i = 0; i < n; i++) {
-        closestDistSq[i] = flann_dist(vecs[indices[i]], vecs[indices[i]] + vecs.cols, vecs[indices[index]]);
-        currentPot += closestDistSq[i];
-    }
 
+struct KMeansIndexParams : public IndexParams {
+       KMeansIndexParams(int branching_ = 32, int iterations_ = 11,
+                       flann_centers_init_t centers_init_ = CENTERS_RANDOM, float cb_index_ = 0.2 ) :
+               IndexParams(KMEANS),
+               branching(branching_),
+               iterations(iterations_),
+               centers_init(centers_init_),
+               cb_index(cb_index_) {};
 
-    const int numLocalTries = 1;
-
-    // Choose each center
-    int centerCount;
-    for (centerCount = 1; centerCount < k; centerCount++) {
-
-        // Repeat several trials
-        double bestNewPot = -1;
-        int bestNewIndex = 0;
-        for (int localTrial = 0; localTrial < numLocalTries; localTrial++) {
-
-            // Choose our center - have to be slightly careful to return a valid answer even accounting
-            // for possible rounding errors
-        double randVal = rand_double(currentPot);
-            for (index = 0; index < n-1; index++) {
-                if (randVal <= closestDistSq[index])
-                    break;
-                else
-                    randVal -= closestDistSq[index];
-            }
-
-            // Compute the new potential
-            double newPot = 0;
-            for (int i = 0; i < n; i++)
-                newPot += min( (double)flann_dist(vecs[indices[i]], vecs[indices[i]] + vecs.cols, vecs[indices[index]]), closestDistSq[i] );
-
-            // Store the best result
-            if (bestNewPot < 0 || newPot < bestNewPot) {
-                bestNewPot = newPot;
-                bestNewIndex = index;
-            }
-        }
-
-        // Add the appropriate center
-        centers[centerCount] = vecs[indices[bestNewIndex]];
-        currentPot = bestNewPot;
-        for (int i = 0; i < n; i++)
-            closestDistSq[i] = min( (double)flann_dist(vecs[indices[i]], vecs[indices[i]]+vecs.cols, vecs[indices[bestNewIndex]]), closestDistSq[i] );
-    }
-
-    centers_length = centerCount;
-
-       delete[] closestDistSq;
-}
-
-
-
-
-namespace {
-
-    typedef void (*centersAlgFunction)(int, const Matrix<float>&, int*, int, float**, int&);
-    /**
-    * Associative array with functions to use for choosing the cluster centers.
-    */
-    map<flann_centers_init_t,centersAlgFunction> centerAlgs;
-    /**
-    * Static initializer. Performs initialization befor the program starts.
-    */
-
-    void centers_init()
-    {
-        centerAlgs[CENTERS_RANDOM] = &chooseCentersRandom;
-        centerAlgs[CENTERS_GONZALES] = &chooseCentersGonzales;
-        centerAlgs[CENTERS_KMEANSPP] = &chooseCentersKMeanspp;
-    }
-
-    struct Init {
-        Init() { centers_init(); }
-    };
-    Init __init;
-}
+       int branching;             // branching factor (for kmeans tree)
+       int iterations;            // max iterations to perform in one kmeans clustering (kmeans tree)
+       flann_centers_init_t centers_init;          // algorithm used for picking the initial cluster centers for kmeans tree
+    float cb_index;            // cluster boundary index. Used when searching the kmeans tree
 
+       flann_algorithm_t getIndexType() const { return KMEANS; }
 
+       void print() const
+       {
+               logger.info("Index type: %d\n",(int)algorithm);
+               logger.info("Branching: %d\n", branching);
+               logger.info("Iterations: %d\n", iterations);
+               logger.info("Centres initialisation: %d\n", centers_init);
+               logger.info("Cluster boundary weight: %g\n", cb_index);
+       }
 
+};
 
 
 /**
  * Hierarchical kmeans index
  *
  * Contains a tree constructed through a hierarchical kmeans clustering
- * and other information for indexing a set of points for nearest-neighbor matching.
+ * and other information for indexing a set of points for nearest-neighbour matching.
  */
-class KMeansIndex : public NNIndex
+template <typename ELEM_TYPE, typename DIST_TYPE = typename DistType<ELEM_TYPE>::type >
+class KMeansIndex : public NNIndex<ELEM_TYPE>
 {
 
        /**
@@ -273,7 +104,7 @@ class KMeansIndex : public NNIndex
      /**
      * Cluster border index. This is used in the tree search phase when determining
      * the closest cluster to explore next. A zero value takes into account only
-     * the cluster centers, a value greater then zero also take into account the size
+     * the cluster centres, a value greater then zero also take into account the size
      * of the cluster.
      */
     float cb_index;
@@ -281,17 +112,19 @@ class KMeansIndex : public NNIndex
        /**
         * The dataset used by this index
         */
-    const Matrix<float> dataset;
+    const Matrix<ELEM_TYPE> dataset;
+
+    const IndexParams& index_params;
 
     /**
     * Number of features in the dataset.
     */
-    int size_;
+    size_t size_;
 
     /**
     * Length of each feature.
     */
-    int veclen_;
+    size_t veclen_;
 
 
        /**
@@ -301,19 +134,19 @@ class KMeansIndex : public NNIndex
                /**
                 * The cluster center.
                 */
-               float* pivot;
+               DIST_TYPE* pivot;
                /**
                 * The cluster radius.
                 */
-               float radius;
+               DIST_TYPE radius;
                /**
                 * The cluster mean radius.
                 */
-               float mean_radius;
+               DIST_TYPE mean_radius;
                /**
                 * The cluster variance.
                 */
-               float variance;
+               DIST_TYPE variance;
                /**
                 * The cluster size (number of points in the cluster)
                 */
@@ -340,12 +173,6 @@ class KMeansIndex : public NNIndex
      */
     typedef BranchStruct<KMeansNode> BranchSt;
 
-    /**
-     * Priority queue storing intermediate branches in the best-bin-first search
-     */
-    Heap<BranchSt>* heap;
-
-
 
        /**
         * The root node in the tree.
@@ -373,6 +200,8 @@ class KMeansIndex : public NNIndex
        int memoryCounter;
 
 
+       typedef void (KMeansIndex::*centersAlgFunction)(int, int*, int, int*, int&);
+
     /**
     * The function used for choosing the cluster centers.
     */
@@ -380,6 +209,173 @@ class KMeansIndex : public NNIndex
 
 
 
+    /**
+    * Chooses the initial centers in the k-means clustering in a random manner.
+    *
+    * Params:
+    *     k = number of centers
+    *     vecs = the dataset of points
+    *     indices = indices in the dataset
+    *     indices_length = length of indices vector
+    *
+    */
+    void chooseCentersRandom(int k, int* indices, int indices_length, int* centers, int& centers_length)
+    {
+        UniqueRandom r(indices_length);
+
+        int index;
+        for (index=0;index<k;++index) {
+            bool duplicate = true;
+            int rnd;
+            while (duplicate) {
+                duplicate = false;
+                rnd = r.next();
+                if (rnd<0) {
+                    centers_length = index;
+                    return;
+                }
+
+                centers[index] = indices[rnd];
+
+                for (int j=0;j<index;++j) {
+                    float sq = flann_dist(dataset[centers[index]],dataset[centers[index]]+dataset.cols,dataset[centers[j]]);
+                    if (sq<1e-16) {
+                        duplicate = true;
+                    }
+                }
+            }
+        }
+
+        centers_length = index;
+    }
+
+
+    /**
+    * Chooses the initial centers in the k-means using Gonzales' algorithm
+    * so that the centers are spaced apart from each other.
+    *
+    * Params:
+    *     k = number of centers
+    *     vecs = the dataset of points
+    *     indices = indices in the dataset
+    * Returns:
+    */
+    void chooseCentersGonzales(int k, int* indices, int indices_length, int* centers, int& centers_length)
+    {
+        int n = indices_length;
+
+        int rnd = rand_int(n);
+        assert(rnd >=0 && rnd < n);
+
+        centers[0] = indices[rnd];
+
+        int index;
+        for (index=1; index<k; ++index) {
+
+            int best_index = -1;
+            float best_val = 0;
+            for (int j=0;j<n;++j) {
+                float dist = flann_dist(dataset[centers[0]],dataset[centers[0]]+dataset.cols,dataset[indices[j]]);
+                for (int i=1;i<index;++i) {
+                        float tmp_dist = flann_dist(dataset[centers[i]],dataset[centers[i]]+dataset.cols,dataset[indices[j]]);
+                    if (tmp_dist<dist) {
+                        dist = tmp_dist;
+                    }
+                }
+                if (dist>best_val) {
+                    best_val = dist;
+                    best_index = j;
+                }
+            }
+            if (best_index!=-1) {
+                centers[index] = indices[best_index];
+            }
+            else {
+                break;
+            }
+        }
+        centers_length = index;
+    }
+
+
+    /**
+    * Chooses the initial centers in the k-means using the algorithm
+    * proposed in the KMeans++ paper:
+    * Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding
+    *
+    * Implementation of this function was converted from the one provided in Arthur's code.
+    *
+    * Params:
+    *     k = number of centers
+    *     vecs = the dataset of points
+    *     indices = indices in the dataset
+    * Returns:
+    */
+    void chooseCentersKMeanspp(int k, int* indices, int indices_length, int* centers, int& centers_length)
+    {
+        int n = indices_length;
+
+        double currentPot = 0;
+        double* closestDistSq = new double[n];
+
+        // Choose one random center and set the closestDistSq values
+        int index = rand_int(n);
+        assert(index >=0 && index < n);
+        centers[0] = indices[index];
+
+        for (int i = 0; i < n; i++) {
+            closestDistSq[i] = flann_dist(dataset[indices[i]], dataset[indices[i]] + dataset.cols, dataset[indices[index]]);
+            currentPot += closestDistSq[i];
+        }
+
+
+        const int numLocalTries = 1;
+
+        // Choose each center
+        int centerCount;
+        for (centerCount = 1; centerCount < k; centerCount++) {
+
+            // Repeat several trials
+            double bestNewPot = -1;
+            int bestNewIndex;
+            for (int localTrial = 0; localTrial < numLocalTries; localTrial++) {
+
+                // Choose our center - have to be slightly careful to return a valid answer even accounting
+                // for possible rounding errors
+            double randVal = rand_double(currentPot);
+                for (index = 0; index < n-1; index++) {
+                    if (randVal <= closestDistSq[index])
+                        break;
+                    else
+                        randVal -= closestDistSq[index];
+                }
+
+                // Compute the new potential
+                double newPot = 0;
+                for (int i = 0; i < n; i++)
+                    newPot += min( flann_dist(dataset[indices[i]], dataset[indices[i]] + dataset.cols, dataset[indices[index]]), closestDistSq[i] );
+
+                // Store the best result
+                if (bestNewPot < 0 || newPot < bestNewPot) {
+                    bestNewPot = newPot;
+                    bestNewIndex = index;
+                }
+            }
+
+            // Add the appropriate center
+            centers[centerCount] = indices[bestNewIndex];
+            currentPot = bestNewPot;
+            for (int i = 0; i < n; i++)
+                closestDistSq[i] = min( flann_dist(dataset[indices[i]], dataset[indices[i]]+dataset.cols, dataset[indices[bestNewIndex]]), closestDistSq[i] );
+        }
+
+        centers_length = centerCount;
+
+       delete[] closestDistSq;
+    }
+
+
+
 public:
 
 
@@ -395,8 +391,8 @@ public:
         *              inputData = dataset with the input features
         *              params = parameters passed to the hierarchical k-means algorithm
         */
-       KMeansIndex(const Matrix<float>& inputData, const KMeansIndexParams& params = KMeansIndexParams() )
-               : dataset(inputData), root(NULL), indices(NULL)
+       KMeansIndex(const Matrix<ELEM_TYPE>& inputData, const KMeansIndexParams& params = KMeansIndexParams() )
+               : dataset(inputData), index_params(params), root(NULL), indices(NULL)
        {
                memoryCounter = 0;
 
@@ -410,15 +406,20 @@ public:
         }
         flann_centers_init_t centersInit = params.centers_init;
 
-               if ( centerAlgs.find(centersInit) != centerAlgs.end() ) {
-                       chooseCenters = centerAlgs[centersInit];
-               }
+        if (centersInit==CENTERS_RANDOM) {
+               chooseCenters = &KMeansIndex::chooseCentersRandom;
+        }
+        else if (centersInit==CENTERS_GONZALES) {
+               chooseCenters = &KMeansIndex::chooseCentersGonzales;
+        }
+        else if (centersInit==CENTERS_KMEANSPP) {
+                       chooseCenters = &KMeansIndex::chooseCentersKMeanspp;
+        }
                else {
                        throw FLANNException("Unknown algorithm for choosing initial centers.");
                }
-        cb_index = 0.4f;
+        cb_index = 0.4;
 
-               heap = new Heap<BranchSt>(size_);
        }
 
 
@@ -432,7 +433,6 @@ public:
                if (root != NULL) {
                        free_centers(root);
                }
-               delete heap;
         if (indices!=NULL) {
                  delete[] indices;
         }
@@ -441,7 +441,7 @@ public:
     /**
     *  Returns size of index.
     */
-    int size() const
+       size_t size() const
     {
         return size_;
     }
@@ -449,7 +449,7 @@ public:
     /**
     * Returns the length of an index feature.
     */
-    int veclen() const
+    size_t veclen() const
     {
         return veclen_;
     }
@@ -480,7 +480,7 @@ public:
                }
 
                indices = new int[size_];
-               for (int i=0;i<size_;++i) {
+               for (size_t i=0;i<size_;++i) {
                        indices[i] = i;
                }
 
@@ -492,7 +492,6 @@ public:
 
     void saveIndex(FILE* stream)
     {
-       save_header(stream, *this);
        save_value(stream, branching);
        save_value(stream, max_iter);
        save_value(stream, memoryCounter);
@@ -500,17 +499,11 @@ public:
        save_value(stream, *indices, size_);
 
                save_tree(stream, root);
-
     }
 
 
     void loadIndex(FILE* stream)
     {
-       IndexHeader header = load_header(stream);
-
-       if (header.rows!=size() || header.cols!=veclen()) {
-               throw FLANNException("The index saved belongs to a different dataset");
-       }
        load_value(stream, branching);
        load_value(stream, max_iter);
        load_value(stream, memoryCounter);
@@ -537,25 +530,30 @@ public:
      *     vec = the vector for which to search the nearest neighbors
      *     searchParams = parameters that influence the search algorithm (checks, cb_index)
      */
-    void findNeighbors(ResultSet& result, const float* vec, const SearchParams& searchParams)
+    void findNeighbors(ResultSet<ELEM_TYPE>& result, const ELEM_TYPE* vec, const SearchParams& searchParams)
     {
+
         int maxChecks = searchParams.checks;
 
         if (maxChecks<0) {
             findExactNN(root, result, vec);
         }
         else {
-            heap->clear();
+             // Priority queue storing intermediate branches in the best-bin-first search
+            Heap<BranchSt>* heap = new Heap<BranchSt>(size_);
+
             int checks = 0;
 
-            findNN(root, result, vec, checks, maxChecks);
+            findNN(root, result, vec, checks, maxChecks, heap);
 
             BranchSt branch;
             while (heap->popMin(branch) && (checks<maxChecks || !result.full())) {
                 KMeansNode node = branch.node;
-                findNN(node, result, vec, checks, maxChecks);
+                findNN(node, result, vec, checks, maxChecks, heap);
             }
             assert(result.full());
+
+            delete heap;
         }
 
     }
@@ -568,7 +566,7 @@ public:
      *     numClusters = number of clusters to have in the clustering computed
      * Returns: number of cluster centers
      */
-    int getClusterCenters(Matrix<float>& centers)
+    int getClusterCenters(Matrix<DIST_TYPE>& centers)
     {
         int numClusters = centers.rows;
         if (numClusters<1) {
@@ -584,8 +582,8 @@ public:
 
 
         for (int i=0;i<clusterCount;++i) {
-            float* center = clusters[i]->pivot;
-            for (int j=0;j<veclen_;++j) {
+            DIST_TYPE* center = clusters[i]->pivot;
+            for (size_t j=0;j<veclen_;++j) {
                 centers[i][j] = center[j];
             }
         }
@@ -594,13 +592,10 @@ public:
         return clusterCount;
     }
 
-//    Params estimateSearchParams(float precision, Dataset<float>* testset = NULL)
-//    {
-//        Params params;
-//
-//        return params;
-//    }
-
+       const IndexParams* getParameters() const
+       {
+               return &index_params;
+       }
 
 
 private:
@@ -626,7 +621,7 @@ private:
     {
        node = pool.allocate<KMeansNodeSt>();
        load_value(stream, *node);
-       node->pivot = new float[veclen_];
+       node->pivot = new DIST_TYPE[veclen_];
        load_value(stream, *(node->pivot), veclen_);
        if (node->childs==NULL) {
                int indices_offset;
@@ -664,27 +659,27 @@ private:
         */
        void computeNodeStatistics(KMeansNode node, int* indices, int indices_length) {
 
-               float radius = 0;
-               float variance = 0;
-               float* mean = new float[veclen_];
-               memoryCounter += veclen_*sizeof(float);
+               DIST_TYPE radius = 0;
+               DIST_TYPE variance = 0;
+               DIST_TYPE* mean = new DIST_TYPE[veclen_];
+               memoryCounter += veclen_*sizeof(DIST_TYPE);
 
         memset(mean,0,veclen_*sizeof(float));
 
-               for (int i=0;i<size_;++i) {
-                       float* vec = dataset[indices[i]];
-            for (int j=0;j<veclen_;++j) {
+               for (size_t i=0;i<size_;++i) {
+                       ELEM_TYPE* vec = dataset[indices[i]];
+            for (size_t j=0;j<veclen_;++j) {
                 mean[j] += vec[j];
             }
                        variance += flann_dist(vec,vec+veclen_,zero);
                }
-               for (int j=0;j<veclen_;++j) {
+               for (size_t j=0;j<veclen_;++j) {
                        mean[j] /= size_;
                }
                variance /= size_;
                variance -= flann_dist(mean,mean+veclen_,zero);
 
-               float tmp = 0;
+               DIST_TYPE tmp = 0;
                for (int i=0;i<indices_length;++i) {
                        tmp = flann_dist(mean, mean + veclen_, dataset[indices[i]]);
                        if (tmp>radius) {
@@ -721,9 +716,9 @@ private:
                        return;
                }
 
-               float** initial_centers = new float*[branching];
+               int* centers_idx = new int[branching];
         int centers_length;
-               chooseCenters(branching, dataset, indices, indices_length, initial_centers, centers_length);
+               (this->*chooseCenters)(branching, indices, indices_length, centers_idx, centers_length);
 
                if (centers_length<branching) {
             node->indices = indices;
@@ -733,13 +728,14 @@ private:
                }
 
 
-        Matrix<double> dcenters(branching,veclen_);
+        Matrix<double> dcenters(new double[branching*veclen_],branching,veclen_);
         for (int i=0; i<centers_length; ++i) {
-            for (int k=0; k<veclen_; ++k) {
-                dcenters[i][k] = double(initial_centers[i][k]);
+               ELEM_TYPE* vec = dataset[centers_idx[i]];
+            for (size_t k=0; k<veclen_; ++k) {
+                dcenters[i][k] = double(vec[k]);
             }
         }
-               delete[] initial_centers;
+               delete[] centers_idx;
 
                float* radiuses = new float[branching];
                int* count = new int[branching];
@@ -779,15 +775,15 @@ private:
                 radiuses[i] = 0;
                        }
             for (int i=0;i<indices_length;++i) {
-                               float* vec = dataset[indices[i]];
+                               ELEM_TYPE* vec = dataset[indices[i]];
                                double* center = dcenters[belongs_to[i]];
-                               for (int k=0;k<veclen_;++k) {
+                               for (size_t k=0;k<veclen_;++k) {
                                        center[k] += vec[k];
                                }
                        }
                        for (int i=0;i<branching;++i) {
                 int cnt = count[i];
-                for (int k=0;k<veclen_;++k) {
+                for (size_t k=0;k<veclen_;++k) {
                     dcenters[i][k] /= cnt;
                 }
                        }
@@ -838,13 +834,13 @@ private:
 
                }
 
-        float** centers = new float*[branching];
+        DIST_TYPE** centers = new DIST_TYPE*[branching];
 
         for (int i=0; i<branching; ++i) {
-                       centers[i] = new float[veclen_];
-                       memoryCounter += veclen_*sizeof(float);
-            for (int k=0; k<veclen_; ++k) {
-                centers[i][k] = (float)dcenters[i][k];
+                       centers[i] = new DIST_TYPE[veclen_];
+                       memoryCounter += veclen_*sizeof(DIST_TYPE);
+            for (size_t k=0; k<veclen_; ++k) {
+                centers[i][k] = dcenters[i][k];
             }
                }
 
@@ -882,6 +878,7 @@ private:
                        start=end;
                }
 
+               delete[] dcenters.data;
                delete[] centers;
                delete[] radiuses;
                delete[] count;
@@ -903,16 +900,17 @@ private:
      */
 
 
-       void findNN(KMeansNode node, ResultSet& result, const float* vec, int& checks, int maxChecks)
+       void findNN(KMeansNode node, ResultSet<ELEM_TYPE>& result, const ELEM_TYPE* vec, int& checks, int maxChecks,
+                       Heap<BranchSt>* heap)
        {
                // Ignore those clusters that are too far away
                {
-                       float bsq = flann_dist(vec, vec+veclen_, node->pivot);
-                       float rsq = node->radius;
-                       float wsq = result.worstDist();
+                       DIST_TYPE bsq = flann_dist(vec, vec+veclen_, node->pivot);
+                       DIST_TYPE rsq = node->radius;
+                       DIST_TYPE wsq = result.worstDist();
 
-                       float val = bsq-rsq-wsq;
-                       float val2 = val*val-4*rsq*wsq;
+                       DIST_TYPE val = bsq-rsq-wsq;
+                       DIST_TYPE val2 = val*val-4*rsq*wsq;
 
                        //if (val>0) {
                        if (val>0 && val2>0) {
@@ -931,9 +929,9 @@ private:
                }
                else {
                        float* domain_distances = new float[branching];
-                       int closest_center = exploreNodeBranches(node, vec, domain_distances);
+                       int closest_center = exploreNodeBranches(node, vec, domain_distances, heap);
                        delete[] domain_distances;
-                       findNN(node->childs[closest_center],result,vec, checks, maxChecks);
+                       findNN(node->childs[closest_center],result,vec, checks, maxChecks, heap);
                }
        }
 
@@ -945,7 +943,7 @@ private:
         *     distances = array with the distances to each child node.
         * Returns:
         */
-       int exploreNodeBranches(KMeansNode node, const float* q, float* domain_distances)
+       int exploreNodeBranches(KMeansNode node, const ELEM_TYPE* q, float* domain_distances, Heap<BranchSt>* heap)
        {
 
                int best_index = 0;
@@ -977,7 +975,7 @@ private:
        /**
         * Function the performs exact nearest neighbor search by traversing the entire tree.
         */
-       void findExactNN(KMeansNode node, ResultSet& result, const float* vec)
+       void findExactNN(KMeansNode node, ResultSet<ELEM_TYPE>& result, const ELEM_TYPE* vec)
        {
                // Ignore those clusters that are too far away
                {
@@ -1019,7 +1017,7 @@ private:
         *
         * I computes the order in which to traverse the child nodes of a particular node.
         */
-       void getCenterOrdering(KMeansNode node, const float* q, int* sort_indices)
+       void getCenterOrdering(KMeansNode node, const ELEM_TYPE* q, int* sort_indices)
        {
                float* domain_distances = new float[branching];
                for (int i=0;i<branching;++i) {
@@ -1114,6 +1112,6 @@ private:
 
 //register_index(KMEANS,KMeansTree)
 
-}
+} // namespace cvflann
 
 #endif //KMEANSTREE_H
similarity index 67%
rename from 3rdparty/flann/linear_index.h
rename to modules/flann/include/opencv2/flann/linear_index.h
index 19a4fd4..b9fe4a6 100644 (file)
 #ifndef LINEARSEARCH_H
 #define LINEARSEARCH_H
 
-#include "constants.h"
-#include "nn_index.h"
+#include "opencv2/flann/general.h"
+#include "opencv2/flann/nn_index.h"
+
 
 namespace cvflann
 {
 
-class LinearIndex : public NNIndex {
+struct LinearIndexParams : public IndexParams {
+       LinearIndexParams() : IndexParams(LINEAR) {};
+
+       flann_algorithm_t getIndexType() const { return algorithm; }
+
+       void print() const
+       {
+               logger.info("Index type: %d\n",(int)algorithm);
+       }
+};
+
 
-       const Matrix<float> dataset;
+template <typename ELEM_TYPE, typename DIST_TYPE = typename DistType<ELEM_TYPE>::type >
+class LinearIndex : public NNIndex<ELEM_TYPE>
+{
+       const Matrix<ELEM_TYPE> dataset;
+       const LinearIndexParams& index_params;
 
 public:
 
-       LinearIndex(const Matrix<float>& inputData, const LinearIndexParams& params = LinearIndexParams() ) : dataset(inputData)
+       LinearIndex(const Matrix<ELEM_TYPE>& inputData, const LinearIndexParams& params = LinearIndexParams() ) :
+               dataset(inputData), index_params(params)
        {
        }
 
@@ -53,12 +69,12 @@ public:
     }
 
 
-       int size() const
+       size_t size() const
        {
                return dataset.rows;
        }
 
-       int veclen() const
+       size_t veclen() const
        {
                return dataset.cols;
        }
@@ -74,32 +90,31 @@ public:
                /* nothing to do here for linear search */
        }
 
-    void saveIndex(FILE* /*stream*/)
+    void saveIndex(FILE* stream)
     {
                /* nothing to do here for linear search */
     }
 
 
-    void loadIndex(FILE* /*stream*/)
+    void loadIndex(FILE* stream)
     {
                /* nothing to do here for linear search */
     }
 
-       void findNeighbors(ResultSet& resultSet, const float* /*vec*/, const SearchParams& /*searchParams*/)
+       void findNeighbors(ResultSet<ELEM_TYPE>& resultSet, const ELEM_TYPE* vec, const SearchParams& searchParams)
        {
-               for (int i=0;i<dataset.rows;++i) {
+               for (size_t i=0;i<dataset.rows;++i) {
                        resultSet.addPoint(dataset[i],i);
                }
        }
 
-//    Params estimateSearchParams(float precision, Matrix<float>* testset = NULL)
-//    {
-//        Params params;
-//        return params;
-//    }
+       const IndexParams* getParameters() const
+       {
+               return &index_params;
+       }
 
 };
 
-}
+} // namespace cvflann
 
 #endif // LINEARSEARCH_H
similarity index 97%
rename from 3rdparty/flann/logger.h
rename to modules/flann/include/opencv2/flann/logger.h
index b47887f..5d9a991 100644 (file)
@@ -33,9 +33,7 @@
 
 
 #include <cstdio>
-#include <stdarg.h>
-#include "common.h"
-#include "flann.h"
+#include "opencv2/flann/general.h"
 
 using namespace std;
 
@@ -88,6 +86,6 @@ public:
 
 extern Logger logger;
 
-}
+} // namespace cvflann
 
 #endif //LOGGER_H
diff --git a/modules/flann/include/opencv2/flann/matrix.h b/modules/flann/include/opencv2/flann/matrix.h
new file mode 100644 (file)
index 0000000..a293892
--- /dev/null
@@ -0,0 +1,118 @@
+/***********************************************************************
+ * Software License Agreement (BSD License)
+ *
+ * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
+ * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
+ *
+ * THE BSD LICENSE
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *************************************************************************/
+
+#ifndef DATASET_H
+#define DATASET_H
+
+#include <stdio.h>
+
+#include "opencv2/flann/general.h"
+
+
+namespace cvflann 
+{
+
+/**
+* Class that implements a simple rectangular matrix stored in a memory buffer and
+* provides convenient matrix-like access using the [] operators.
+*/
+template <typename T>
+class Matrix {
+public:
+    size_t rows;
+    size_t cols;
+    T* data;
+
+    Matrix() : rows(0), cols(0), data(NULL)
+    {
+    }
+
+    Matrix(T* data_, long rows_, long cols_) :
+        rows(rows_), cols(cols_), data(data_)
+       {
+       }
+
+    /**
+     * Convenience function for deallocating the storage data.
+     */
+    void free()
+    {
+        if (data!=NULL) delete[] data;
+    }
+
+       ~Matrix()
+       {
+       }
+
+    /**
+    * Operator that return a (pointer to a) row of the data.
+    */
+    T* operator[](size_t index)
+    {
+        return data+index*cols;
+    }
+
+    T* operator[](size_t index) const
+    {
+        return data+index*cols;
+    }
+};
+
+
+class UntypedMatrix
+{
+public:
+    size_t rows;
+    size_t cols;
+    void* data;
+    flann_datatype_t type;
+
+    UntypedMatrix(void* data_, long rows_, long cols_) :
+        rows(rows_), cols(cols_), data(data_)
+    {
+    }
+
+    ~UntypedMatrix()
+    {
+    }
+
+
+    template<typename T>
+    Matrix<T> as()
+    {
+        return Matrix<T>((T*)data, rows, cols);
+    }
+};
+
+
+
+} // namespace cvflann
+
+#endif //DATASET_H
similarity index 81%
rename from 3rdparty/flann/nn_index.h
rename to modules/flann/include/opencv2/flann/nn_index.h
index eeca4e0..7113c9f 100644 (file)
 #ifndef NNINDEX_H
 #define NNINDEX_H
 
-#include "flann.hpp"
-#include "constants.h"
-#include "common.h"
-#include "matrix.h"
-
 #include <string>
-#include <string.h>
+
+#include "opencv2/flann/general.h"
+#include "opencv2/flann/matrix.h"
 
 using namespace std;
 
 namespace cvflann
 {
 
+
+template <typename ELEM_TYPE>
 class ResultSet;
 
 /**
-* Nearest-neighbor index base class
+* Nearest-neighbour index base class
 */
+template <typename ELEM_TYPE>
 class NNIndex
 {
 public:
@@ -73,17 +73,17 @@ public:
        /**
        Method that searches for nearest-neighbors
        */
-       virtual void findNeighbors(ResultSet& result, const float* vec, const SearchParams& searchParams) = 0;
+       virtual void findNeighbors(ResultSet<ELEM_TYPE>& result, const ELEM_TYPE* vec, const SearchParams& searchParams) = 0;
 
        /**
        Number of features in this index.
        */
-       virtual int size() const = 0;
+       virtual size_t size() const = 0;
 
        /**
        The length of each vector in this index.
        */
-       virtual int veclen() const = 0;
+       virtual size_t veclen() const = 0;
 
        /**
        The amount of memory (in bytes) this index uses.
@@ -96,14 +96,13 @@ public:
        virtual flann_algorithm_t getType() const = 0;
 
        /**
-       Estimates the search parameters required in order to get a certain precision.
-       If testset is not given it uses cross-validation.
-       */
-//     virtual Params estimateSearchParams(float precision, Matrix<float>* testset = NULL) = 0;
+        * Returns the parameters used for the index
+        */
+       virtual const IndexParams* getParameters() const = 0;
 
 };
 
 
-}
+} // namespace cvflann
 
 #endif //NNINDEX_H
similarity index 99%
rename from 3rdparty/flann/object_factory.h
rename to modules/flann/include/opencv2/flann/object_factory.h
index 372bbe6..7318ec6 100644 (file)
@@ -88,6 +88,6 @@ public:
 
 };
 
-}
+} // namespace cvflann
 
 #endif /* OBJECT_FACTORY_H_ */
similarity index 99%
rename from 3rdparty/include/flann/random.h
rename to modules/flann/include/opencv2/flann/random.h
index 74d5a56..b08a269 100644 (file)
@@ -129,6 +129,6 @@ public:
        }
 };
 
-}
+} // namespace cvflann
 
 #endif //RANDOM_H
similarity index 82%
rename from 3rdparty/flann/result_set.h
rename to modules/flann/include/opencv2/flann/result_set.h
index b481a1f..241e7d5 100644 (file)
@@ -35,7 +35,7 @@
 #include <algorithm>
 #include <limits>
 #include <vector>
-#include "dist.h"
+#include "opencv2/flann/dist.h"
 
 using namespace std;
 
@@ -58,7 +58,7 @@ struct BranchStruct {
         return mindistsq<rhs.mindistsq;
        }
 
-    static BranchStruct<T> make_branch(T aNode, float dist)
+    static BranchStruct<T> make_branch(const T& aNode, float dist)
     {
         BranchStruct<T> branch;
         branch.node = aNode;
@@ -71,40 +71,39 @@ struct BranchStruct {
 
 
 
-
+template <typename ELEM_TYPE>
 class ResultSet
 {
 protected:
-       const float* target;
-       const float* target_end;
-    int veclen;
 
 public:
 
-       ResultSet(float* target_ = NULL, int veclen_ = 0) :
-               target(target_), veclen(veclen_) { target_end = target + veclen;}
+       virtual ~ResultSet() {};
 
-       virtual ~ResultSet() {}
-
-       virtual void init(const float* target_, int veclen_) = 0;
+       virtual void init(const ELEM_TYPE* target_, int veclen_) = 0;
 
        virtual int* getNeighbors() = 0;
 
        virtual float* getDistances() = 0;
 
-       virtual int size() const = 0;
+       virtual size_t size() const = 0;
 
        virtual bool full() const = 0;
 
-       virtual bool addPoint(float* point, int index) = 0;
+       virtual bool addPoint(const ELEM_TYPE* point, int index) = 0;
 
        virtual float worstDist() const = 0;
 
 };
 
 
-class KNNResultSet : public ResultSet
+template <typename ELEM_TYPE>
+class KNNResultSet : public ResultSet<ELEM_TYPE>
 {
+       const ELEM_TYPE* target;
+       const ELEM_TYPE* target_end;
+    int veclen;
+
        int* indices;
        float* dists;
     int capacity;
@@ -112,9 +111,11 @@ class KNNResultSet : public ResultSet
        int count;
 
 public:
-       KNNResultSet(int capacity_, float* target_ = NULL, int veclen_ = 0 ) :
-        ResultSet(target_, veclen_), capacity(capacity_), count(0)
+       KNNResultSet(int capacity_, ELEM_TYPE* target_ = NULL, int veclen_ = 0 ) :
+                       target(target_), veclen(veclen_), capacity(capacity_), count(0)
        {
+               target_end = target + veclen;
+
         indices = new int[capacity_];
         dists = new float[capacity_];
        }
@@ -125,7 +126,7 @@ public:
                delete[] dists;
        }
 
-       void init(const float* target_, int veclen_)
+       void init(const ELEM_TYPE* target_, int veclen_)
        {
         target = target_;
         veclen = veclen_;
@@ -144,7 +145,7 @@ public:
         return dists;
     }
 
-    int size() const
+    size_t size() const
     {
        return count;
     }
@@ -155,12 +156,12 @@ public:
        }
 
 
-       bool addPoint(float* point, int index)
+       bool addPoint(const ELEM_TYPE* point, int index)
        {
                for (int i=0;i<count;++i) {
                        if (indices[i]==index) return false;
                }
-               float dist = (float)flann_dist(target, target_end, point);
+               float dist = flann_dist(target, target_end, point);
 
                if (count<capacity) {
                        indices[count] = index;
@@ -198,8 +199,13 @@ public:
 /**
  * A result-set class used when performing a radius based search.
  */
-class RadiusResultSet : public ResultSet
+template <typename ELEM_TYPE>
+class RadiusResultSet : public ResultSet<ELEM_TYPE>
 {
+       const ELEM_TYPE* target;
+       const ELEM_TYPE* target_end;
+    int veclen;
+
        struct Item {
                int index;
                float dist;
@@ -244,7 +250,7 @@ public:
                if (dists!=NULL) delete[] dists;
        }
 
-       void init(const float* target_, int veclen_)
+       void init(const ELEM_TYPE* target_, int veclen_)
        {
         target = target_;
         veclen = veclen_;
@@ -279,9 +285,9 @@ public:
         return dists;
     }
 
-    int size() const
+    size_t size() const
     {
-       return (int)items.size();
+       return items.size();
     }
 
        bool full() const
@@ -289,11 +295,11 @@ public:
                return true;
        }
 
-       bool addPoint(float* point, int index)
+       bool addPoint(const ELEM_TYPE* point, int index)
        {
                Item it;
                it.index = index;
-               it.dist = (float)flann_dist(target, target_end, point);
+               it.dist = flann_dist(target, target_end, point);
                if (it.dist<=radius) {
                        items.push_back(it);
                        push_heap(items.begin(), items.end());
@@ -309,6 +315,6 @@ public:
 
 };
 
-}
+} // namespace cvflann
 
 #endif //RESULTSET_H
diff --git a/modules/flann/include/opencv2/flann/sampling.h b/modules/flann/include/opencv2/flann/sampling.h
new file mode 100644 (file)
index 0000000..2240182
--- /dev/null
@@ -0,0 +1,94 @@
+/***********************************************************************
+ * Software License Agreement (BSD License)
+ *
+ * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
+ * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *************************************************************************/
+
+
+#ifndef SAMPLING_H_
+#define SAMPLING_H_
+
+
+#include "opencv2/flann/matrix.h"
+#include "opencv2/flann/random.h"
+
+
+namespace cvflann
+{
+
+template<typename T>
+Matrix<T> random_sample(Matrix<T>& srcMatrix, long size, bool remove = false)
+{
+    UniqueRandom rand(srcMatrix.rows);
+    Matrix<T> newSet(new T[size * srcMatrix.cols], size,srcMatrix.cols);
+
+    T *src,*dest;
+    for (long i=0;i<size;++i) {
+        long r = rand.next();
+        dest = newSet[i];
+        src = srcMatrix[r];
+        for (size_t j=0;j<srcMatrix.cols;++j) {
+            dest[j] = src[j];
+        }
+        if (remove) {
+            dest = srcMatrix[srcMatrix.rows-i-1];
+            src = srcMatrix[r];
+            for (size_t j=0;j<srcMatrix.cols;++j) {
+                swap(*src,*dest);
+                src++;
+                dest++;
+            }
+        }
+    }
+
+    if (remove) {
+       srcMatrix.rows -= size;
+    }
+
+    return newSet;
+}
+
+template<typename T>
+Matrix<T> random_sample(const Matrix<T>& srcMatrix, size_t size)
+{
+    UniqueRandom rand(srcMatrix.rows);
+    Matrix<T> newSet(new T[size * srcMatrix.cols], size,srcMatrix.cols);
+
+    T *src,*dest;
+    for (size_t i=0;i<size;++i) {
+        long r = rand.next();
+        dest = newSet[i];
+        src = srcMatrix[r];
+        for (size_t j=0;j<srcMatrix.cols;++j) {
+            dest[j] = src[j];
+        }
+    }
+
+    return newSet;
+}
+
+} // namespace cvflann
+
+#endif /* SAMPLING_H_ */
diff --git a/modules/flann/include/opencv2/flann/saving.h b/modules/flann/include/opencv2/flann/saving.h
new file mode 100644 (file)
index 0000000..1083993
--- /dev/null
@@ -0,0 +1,115 @@
+/***********************************************************************
+ * Software License Agreement (BSD License)
+ *
+ * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
+ * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE NNIndexGOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *************************************************************************/
+
+#ifndef SAVING_H_
+#define SAVING_H_
+
+#include "opencv2/flann/general.h"
+#include "opencv2/flann/nn_index.h"
+#include <cstdio>
+#include <cstring>
+
+namespace cvflann
+{
+template <typename T> struct Datatype {};
+template<> struct Datatype<char> { static flann_datatype_t type() { return INT8; } };
+template<> struct Datatype<short> { static flann_datatype_t type() { return INT16; } };
+template<> struct Datatype<int> { static flann_datatype_t type() { return INT32; } };
+template<> struct Datatype<unsigned char> { static flann_datatype_t type() { return UINT8; } };
+template<> struct Datatype<unsigned short> { static flann_datatype_t type() { return UINT16; } };
+template<> struct Datatype<unsigned int> { static flann_datatype_t type() { return UINT32; } };
+template<> struct Datatype<float> { static flann_datatype_t type() { return FLOAT32; } };
+template<> struct Datatype<double> { static flann_datatype_t type() { return FLOAT64; } };
+
+
+extern const char FLANN_SIGNATURE[];
+extern const char FLANN_VERSION[];
+
+/**
+ * Structure representing the index header.
+ */
+struct IndexHeader
+{
+       char signature[16];
+       char version[16];
+       flann_datatype_t data_type;
+       flann_algorithm_t index_type;
+       int rows;
+       int cols;
+};
+
+/**
+ * Saves index header to stream
+ *
+ * @param stream - Stream to save to
+ * @param index - The index to save
+ */
+template<typename ELEM_TYPE>
+void save_header(FILE* stream, const NNIndex<ELEM_TYPE>& index)
+{
+       IndexHeader header;
+       memset(header.signature, 0 , sizeof(header.signature));
+       strcpy(header.signature, FLANN_SIGNATURE);
+       memset(header.version, 0 , sizeof(header.version));
+       strcpy(header.version, FLANN_VERSION);
+       header.data_type = Datatype<ELEM_TYPE>::type();
+       header.index_type = index.getType();
+       header.rows = index.size();
+       header.cols = index.veclen();
+
+       std::fwrite(&header, sizeof(header),1,stream);
+}
+
+
+/**
+ *
+ * @param stream - Stream to load from
+ * @return Index header
+ */
+IndexHeader load_header(FILE* stream);
+
+
+template<typename T>
+void save_value(FILE* stream, const T& value, int count = 1)
+{
+       fwrite(&value, sizeof(value),count, stream);
+}
+
+
+template<typename T>
+void load_value(FILE* stream, T& value, int count = 1)
+{
+       int read_cnt = fread(&value, sizeof(value),count, stream);
+       if (read_cnt!=count) {
+               throw FLANNException("Cannot read from file");
+       }
+}
+
+} // namespace cvflann
+
+#endif /* SAVING_H_ */
similarity index 99%
rename from 3rdparty/flann/simplex_downhill.h
rename to modules/flann/include/opencv2/flann/simplex_downhill.h
index b995398..5e0f665 100644 (file)
@@ -181,6 +181,6 @@ float optimizeSimplexDownhill(T* points, int n, F func, float* vals = NULL )
     return bestVal;
 }
 
-}
+} // namespace cvflann
 
 #endif //SIMPLEX_DOWNHILL_H
similarity index 99%
rename from 3rdparty/flann/timer.h
rename to modules/flann/include/opencv2/flann/timer.h
index c5d2aef..bebe8b1 100644 (file)
@@ -85,6 +85,6 @@ public:
 
 };
 
-}
+}// namespace cvflann
 
 #endif // TIMER_H
diff --git a/modules/flann/src/flann.cpp b/modules/flann/src/flann.cpp
new file mode 100644 (file)
index 0000000..612af35
--- /dev/null
@@ -0,0 +1,222 @@
+/***********************************************************************
+ * Software License Agreement (BSD License)
+ *
+ * Copyright 2008-2009  Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
+ * Copyright 2008-2009  David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *************************************************************************/
+
+#include <cstdio>
+#include <cstdarg>
+#include <sstream>
+
+#include "opencv2/flann/dist.h"
+#include "opencv2/flann/index_testing.h"
+#include "opencv2/flann/logger.h"
+#include "opencv2/flann/logger.h"
+#include "opencv2/flann/saving.h"
+#include "opencv2/flann/general.h"
+
+// index types
+#include "opencv2/flann/all_indices.h"
+
+namespace cvflann
+{
+// ----------------------- dist.cpp ---------------------------
+
+/** Global variable indicating the distance metric
+ * to be used.
+ */
+flann_distance_t flann_distance_type = EUCLIDEAN;
+
+/**
+ * Zero iterator that emulates a zero feature.
+ */
+ZeroIterator<float> zero;
+
+/**
+ * Order of Minkowski distance to use.
+ */
+int flann_minkowski_order;
+
+
+double euclidean_dist(const unsigned char* first1, const unsigned char* last1, unsigned char* first2, double acc)
+{
+       double distsq = acc;
+       double diff0, diff1, diff2, diff3;
+       const unsigned char* lastgroup = last1 - 3;
+
+       while (first1 < lastgroup) {
+               diff0 = first1[0] - first2[0];
+               diff1 = first1[1] - first2[1];
+               diff2 = first1[2] - first2[2];
+               diff3 = first1[3] - first2[3];
+               distsq += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3;
+               first1 += 4;
+               first2 += 4;
+       }
+       while (first1 < last1) {
+               diff0 = *first1++ - *first2++;
+               distsq += diff0 * diff0;
+       }
+       return distsq;
+}
+
+// ----------------------- index_testing.cpp ---------------------------
+
+int countCorrectMatches(int* neighbors, int* groundTruth, int n)
+{
+    int count = 0;
+    for (int i=0;i<n;++i) {
+        for (int k=0;k<n;++k) {
+            if (neighbors[i]==groundTruth[k]) {
+                count++;
+                break;
+            }
+        }
+    }
+    return count;
+}
+
+// ----------------------- logger.cpp ---------------------------
+
+Logger logger;
+
+int Logger::log(int level, const char* fmt, ...)
+{
+    if (level > logLevel ) return -1;
+
+    int ret;
+    va_list arglist;
+    va_start(arglist, fmt);
+    ret = vfprintf(stream, fmt, arglist);
+    va_end(arglist);
+
+    return ret;
+}
+
+int Logger::log(int level, const char* fmt, va_list arglist)
+{
+    if (level > logLevel ) return -1;
+
+    int ret;
+    ret = vfprintf(stream, fmt, arglist);
+
+    return ret;
+}
+
+
+#define LOG_METHOD(NAME,LEVEL) \
+    int Logger::NAME(const char* fmt, ...) \
+    { \
+        int ret; \
+        va_list ap; \
+        va_start(ap, fmt); \
+        ret = log(LEVEL, fmt, ap); \
+        va_end(ap); \
+        return ret; \
+    }
+
+
+LOG_METHOD(fatal, LOG_FATAL)
+LOG_METHOD(error, LOG_ERROR)
+LOG_METHOD(warn, LOG_WARN)
+LOG_METHOD(info, LOG_INFO)
+
+// ----------------------- random.cpp ---------------------------
+
+void seed_random(unsigned int seed)
+{
+    srand(seed);
+}
+
+double rand_double(double high, double low)
+{
+    return low + ((high-low) * (std::rand() / (RAND_MAX + 1.0)));
+}
+
+
+int rand_int(int high, int low)
+{
+    return low + (int) ( double(high-low) * (std::rand() / (RAND_MAX + 1.0)));
+}
+
+// ----------------------- saving.cpp ---------------------------
+
+const char FLANN_SIGNATURE[] = "FLANN_INDEX";
+const char FLANN_VERSION[] = "1.5.0";
+
+
+IndexHeader load_header(FILE* stream)
+{
+       IndexHeader header;
+       int read_size = fread(&header,sizeof(header),1,stream);
+
+       if (read_size!=1) {
+               throw FLANNException("Invalid index file, cannot read");
+       }
+
+       if (strcmp(header.signature,FLANN_SIGNATURE)!=0) {
+               throw FLANNException("Invalid index file, wrong signature");
+       }
+
+       return header;
+
+}
+
+// ----------------------- flann.cpp ---------------------------
+
+
+void log_verbosity(int level)
+{
+    if (level>=0) {
+        logger.setLevel(level);
+    }
+}
+
+void set_distance_type(flann_distance_t distance_type, int order)
+{
+       flann_distance_type = distance_type;
+       flann_minkowski_order = order;
+}
+
+class StaticInit
+{
+public:
+       StaticInit()
+       {
+               ParamsFactory::instance().register_<LinearIndexParams>(LINEAR);
+               ParamsFactory::instance().register_<KDTreeIndexParams>(KDTREE);
+               ParamsFactory::instance().register_<KMeansIndexParams>(KMEANS);
+               ParamsFactory::instance().register_<CompositeIndexParams>(COMPOSITE);
+               ParamsFactory::instance().register_<AutotunedIndexParams>(AUTOTUNED);
+//             ParamsFactory::instance().register_<SavedIndexParams>(SAVED);
+       }
+};
+StaticInit __init;
+
+
+} // namespace cvflann
+
+
+
diff --git a/modules/flann/src/precomp.hpp b/modules/flann/src/precomp.hpp
new file mode 100644 (file)
index 0000000..e69de29
index 9bbde35..d092808 100644 (file)
@@ -9,6 +9,7 @@ include_directories(
     "${CMAKE_SOURCE_DIR}/modules/highgui/include"
     "${CMAKE_SOURCE_DIR}/modules/video/include"
     "${CMAKE_SOURCE_DIR}/modules/features2d/include"
+    "${CMAKE_SOURCE_DIR}/modules/flann/include"
     "${CMAKE_SOURCE_DIR}/modules/calib3d/include"
     "${CMAKE_SOURCE_DIR}/modules/legacy/include"
     )
index fab6d26..9e6812b 100644 (file)
@@ -1 +1 @@
-define_opencv_module(legacy opencv_core opencv_imgproc opencv_calib3d opencv_features2d opencv_highgui opencv_video)
+define_opencv_module(legacy opencv_core opencv_imgproc opencv_calib3d opencv_features2d opencv_highgui opencv_video opencv_flann)
index 681f8d8..acf2acb 100644 (file)
@@ -12,6 +12,7 @@ include_directories(
     "${CMAKE_SOURCE_DIR}/modules/highgui/include"
     "${CMAKE_SOURCE_DIR}/modules/ml/include"
     "${CMAKE_SOURCE_DIR}/modules/features2d/include"
+    "${CMAKE_SOURCE_DIR}/modules/flann/include"
     "${CMAKE_SOURCE_DIR}/modules/calib3d/include"
     "${CMAKE_SOURCE_DIR}/modules/objdetect/include"
     "${CMAKE_SOURCE_DIR}/modules/legacy/include"
index 1a963a0..eb39a0c 100644 (file)
@@ -9,6 +9,7 @@ include_directories(
     "${CMAKE_SOURCE_DIR}/modules/highgui/include"
     "${CMAKE_SOURCE_DIR}/modules/video/include"
     "${CMAKE_SOURCE_DIR}/modules/features2d/include"
+    "${CMAKE_SOURCE_DIR}/modules/flann/include"
     "${CMAKE_SOURCE_DIR}/modules/calib3d/include"
     "${CMAKE_SOURCE_DIR}/modules/legacy/include"
     )
index bc7e632..01aa794 100644 (file)
@@ -13,6 +13,7 @@ include_directories("${CMAKE_SOURCE_DIR}/include/opencv"
                                        "${CMAKE_SOURCE_DIR}/modules/core/include"
                                        "${CMAKE_SOURCE_DIR}/modules/imgproc/include"
                                        "${CMAKE_SOURCE_DIR}/modules/features2d/include"
+                                       "${CMAKE_SOURCE_DIR}/modules/flann/include"
                                        "${CMAKE_SOURCE_DIR}/modules/calib3d/include"
                                        "${CMAKE_SOURCE_DIR}/modules/highgui/include"
                                        "${CMAKE_SOURCE_DIR}/modules/objdetect/include"
index f739693..4a25f2f 100644 (file)
@@ -15,6 +15,7 @@ include_directories   (
                        "${CMAKE_SOURCE_DIR}/modules/core/include"
                        "${CMAKE_SOURCE_DIR}/modules/imgproc/include"
                        "${CMAKE_SOURCE_DIR}/modules/features2d/include"
+                       "${CMAKE_SOURCE_DIR}/modules/flann/include"
                        "${CMAKE_SOURCE_DIR}/modules/calib3d/include"
                        "${CMAKE_SOURCE_DIR}/modules/highgui/include"
                        "${CMAKE_SOURCE_DIR}/modules/objdetect/include"