mirror of
https://github.com/opencv/opencv.git
synced 2026-11-20 08:15:26 -06:00
flann: fix Index::radiusSearch output size mismatch #28990 ## Problem `Index::radiusSearch` returns `nn` — the number of neighbors found within the radius — but the output arrays `_indices` and `_dists` are always allocated with `maxResults` columns regardless of how many neighbors were actually found. This creates two inconsistencies: 1. When `nn < maxResults`, the output arrays contain stale entries beyond position `nn`, so `nn != indices.cols` and callers cannot rely on the output size to know how many results are valid. 2. When `nn > maxResults`, the return value exceeds the capacity of the output arrays, which have only `maxResults` columns. The extra neighbors were never stored, so the return value is misleading. The following snippet reproduces both cases: ```cpp int testFLANN(){ std::vector<cv::Point2f> corners={{3679.83,1857.22},{3324.43,1850.67},{3278.83,1502.32},{3621.32,1508.69},{3662.26,1837.97},{3336.06,1839.28},{3291.74,1516.03},{3608.94,1518.72},{2980.66,1843.22},{2628.11,1837.14},{2607.73,1491.57},{2948.22,1496.76},{2289.31,1830.19},{1943.99,1824.17},{1945.51,1482.34},{2280.68,1487.39},{1607.47,1819.11},{1260.04,1813.26},{1283.94,1470.34},{1620.03,1475.85},{923.063,1808.08},{576.193,1802.4},{624.713,1459.78},{959.715,1464.93},{3270.25,1494.98},{2952.95,1492.19},{2922.75,1190.02},{3231.05,1194.81},{3284.82,1507.62},{2942.74,1502.59},{2912.32,1178.33},{3242.98,1183.19},{2612.82,1496.37},{2276.44,1491.63},{2267.61,1170.13},{2593.64,1174.43},{1949.73,1486.61},{1614.92,1480.64},{1626.77,1160.34},{1952,1165.51},{1289.38,1476.21},{953.709,1470.21},{986.779,1148.92},{1311.98,1154.89},{3567.28,1195.1},{3237.51,1189.03},{3197.63,884.15},{3518.61,888.76},{2918.31,1183.62},{2588.69,1179.37},{2570.64,875.672},{2889.87,878.902},{2271.97,1174.25},{1947.62,1169.61},{1948.56,868.197},{2263.8,872.533},{1630.99,1164.6},{1306.74,1159.52},{1327.81,858.358},{1642.69,862.765},{992.896,1155.52},{666.107,1149.96},{705.246,845.776},{1023.25,851.582},{3204.48,889.981},{2883.49,885.252},{2859.31,593.752},{3175.43,594.736},{2575.86,880.331},{2259.44,876.647},{2252.33,589.235},{2560.47,592.332},{1954.36,873.708},{1636.7,868.068},{1646.93,580.76},{1956.14,584.797},{1332.02,862.624},{1017.11,856.71},{1045.32,572.178},{1350.95,577.635},{3481.36,605.324},{3169.05,601.083},{3138.84,324.116},{3446.12,325.545},{2866.14,599.61},{2555.38,597.142},{2541.51,320.931},{2845.5,322.419},{2256.79,593.253},{1950.17,590.12},{1951.8,317.445},{2250.88,319.418},{1654.16,587.663},{1344.83,582.787},{1362.8,309.253},{1663.89,313.056},{1050.94,577.867},{741.476,571.648},{776.433,300.444},{1076.97,304.56},{3327.05,1847.65},{2977.74,1840.48},{2945.48,1499.68},{3281.82,1504.97},{2630.85,1834.22},{2287.2,1828.06},{2278.56,1489.51},{2610.64,1494.31},{1946.11,1822.05},{1604.75,1816.18},{1617.11,1478.59},{1947.62,1484.48},{1262.96,1810.53},{920.46,1805.05},{956.712,1467.57},{1286.66,1473.27},{3618.7,1511.71},{3281.82,1504.97},{3240.24,1186.11},{3564.22,1192.53},{2945.48,1499.68},{2610.64,1494.31},{2591.52,1176.55},{2915.32,1180.97},{2278.56,1489.51},{1947.62,1484.48},{1949.81,1167.56},{2269.79,1172.18},{1617.11,1478.59},{1286.66,1473.27},{1308.98,1157.53},{1628.88,1162.47},{956.712,1467.57},{627.315,1462.81},{669.943,1146.75},{989.494,1151.86},{3240.25,1186.11},{2915.32,1180.98},{2887.03,881.727},{3200.69,886.725},{2591.52,1176.55},{2269.79,1172.19},{2261.62,874.587},{2573.63,878.324},{1949.81,1167.55},{1628.88,1162.47},{1640.44,864.751},{1950.74,870.259},{1308.98,1157.53},{989.494,1151.86},{1019.41,854.787},{1329.92,860.49},{3515.88,891.68},{3200.69,886.725},{3171.89,598.263},{3478.26,602.785},{2887.04,881.725},{2573.63,878.324},{2558.28,594.392},{2863.1,597.005},{2261.62,874.587},{1950.74,870.259},{1952.4,588.114},{2254.56,591.241},{1640.44,864.751},{1329.92,860.49},{1348.65,579.559},{1650.55,584.209},{1019.41,854.787},{708.649,849.44},{745.388,568.534},{1047.42,574.313},{3171.89,598.263},{2863.1,597.005},{2842.6,325.169},{3141.93,326.654},{2558.28,594.392},{2254.56,591.241},{2248.65,321.425},{2544.55,323.537},{1952.4,588.113},{1650.55,584.209},{1660.07,316.284},{1954.02,319.457},{1348.65,579.559},{1047.43,574.312},{1073.06,307.674},{1366.42,312.707}}; cv::flann::KDTreeIndexParams indexParams(1); cv::Mat data = cv::Mat(corners).reshape(1, static_cast<int>(corners.size())); auto index = std::make_shared<cv::flann::Index>(data, indexParams); int maxResults = 4; int nTimesError1 = 0; // nn != indices.size() int nTimesError2 = 0; // nn > maxResults for (size_t i = 0; i < corners.size(); i++) { std::vector<int> indices(4); std::vector<float> dists(4); int nn = index->radiusSearch(data.row(static_cast<int>(i)), indices, dists, 100, maxResults); if (nn != (int)indices.size()) { nTimesError1++; } if (nn > maxResults) { nTimesError2++; } } std::cout << "nTimesError1: " << nTimesError1 << std::endl; // > 0 before fix std::cout << "nTimesError2: " << nTimesError2 << std::endl; // > 0 before fix return 1; } ``` ## Fix - Capture the search result in `rsearch_ret` instead of returning early from each `switch` case (this also required adding the missing `break` statements that would otherwise have caused fall-through between type-incompatible distance specialisations). - Cap `rsearch_ret` at `maxResults` so the return value never exceeds the capacity of the output arrays. - When `rsearch_ret < maxResults`, trim `_indices` and `_dists` to `query.rows × rsearch_ret` via `colRange(0, rsearch_ret).copyTo(...)` so the output dimensions always match the returned count.
905 lines
29 KiB
C++
905 lines
29 KiB
C++
#include "precomp.hpp"
|
|
|
|
#define MINIFLANN_SUPPORT_EXOTIC_DISTANCE_TYPES 0
|
|
|
|
static cvflann::IndexParams& get_params(const cv::flann::IndexParams& p)
|
|
{
|
|
return *(cvflann::IndexParams*)(p.params);
|
|
}
|
|
|
|
cv::flann::IndexParams::~IndexParams()
|
|
{
|
|
delete &get_params(*this);
|
|
}
|
|
|
|
namespace cv
|
|
{
|
|
|
|
namespace flann
|
|
{
|
|
|
|
using namespace cvflann;
|
|
|
|
IndexParams::IndexParams()
|
|
{
|
|
params = new ::cvflann::IndexParams();
|
|
}
|
|
|
|
template<typename T>
|
|
T getParam(const IndexParams& _p, const String& key, const T& defaultVal=T())
|
|
{
|
|
::cvflann::IndexParams& p = get_params(_p);
|
|
::cvflann::IndexParams::const_iterator it = p.find(key);
|
|
if( it == p.end() )
|
|
return defaultVal;
|
|
return it->second.cast<T>();
|
|
}
|
|
|
|
template<typename T>
|
|
void setParam(IndexParams& _p, const String& key, const T& value)
|
|
{
|
|
::cvflann::IndexParams& p = get_params(_p);
|
|
p[key] = value;
|
|
}
|
|
|
|
String IndexParams::getString(const String& key, const String& defaultVal) const
|
|
{
|
|
return getParam(*this, key, defaultVal);
|
|
}
|
|
|
|
int IndexParams::getInt(const String& key, int defaultVal) const
|
|
{
|
|
return getParam(*this, key, defaultVal);
|
|
}
|
|
|
|
double IndexParams::getDouble(const String& key, double defaultVal) const
|
|
{
|
|
return getParam(*this, key, defaultVal);
|
|
}
|
|
|
|
|
|
void IndexParams::setString(const String& key, const String& value)
|
|
{
|
|
setParam(*this, key, value);
|
|
}
|
|
|
|
void IndexParams::setInt(const String& key, int value)
|
|
{
|
|
setParam(*this, key, value);
|
|
}
|
|
|
|
void IndexParams::setDouble(const String& key, double value)
|
|
{
|
|
setParam(*this, key, value);
|
|
}
|
|
|
|
void IndexParams::setFloat(const String& key, float value)
|
|
{
|
|
setParam(*this, key, value);
|
|
}
|
|
|
|
void IndexParams::setBool(const String& key, bool value)
|
|
{
|
|
setParam(*this, key, value);
|
|
}
|
|
|
|
void IndexParams::setAlgorithm(int value)
|
|
{
|
|
setParam(*this, "algorithm", (cvflann::flann_algorithm_t)value);
|
|
}
|
|
|
|
void IndexParams::getAll(std::vector<String>& names,
|
|
std::vector<FlannIndexType>& types,
|
|
std::vector<String>& strValues,
|
|
std::vector<double>& numValues) const
|
|
{
|
|
names.clear();
|
|
types.clear();
|
|
strValues.clear();
|
|
numValues.clear();
|
|
|
|
::cvflann::IndexParams& p = get_params(*this);
|
|
::cvflann::IndexParams::const_iterator it = p.begin(), it_end = p.end();
|
|
|
|
for( ; it != it_end; ++it )
|
|
{
|
|
names.push_back(it->first);
|
|
try
|
|
{
|
|
String val = it->second.cast<String>();
|
|
types.push_back(FLANN_INDEX_TYPE_STRING);
|
|
strValues.push_back(val);
|
|
numValues.push_back(-1);
|
|
continue;
|
|
}
|
|
catch (...) {}
|
|
|
|
strValues.push_back(it->second.type().name());
|
|
|
|
try
|
|
{
|
|
double val = it->second.cast<double>();
|
|
types.push_back(FLANN_INDEX_TYPE_64F);
|
|
numValues.push_back(val);
|
|
continue;
|
|
}
|
|
catch (...) {}
|
|
try
|
|
{
|
|
float val = it->second.cast<float>();
|
|
types.push_back(FLANN_INDEX_TYPE_32F);
|
|
numValues.push_back(val);
|
|
continue;
|
|
}
|
|
catch (...) {}
|
|
try
|
|
{
|
|
int val = it->second.cast<int>();
|
|
types.push_back(FLANN_INDEX_TYPE_32S);
|
|
numValues.push_back(val);
|
|
continue;
|
|
}
|
|
catch (...) {}
|
|
try
|
|
{
|
|
short val = it->second.cast<short>();
|
|
types.push_back(FLANN_INDEX_TYPE_16S);
|
|
numValues.push_back(val);
|
|
continue;
|
|
}
|
|
catch (...) {}
|
|
try
|
|
{
|
|
ushort val = it->second.cast<ushort>();
|
|
types.push_back(FLANN_INDEX_TYPE_16U);
|
|
numValues.push_back(val);
|
|
continue;
|
|
}
|
|
catch (...) {}
|
|
try
|
|
{
|
|
char val = it->second.cast<char>();
|
|
types.push_back(FLANN_INDEX_TYPE_8S);
|
|
numValues.push_back(val);
|
|
continue;
|
|
}
|
|
catch (...) {}
|
|
try
|
|
{
|
|
uchar val = it->second.cast<uchar>();
|
|
types.push_back(FLANN_INDEX_TYPE_8U);
|
|
numValues.push_back(val);
|
|
continue;
|
|
}
|
|
catch (...) {}
|
|
try
|
|
{
|
|
bool val = it->second.cast<bool>();
|
|
types.push_back(FLANN_INDEX_TYPE_BOOL);
|
|
numValues.push_back(val);
|
|
continue;
|
|
}
|
|
catch (...) {}
|
|
try
|
|
{
|
|
cvflann::flann_algorithm_t val = it->second.cast<cvflann::flann_algorithm_t>();
|
|
types.push_back(FLANN_INDEX_TYPE_ALGORITHM);
|
|
numValues.push_back(val);
|
|
continue;
|
|
}
|
|
catch (...) {}
|
|
|
|
|
|
types.push_back((FlannIndexType)-1); // unknown type
|
|
numValues.push_back(-1);
|
|
}
|
|
}
|
|
|
|
|
|
KDTreeIndexParams::KDTreeIndexParams(int trees)
|
|
{
|
|
::cvflann::IndexParams& p = get_params(*this);
|
|
p["algorithm"] = FLANN_INDEX_KDTREE;
|
|
p["trees"] = trees;
|
|
}
|
|
|
|
LinearIndexParams::LinearIndexParams()
|
|
{
|
|
::cvflann::IndexParams& p = get_params(*this);
|
|
p["algorithm"] = FLANN_INDEX_LINEAR;
|
|
}
|
|
|
|
CompositeIndexParams::CompositeIndexParams(int trees, int branching, int iterations,
|
|
flann_centers_init_t centers_init, float cb_index )
|
|
{
|
|
::cvflann::IndexParams& p = get_params(*this);
|
|
p["algorithm"] = FLANN_INDEX_KMEANS;
|
|
// number of randomized trees to use (for kdtree)
|
|
p["trees"] = trees;
|
|
// branching factor
|
|
p["branching"] = branching;
|
|
// max iterations to perform in one kmeans clustering (kmeans tree)
|
|
p["iterations"] = iterations;
|
|
// algorithm used for picking the initial cluster centers for kmeans tree
|
|
p["centers_init"] = centers_init;
|
|
// cluster boundary index. Used when searching the kmeans tree
|
|
p["cb_index"] = cb_index;
|
|
}
|
|
|
|
AutotunedIndexParams::AutotunedIndexParams(float target_precision, float build_weight,
|
|
float memory_weight, float sample_fraction)
|
|
{
|
|
::cvflann::IndexParams& p = get_params(*this);
|
|
p["algorithm"] = FLANN_INDEX_AUTOTUNED;
|
|
// precision desired (used for autotuning, -1 otherwise)
|
|
p["target_precision"] = target_precision;
|
|
// build tree time weighting factor
|
|
p["build_weight"] = build_weight;
|
|
// index memory weighting factor
|
|
p["memory_weight"] = memory_weight;
|
|
// what fraction of the dataset to use for autotuning
|
|
p["sample_fraction"] = sample_fraction;
|
|
}
|
|
|
|
|
|
KMeansIndexParams::KMeansIndexParams(int branching, int iterations,
|
|
flann_centers_init_t centers_init, float cb_index )
|
|
{
|
|
::cvflann::IndexParams& p = get_params(*this);
|
|
p["algorithm"] = FLANN_INDEX_KMEANS;
|
|
// branching factor
|
|
p["branching"] = branching;
|
|
// max iterations to perform in one kmeans clustering (kmeans tree)
|
|
p["iterations"] = iterations;
|
|
// algorithm used for picking the initial cluster centers for kmeans tree
|
|
p["centers_init"] = centers_init;
|
|
// cluster boundary index. Used when searching the kmeans tree
|
|
p["cb_index"] = cb_index;
|
|
}
|
|
|
|
HierarchicalClusteringIndexParams::HierarchicalClusteringIndexParams(int branching ,
|
|
flann_centers_init_t centers_init,
|
|
int trees, int leaf_size)
|
|
{
|
|
::cvflann::IndexParams& p = get_params(*this);
|
|
p["algorithm"] = FLANN_INDEX_HIERARCHICAL;
|
|
// The branching factor used in the hierarchical clustering
|
|
p["branching"] = branching;
|
|
// Algorithm used for picking the initial cluster centers
|
|
p["centers_init"] = centers_init;
|
|
// number of parallel trees to build
|
|
p["trees"] = trees;
|
|
// maximum leaf size
|
|
p["leaf_size"] = leaf_size;
|
|
}
|
|
|
|
LshIndexParams::LshIndexParams(int table_number, int key_size, int multi_probe_level)
|
|
{
|
|
::cvflann::IndexParams& p = get_params(*this);
|
|
p["algorithm"] = FLANN_INDEX_LSH;
|
|
// The number of hash tables to use
|
|
p["table_number"] = table_number;
|
|
// The length of the key in the hash tables
|
|
p["key_size"] = key_size;
|
|
// Number of levels to use in multi-probe (0 for standard LSH)
|
|
p["multi_probe_level"] = multi_probe_level;
|
|
}
|
|
|
|
SavedIndexParams::SavedIndexParams(const String& _filename)
|
|
{
|
|
String filename = _filename;
|
|
::cvflann::IndexParams& p = get_params(*this);
|
|
|
|
p["algorithm"] = FLANN_INDEX_SAVED;
|
|
p["filename"] = filename;
|
|
}
|
|
|
|
SearchParams::SearchParams( int checks, float eps, bool sorted, bool explore_all_trees )
|
|
{
|
|
::cvflann::IndexParams& p = get_params(*this);
|
|
|
|
// how many leafs to visit when searching for neighbours (-1 for unlimited)
|
|
p["checks"] = checks;
|
|
// search for eps-approximate neighbours (default: 0)
|
|
p["eps"] = eps;
|
|
// only for radius search, require neighbours sorted by distance (default: true)
|
|
p["sorted"] = sorted;
|
|
// if false, search stops at the tree reaching the number of max checks (original behavior).
|
|
// When true, we do a descent in each tree and. Like before the alternative paths
|
|
// stored in the heap are not be processed further when max checks is reached.
|
|
p["explore_all_trees"] = explore_all_trees;
|
|
}
|
|
|
|
|
|
SearchParams::SearchParams( int checks, float eps, bool sorted )
|
|
{
|
|
::cvflann::IndexParams& p = get_params(*this);
|
|
|
|
// how many leafs to visit when searching for neighbours (-1 for unlimited)
|
|
p["checks"] = checks;
|
|
// search for eps-approximate neighbours (default: 0)
|
|
p["eps"] = eps;
|
|
// only for radius search, require neighbours sorted by distance (default: true)
|
|
p["sorted"] = sorted;
|
|
// if false, search stops at the tree reaching the number of max checks (original behavior).
|
|
// When true, we do a descent in each tree and. Like before the alternative paths
|
|
// stored in the heap are not be processed further when max checks is reached.
|
|
p["explore_all_trees"] = false;
|
|
}
|
|
|
|
|
|
template<typename Distance, typename IndexType> void
|
|
buildIndex_(void*& index, const Mat& data, const IndexParams& params, const Distance& dist = Distance())
|
|
{
|
|
typedef typename Distance::ElementType ElementType;
|
|
if(DataType<ElementType>::type != data.type())
|
|
CV_Error_(Error::StsUnsupportedFormat, ("type=%d\n", data.type()));
|
|
if(!data.isContinuous())
|
|
CV_Error(Error::StsBadArg, "Only continuous arrays are supported");
|
|
|
|
::cvflann::Matrix<ElementType> dataset((ElementType*)data.data, data.rows, data.cols);
|
|
IndexType* _index = new IndexType(dataset, get_params(params), dist);
|
|
|
|
try
|
|
{
|
|
_index->buildIndex();
|
|
}
|
|
catch (...)
|
|
{
|
|
delete _index;
|
|
_index = NULL;
|
|
|
|
throw;
|
|
}
|
|
|
|
index = _index;
|
|
}
|
|
|
|
template<typename Distance> void
|
|
buildIndex(void*& index, const Mat& data, const IndexParams& params, const Distance& dist = Distance())
|
|
{
|
|
buildIndex_<Distance, ::cvflann::Index<Distance> >(index, data, params, dist);
|
|
}
|
|
|
|
#if CV_NEON
|
|
typedef ::cvflann::Hamming<uchar> HammingDistance;
|
|
#else
|
|
typedef ::cvflann::HammingLUT HammingDistance;
|
|
#endif
|
|
typedef ::cvflann::DNAmming2<uchar> DNAmmingDistance;
|
|
|
|
Index::Index()
|
|
{
|
|
index = 0;
|
|
featureType = CV_32F;
|
|
algo = FLANN_INDEX_LINEAR;
|
|
distType = FLANN_DIST_L2;
|
|
}
|
|
|
|
Index::Index(InputArray _data, const IndexParams& params, flann_distance_t _distType)
|
|
{
|
|
index = 0;
|
|
featureType = CV_32F;
|
|
algo = FLANN_INDEX_LINEAR;
|
|
distType = FLANN_DIST_L2;
|
|
build(_data, params, _distType);
|
|
}
|
|
|
|
void Index::build(InputArray _data, const IndexParams& params, flann_distance_t _distType)
|
|
{
|
|
CV_INSTRUMENT_REGION();
|
|
|
|
release();
|
|
|
|
// Index may reuse 'data' during search, need to keep it alive
|
|
features_clone = _data.getMat().clone();
|
|
Mat data = features_clone;
|
|
|
|
algo = getParam<flann_algorithm_t>(params, "algorithm", FLANN_INDEX_LINEAR);
|
|
if( algo == FLANN_INDEX_SAVED )
|
|
{
|
|
load_(getParam<String>(params, "filename", String()));
|
|
return;
|
|
}
|
|
|
|
index = 0;
|
|
featureType = data.type();
|
|
distType = _distType;
|
|
|
|
if ( algo == FLANN_INDEX_LSH)
|
|
{
|
|
distType = FLANN_DIST_HAMMING;
|
|
}
|
|
|
|
switch( distType )
|
|
{
|
|
case FLANN_DIST_HAMMING:
|
|
buildIndex< HammingDistance >(index, data, params);
|
|
break;
|
|
case FLANN_DIST_L2:
|
|
buildIndex< ::cvflann::L2<float> >(index, data, params);
|
|
break;
|
|
case FLANN_DIST_L1:
|
|
buildIndex< ::cvflann::L1<float> >(index, data, params);
|
|
break;
|
|
#if MINIFLANN_SUPPORT_EXOTIC_DISTANCE_TYPES
|
|
case FLANN_DIST_DNAMMING:
|
|
buildIndex< DNAmmingDistance >(index, data, params);
|
|
break;
|
|
case FLANN_DIST_MAX:
|
|
buildIndex< ::cvflann::MaxDistance<float> >(index, data, params);
|
|
break;
|
|
case FLANN_DIST_HIST_INTERSECT:
|
|
buildIndex< ::cvflann::HistIntersectionDistance<float> >(index, data, params);
|
|
break;
|
|
case FLANN_DIST_HELLINGER:
|
|
buildIndex< ::cvflann::HellingerDistance<float> >(index, data, params);
|
|
break;
|
|
case FLANN_DIST_CHI_SQUARE:
|
|
buildIndex< ::cvflann::ChiSquareDistance<float> >(index, data, params);
|
|
break;
|
|
case FLANN_DIST_KL:
|
|
buildIndex< ::cvflann::KL_Divergence<float> >(index, data, params);
|
|
break;
|
|
#endif
|
|
default:
|
|
CV_Error(Error::StsBadArg, "Unknown/unsupported distance type");
|
|
}
|
|
}
|
|
|
|
template<typename IndexType> void deleteIndex_(void* index)
|
|
{
|
|
delete (IndexType*)index;
|
|
}
|
|
|
|
template<typename Distance> void deleteIndex(void* index)
|
|
{
|
|
deleteIndex_< ::cvflann::Index<Distance> >(index);
|
|
}
|
|
|
|
Index::~Index()
|
|
{
|
|
release();
|
|
}
|
|
|
|
void Index::release()
|
|
{
|
|
CV_INSTRUMENT_REGION();
|
|
|
|
features_clone.release();
|
|
|
|
if( !index )
|
|
return;
|
|
|
|
switch( distType )
|
|
{
|
|
case FLANN_DIST_HAMMING:
|
|
deleteIndex< HammingDistance >(index);
|
|
break;
|
|
case FLANN_DIST_L2:
|
|
deleteIndex< ::cvflann::L2<float> >(index);
|
|
break;
|
|
case FLANN_DIST_L1:
|
|
deleteIndex< ::cvflann::L1<float> >(index);
|
|
break;
|
|
#if MINIFLANN_SUPPORT_EXOTIC_DISTANCE_TYPES
|
|
case FLANN_DIST_DNAMMING:
|
|
deleteIndex< DNAmmingDistance >(index);
|
|
break;
|
|
case FLANN_DIST_MAX:
|
|
deleteIndex< ::cvflann::MaxDistance<float> >(index);
|
|
break;
|
|
case FLANN_DIST_HIST_INTERSECT:
|
|
deleteIndex< ::cvflann::HistIntersectionDistance<float> >(index);
|
|
break;
|
|
case FLANN_DIST_HELLINGER:
|
|
deleteIndex< ::cvflann::HellingerDistance<float> >(index);
|
|
break;
|
|
case FLANN_DIST_CHI_SQUARE:
|
|
deleteIndex< ::cvflann::ChiSquareDistance<float> >(index);
|
|
break;
|
|
case FLANN_DIST_KL:
|
|
deleteIndex< ::cvflann::KL_Divergence<float> >(index);
|
|
break;
|
|
#endif
|
|
default:
|
|
CV_Error(Error::StsBadArg, "Unknown/unsupported distance type");
|
|
}
|
|
index = 0;
|
|
}
|
|
|
|
template<typename Distance, typename IndexType>
|
|
void runKnnSearch_(void* index, const Mat& query, Mat& indices, Mat& dists,
|
|
int knn, const SearchParams& params)
|
|
{
|
|
typedef typename Distance::ElementType ElementType;
|
|
typedef typename Distance::ResultType DistanceType;
|
|
int type = DataType<ElementType>::type;
|
|
int dtype = DataType<DistanceType>::type;
|
|
IndexType* index_ = (IndexType*)index;
|
|
|
|
CV_Assert((size_t)knn <= index_->size());
|
|
CV_Assert(query.type() == type && indices.type() == CV_32S && dists.type() == dtype);
|
|
CV_Assert(query.isContinuous() && indices.isContinuous() && dists.isContinuous());
|
|
|
|
::cvflann::Matrix<ElementType> _query((ElementType*)query.data, query.rows, query.cols);
|
|
::cvflann::Matrix<int> _indices(indices.ptr<int>(), indices.rows, indices.cols);
|
|
::cvflann::Matrix<DistanceType> _dists(dists.ptr<DistanceType>(), dists.rows, dists.cols);
|
|
|
|
index_->knnSearch(_query, _indices, _dists, knn,
|
|
(const ::cvflann::SearchParams&)get_params(params));
|
|
}
|
|
|
|
template<typename Distance>
|
|
void runKnnSearch(void* index, const Mat& query, Mat& indices, Mat& dists,
|
|
int knn, const SearchParams& params)
|
|
{
|
|
runKnnSearch_<Distance, ::cvflann::Index<Distance> >(index, query, indices, dists, knn, params);
|
|
}
|
|
|
|
template<typename Distance, typename IndexType>
|
|
int runRadiusSearch_(void* index, const Mat& query, Mat& indices, Mat& dists,
|
|
double radius, const SearchParams& params)
|
|
{
|
|
typedef typename Distance::ElementType ElementType;
|
|
typedef typename Distance::ResultType DistanceType;
|
|
int type = DataType<ElementType>::type;
|
|
int dtype = DataType<DistanceType>::type;
|
|
CV_Assert(query.type() == type && indices.type() == CV_32S && dists.type() == dtype);
|
|
CV_Assert(query.isContinuous() && indices.isContinuous() && dists.isContinuous());
|
|
|
|
::cvflann::Matrix<ElementType> _query((ElementType*)query.data, query.rows, query.cols);
|
|
::cvflann::Matrix<int> _indices(indices.ptr<int>(), indices.rows, indices.cols);
|
|
::cvflann::Matrix<DistanceType> _dists(dists.ptr<DistanceType>(), dists.rows, dists.cols);
|
|
|
|
return ((IndexType*)index)->radiusSearch(_query, _indices, _dists,
|
|
saturate_cast<float>(radius),
|
|
(const ::cvflann::SearchParams&)get_params(params));
|
|
}
|
|
|
|
template<typename Distance>
|
|
int runRadiusSearch(void* index, const Mat& query, Mat& indices, Mat& dists,
|
|
double radius, const SearchParams& params)
|
|
{
|
|
return runRadiusSearch_<Distance, ::cvflann::Index<Distance> >(index, query, indices, dists, radius, params);
|
|
}
|
|
|
|
|
|
static void createIndicesDists(OutputArray _indices, OutputArray _dists,
|
|
Mat& indices, Mat& dists, int rows,
|
|
int minCols, int maxCols, int dtype)
|
|
{
|
|
if( _indices.needed() )
|
|
{
|
|
indices = _indices.getMat();
|
|
if( !indices.isContinuous() || indices.type() != CV_32S ||
|
|
indices.rows != rows || indices.cols < minCols || indices.cols > maxCols )
|
|
{
|
|
if( !indices.isContinuous() )
|
|
_indices.release();
|
|
_indices.create( rows, minCols, CV_32S );
|
|
indices = _indices.getMat();
|
|
}
|
|
}
|
|
else
|
|
indices.create( rows, minCols, CV_32S );
|
|
|
|
if( _dists.needed() )
|
|
{
|
|
dists = _dists.getMat();
|
|
if( !dists.isContinuous() || dists.type() != dtype ||
|
|
dists.rows != rows || dists.cols < minCols || dists.cols > maxCols )
|
|
{
|
|
if( !_dists.isContinuous() )
|
|
_dists.release();
|
|
_dists.create( rows, minCols, dtype );
|
|
dists = _dists.getMat();
|
|
}
|
|
}
|
|
else
|
|
dists.create( rows, minCols, dtype );
|
|
}
|
|
|
|
|
|
void Index::knnSearch(InputArray _query, OutputArray _indices,
|
|
OutputArray _dists, int knn, const SearchParams& params)
|
|
{
|
|
CV_INSTRUMENT_REGION();
|
|
|
|
Mat query = _query.getMat(), indices, dists;
|
|
int dtype = (distType == FLANN_DIST_HAMMING)
|
|
|| (distType == FLANN_DIST_DNAMMING) ? CV_32S : CV_32F;
|
|
|
|
createIndicesDists( _indices, _dists, indices, dists, query.rows, knn, knn, dtype );
|
|
|
|
switch( distType )
|
|
{
|
|
case FLANN_DIST_HAMMING:
|
|
runKnnSearch<HammingDistance>(index, query, indices, dists, knn, params);
|
|
break;
|
|
case FLANN_DIST_L2:
|
|
runKnnSearch< ::cvflann::L2<float> >(index, query, indices, dists, knn, params);
|
|
break;
|
|
case FLANN_DIST_L1:
|
|
runKnnSearch< ::cvflann::L1<float> >(index, query, indices, dists, knn, params);
|
|
break;
|
|
#if MINIFLANN_SUPPORT_EXOTIC_DISTANCE_TYPES
|
|
case FLANN_DIST_DNAMMING:
|
|
runKnnSearch<DNAmmingDistance>(index, query, indices, dists, knn, params);
|
|
break;
|
|
case FLANN_DIST_MAX:
|
|
runKnnSearch< ::cvflann::MaxDistance<float> >(index, query, indices, dists, knn, params);
|
|
break;
|
|
case FLANN_DIST_HIST_INTERSECT:
|
|
runKnnSearch< ::cvflann::HistIntersectionDistance<float> >(index, query, indices, dists, knn, params);
|
|
break;
|
|
case FLANN_DIST_HELLINGER:
|
|
runKnnSearch< ::cvflann::HellingerDistance<float> >(index, query, indices, dists, knn, params);
|
|
break;
|
|
case FLANN_DIST_CHI_SQUARE:
|
|
runKnnSearch< ::cvflann::ChiSquareDistance<float> >(index, query, indices, dists, knn, params);
|
|
break;
|
|
case FLANN_DIST_KL:
|
|
runKnnSearch< ::cvflann::KL_Divergence<float> >(index, query, indices, dists, knn, params);
|
|
break;
|
|
#endif
|
|
default:
|
|
CV_Error(Error::StsBadArg, "Unknown/unsupported distance type");
|
|
}
|
|
}
|
|
|
|
int Index::radiusSearch(InputArray _query, OutputArray _indices,
|
|
OutputArray _dists, double radius, int maxResults,
|
|
const SearchParams& params)
|
|
{
|
|
CV_INSTRUMENT_REGION();
|
|
|
|
Mat query = _query.getMat(), indices, dists;
|
|
int dtype = (distType == FLANN_DIST_HAMMING)
|
|
|| (distType == FLANN_DIST_DNAMMING) ? CV_32S : CV_32F;
|
|
CV_Assert( maxResults > 0 );
|
|
createIndicesDists( _indices, _dists, indices, dists, query.rows, maxResults, INT_MAX, dtype );
|
|
|
|
if( algo == FLANN_INDEX_LSH )
|
|
CV_Error( Error::StsNotImplemented, "LSH index does not support radiusSearch operation" );
|
|
|
|
int rsearch_ret;
|
|
switch( distType )
|
|
{
|
|
case FLANN_DIST_HAMMING:
|
|
rsearch_ret = runRadiusSearch< HammingDistance >(index, query, indices, dists, radius, params);
|
|
break;
|
|
case FLANN_DIST_L2:
|
|
rsearch_ret = runRadiusSearch< ::cvflann::L2<float> >(index, query, indices, dists, radius, params);
|
|
break;
|
|
case FLANN_DIST_L1:
|
|
rsearch_ret = runRadiusSearch< ::cvflann::L1<float> >(index, query, indices, dists, radius, params);
|
|
break;
|
|
#if MINIFLANN_SUPPORT_EXOTIC_DISTANCE_TYPES
|
|
case FLANN_DIST_DNAMMING:
|
|
rsearch_ret = runRadiusSearch< DNAmmingDistance >(index, query, indices, dists, radius, params);
|
|
break;
|
|
case FLANN_DIST_MAX:
|
|
rsearch_ret = runRadiusSearch< ::cvflann::MaxDistance<float> >(index, query, indices, dists, radius, params);
|
|
break;
|
|
case FLANN_DIST_HIST_INTERSECT:
|
|
rsearch_ret = runRadiusSearch< ::cvflann::HistIntersectionDistance<float> >(index, query, indices, dists, radius, params);
|
|
break;
|
|
case FLANN_DIST_HELLINGER:
|
|
rsearch_ret = runRadiusSearch< ::cvflann::HellingerDistance<float> >(index, query, indices, dists, radius, params);
|
|
break;
|
|
case FLANN_DIST_CHI_SQUARE:
|
|
rsearch_ret = runRadiusSearch< ::cvflann::ChiSquareDistance<float> >(index, query, indices, dists, radius, params);
|
|
break;
|
|
case FLANN_DIST_KL:
|
|
rsearch_ret = runRadiusSearch< ::cvflann::KL_Divergence<float> >(index, query, indices, dists, radius, params);
|
|
break;
|
|
#endif
|
|
default:
|
|
CV_Error(Error::StsBadArg, "Unknown/unsupported distance type");
|
|
return -1;
|
|
}
|
|
if (rsearch_ret > maxResults)
|
|
rsearch_ret = maxResults;
|
|
if (rsearch_ret < maxResults) {
|
|
if (_indices.needed())
|
|
indices.colRange(0, rsearch_ret).copyTo(_indices);
|
|
if (_dists.needed())
|
|
dists.colRange(0, rsearch_ret).copyTo(_dists);
|
|
}
|
|
return rsearch_ret;
|
|
}
|
|
|
|
flann_distance_t Index::getDistance() const
|
|
{
|
|
return distType;
|
|
}
|
|
|
|
flann_algorithm_t Index::getAlgorithm() const
|
|
{
|
|
return algo;
|
|
}
|
|
|
|
template<typename IndexType> void saveIndex_(const Index* index0, const void* index, FILE* fout)
|
|
{
|
|
IndexType* _index = (IndexType*)index;
|
|
::cvflann::save_header(fout, *_index);
|
|
// some compilers may store short enumerations as bytes,
|
|
// so make sure we always write integers (which are 4-byte values in any modern C compiler)
|
|
int idistType = (int)index0->getDistance();
|
|
::cvflann::save_value<int>(fout, idistType);
|
|
_index->saveIndex(fout);
|
|
}
|
|
|
|
template<typename Distance> void saveIndex(const Index* index0, const void* index, FILE* fout)
|
|
{
|
|
saveIndex_< ::cvflann::Index<Distance> >(index0, index, fout);
|
|
}
|
|
|
|
void Index::save(const String& filename) const
|
|
{
|
|
CV_INSTRUMENT_REGION();
|
|
|
|
FILE* fout = fopen(filename.c_str(), "wb");
|
|
if (fout == NULL)
|
|
CV_Error_( Error::StsError, ("Can not open file %s for writing FLANN index\n", filename.c_str()) );
|
|
|
|
switch( distType )
|
|
{
|
|
case FLANN_DIST_HAMMING:
|
|
saveIndex< HammingDistance >(this, index, fout);
|
|
break;
|
|
case FLANN_DIST_L2:
|
|
saveIndex< ::cvflann::L2<float> >(this, index, fout);
|
|
break;
|
|
case FLANN_DIST_L1:
|
|
saveIndex< ::cvflann::L1<float> >(this, index, fout);
|
|
break;
|
|
#if MINIFLANN_SUPPORT_EXOTIC_DISTANCE_TYPES
|
|
case FLANN_DIST_DNAMMING:
|
|
saveIndex< DNAmmingDistance >(this, index, fout);
|
|
break;
|
|
case FLANN_DIST_MAX:
|
|
saveIndex< ::cvflann::MaxDistance<float> >(this, index, fout);
|
|
break;
|
|
case FLANN_DIST_HIST_INTERSECT:
|
|
saveIndex< ::cvflann::HistIntersectionDistance<float> >(this, index, fout);
|
|
break;
|
|
case FLANN_DIST_HELLINGER:
|
|
saveIndex< ::cvflann::HellingerDistance<float> >(this, index, fout);
|
|
break;
|
|
case FLANN_DIST_CHI_SQUARE:
|
|
saveIndex< ::cvflann::ChiSquareDistance<float> >(this, index, fout);
|
|
break;
|
|
case FLANN_DIST_KL:
|
|
saveIndex< ::cvflann::KL_Divergence<float> >(this, index, fout);
|
|
break;
|
|
#endif
|
|
default:
|
|
fclose(fout);
|
|
fout = 0;
|
|
CV_Error(Error::StsBadArg, "Unknown/unsupported distance type");
|
|
}
|
|
if( fout )
|
|
fclose(fout);
|
|
}
|
|
|
|
|
|
template<typename Distance, typename IndexType>
|
|
bool loadIndex_(Index* index0, void*& index, const Mat& data, FILE* fin, const Distance& dist=Distance())
|
|
{
|
|
typedef typename Distance::ElementType ElementType;
|
|
CV_Assert(DataType<ElementType>::type == data.type() && data.isContinuous());
|
|
|
|
::cvflann::Matrix<ElementType> dataset((ElementType*)data.data, data.rows, data.cols);
|
|
|
|
::cvflann::IndexParams params;
|
|
params["algorithm"] = index0->getAlgorithm();
|
|
IndexType* _index = new IndexType(dataset, params, dist);
|
|
_index->loadIndex(fin);
|
|
index = _index;
|
|
return true;
|
|
}
|
|
|
|
template<typename Distance>
|
|
bool loadIndex(Index* index0, void*& index, const Mat& data, FILE* fin, const Distance& dist=Distance())
|
|
{
|
|
return loadIndex_<Distance, ::cvflann::Index<Distance> >(index0, index, data, fin, dist);
|
|
}
|
|
|
|
bool Index::load(InputArray _data, const String& filename)
|
|
{
|
|
release();
|
|
|
|
// Index may reuse 'data' during search, need to keep it alive
|
|
features_clone = _data.getMat().clone();
|
|
Mat data = features_clone;
|
|
|
|
return load_(filename);
|
|
}
|
|
|
|
bool Index::load_(const String& filename)
|
|
{
|
|
Mat data = features_clone;
|
|
bool ok = true;
|
|
|
|
FILE* fin = fopen(filename.c_str(), "rb");
|
|
if (fin == NULL) {
|
|
return false;
|
|
}
|
|
FILEScopeGuard fscgd(fin);
|
|
|
|
::cvflann::IndexHeader header = ::cvflann::load_header(fin);
|
|
|
|
algo = header.index_type;
|
|
featureType = header.data_type == FLANN_UINT8 ? CV_8U :
|
|
header.data_type == FLANN_INT8 ? CV_8S :
|
|
header.data_type == FLANN_UINT16 ? CV_16U :
|
|
header.data_type == FLANN_INT16 ? CV_16S :
|
|
header.data_type == FLANN_INT32 ? CV_32S :
|
|
header.data_type == FLANN_FLOAT32 ? CV_32F :
|
|
header.data_type == FLANN_FLOAT64 ? CV_64F : -1;
|
|
|
|
if( (int)header.rows != data.rows || (int)header.cols != data.cols ||
|
|
featureType != data.type() )
|
|
{
|
|
fprintf(stderr, "Reading FLANN index error: the saved data size (%d, %d) or type (%d) is different from the passed one (%d, %d), %d\n",
|
|
(int)header.rows, (int)header.cols, featureType, data.rows, data.cols, data.type());
|
|
return false;
|
|
}
|
|
|
|
int idistType = 0;
|
|
::cvflann::load_value(fin, idistType);
|
|
distType = (flann_distance_t)idistType;
|
|
|
|
if( !((distType == FLANN_DIST_HAMMING && featureType == CV_8U) ||
|
|
(distType == FLANN_DIST_DNAMMING && featureType == CV_8U) ||
|
|
(distType != FLANN_DIST_HAMMING && featureType == CV_32F)) )
|
|
{
|
|
fprintf(stderr, "Reading FLANN index error: unsupported feature type %d for the index type %d\n", featureType, algo);
|
|
return false;
|
|
}
|
|
|
|
switch( distType )
|
|
{
|
|
case FLANN_DIST_HAMMING:
|
|
loadIndex< HammingDistance >(this, index, data, fin);
|
|
break;
|
|
case FLANN_DIST_L2:
|
|
loadIndex< ::cvflann::L2<float> >(this, index, data, fin);
|
|
break;
|
|
case FLANN_DIST_L1:
|
|
loadIndex< ::cvflann::L1<float> >(this, index, data, fin);
|
|
break;
|
|
#if MINIFLANN_SUPPORT_EXOTIC_DISTANCE_TYPES
|
|
case FLANN_DIST_DNAMMING:
|
|
loadIndex< DNAmmingDistance >(this, index, data, fin);
|
|
break;
|
|
case FLANN_DIST_MAX:
|
|
loadIndex< ::cvflann::MaxDistance<float> >(this, index, data, fin);
|
|
break;
|
|
case FLANN_DIST_HIST_INTERSECT:
|
|
loadIndex< ::cvflann::HistIntersectionDistance<float> >(this, index, data, fin);
|
|
break;
|
|
case FLANN_DIST_HELLINGER:
|
|
loadIndex< ::cvflann::HellingerDistance<float> >(this, index, data, fin);
|
|
break;
|
|
case FLANN_DIST_CHI_SQUARE:
|
|
loadIndex< ::cvflann::ChiSquareDistance<float> >(this, index, data, fin);
|
|
break;
|
|
case FLANN_DIST_KL:
|
|
loadIndex< ::cvflann::KL_Divergence<float> >(this, index, data, fin);
|
|
break;
|
|
#endif
|
|
default:
|
|
fprintf(stderr, "Reading FLANN index error: unsupported distance type %d\n", distType);
|
|
ok = false;
|
|
}
|
|
|
|
return ok;
|
|
}
|
|
|
|
}
|
|
|
|
}
|