1

在我的代码中,我将关键点插入到向量中,如代码所示,谁能告诉我如何将其保存到文本文件中。

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_ob​​ject 向量保存到文本文件中。

4

3 回答 3

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 中,您会遇到它非常慢。

于 2014-02-08T20:21:21.353 回答
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>    
于 2013-09-29T10:35:09.220 回答
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;
}

就这样

于 2013-09-29T09:47:24.283 回答