gpt4 book ai didi

c++ - 保存和加载 FlannBasedMatcher

转载 作者:可可西里 更新时间:2023-11-01 18:25:49 25 4
gpt4 key购买 nike

如果训练图像集很大,训练 OpenCV DescriptorMatcher 可能是一项耗时的操作。因此,将经过训练的 DescriptorMatcher 数据保存到磁盘以供以后重新加载似乎是一件非常明显的事情。

不幸的是,对于这种需求似乎没有任何明显的解决方案。

我找到答案最接近的是 this thread in the OpenCV discussion group . 2009年开始发帖,2011年大家还在找答案!

从该线程中截取的代码片段看起来应该从文件中重新加载索引:

FileStorage fs("data.xml",FileStorage::READ);
Mat data;
fs["mtx"] >> data;
flann::Index idx(data,"index.bin");

但我一直无法从中弄清楚如何实现完整的保存/加载功能。

以防万一,我使用的是 OpenCV 2.3.1。

最佳答案

我没有在论坛或邮件列表中看到对此的回答。我不得不深入研究 OpenCV 源代码 (2.4.5) 以了解如何完成此操作。它需要子类化才能获取 FlannBasedMatcher 的 protected 成员。

关键是将算法设置为 FLANN_INDEX_SAVED 并将文件名设置为 indexParams

另请注意:

  • 描述符必须在 readIndex() 之前传递给 add()

  • 对于要构建的索引,您必须先对其进行匹配,然后调用 write()。 train() 似乎除了构建匹配器(不提供描述符)之外什么都不做

  • 这适用于 SURF 描述符。对于完整的解决方案,可能还需要保存/恢复匹配器的 IndexParams 和/或 SearchParams。

接下来要做的是压缩索引(使用 gzip),它可以小 3-4 倍并且解压缩成本相对较低。这必须是 OpenCV 中的一个补丁。

class SaveableMatcher : public cv::FlannBasedMatcher
{
public:
SaveableMatcher()
{
}

virtual ~SaveableMatcher()
{
}

void printParams()
{
printf("SaveableMatcher::printParams: \n\t"
"addedDescCount=%d\n\t"
"flan distance_t=%d\n\t"
"flan algorithm_t=%d\n",
addedDescCount,
flannIndex->getDistance(),
flannIndex->getAlgorithm());

vector<std::string> names;
vector<int> types;
vector<std::string> strValues;
vector<double> numValues;

indexParams->getAll(names, types, strValues, numValues);

for (size_t i = 0; i < names.size(); i++)
printf("\tindex param: %s:\t type=%d val=%s %.2f\n",
names[i].c_str(), types[i],
strValues[i].c_str(), numValues[i]);

names.clear();
types.clear();
strValues.clear();
numValues.clear();
searchParams->getAll(names, types, strValues, numValues);

for (size_t i = 0; i < names.size(); i++)
printf("\tsearch param: %s:\t type=%d val=%s %.2f\n",
names[i].c_str(), types[i],
strValues[i].c_str(), numValues[i]);
}

void readIndex(const char* filename)
{
indexParams->setAlgorithm(cvflann::FLANN_INDEX_SAVED);
indexParams->setString("filename", filename);

// construct flannIndex now, so printParams works
train();

printParams();
}

void writeIndex(const char* filename)
{
printParams();
flannIndex->save(filename);
}
};

关于c++ - 保存和加载 FlannBasedMatcher,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9248012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com