在我的代码中,我将关键点插入到代码中所示的向量中,任何人都可以告诉我如何将其保存到文本文件中。
Mat object = imread("face24.bmp", CV_LOAD_IMAGE_GRAYSCALE);
if( !object.data )
{
// std::cout<< "Error reading object " << std::endl;
return -2;
}
//Detect the keypoints using SURF Detector
int minHessian = 500;
SurfFeatureDetector detector( minHessian );
std::vector<KeyPoint> kp_object;
detector.detect( object, kp_object );
我想将kp_object vecor保存到文本文件中。
答案 0 :(得分:5)
您可以使用FileStorage编写和读取数据,而无需编写自己的序列化代码。写作时你可以使用:
std::vector<KeyPoint> keypointvector;
cv::Mat descriptormatrix
// do some detection and description
// ...
cv::FileStorage store("template.bin", cv::FileStorage::WRITE);
cv::write(store,"keypoints",keypointvector;
cv::write(store,"descriptors",descriptormatrix);
store.release();
阅读时你可以做类似的事情:
cv::FileStorage store("template.bin", cv::FileStorage::READ);
cv::FileNode n1 = store["keypoints"];
cv::read(n1,keypointvector);
cv::FileNode n2 = store["descriptors"];
cv::read(n2,descriptormatrix);
store.release();
这当然适用于二进制文件。这实际上取决于你想要的东西;如果你以后想要将txt文件解析成Matlab,你会发现它很慢。
答案 1 :(得分:3)
我假设KeyPoint是OpenCV KeyPoint类。在这种情况下,您只需在您发布的代码的末尾添加:
std::fstream outputFile;
outputFile.open( "outputFile.txt", std::ios::out )
for( size_t ii = 0; ii < kp_object.size( ); ++ii )
outputFile << kp_object[ii].pt.x << " " << kp_object[ii].pt.y <<std::endl;
outputFile.close( );
在您的包含中添加
#include <fstream>
答案 2 :(得分:0)
我建议你努力实施boost/serialization。
仅保存/恢复单个结构有点过分,但它是未来的证据,值得学习。
有一个虚构的结构声明:
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/vector.hpp>
#include <fstream>
struct KeyPoints {
int x, y;
std::string s;
/* this is the 'intrusive' technique, see the tutorial for non-intrusive one */
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & x;
ar & y;
ar & s;
}
};
int main(int argc, char *argv[])
{
std::vector<KeyPoints> v;
v.push_back( KeyPoints { 10, 20, "first" } );
v.push_back( KeyPoints { 13, 23, "second" } );
std::ofstream ofs("filename");
boost::archive::text_oarchive oa(ofs);
oa << v;
}
这就是全部