2013-09-29 32 views
1

在我的代碼中,我將代碼中所示的關鍵點插入到一個向量中,任何人都可以告訴我如何將其保存到文本文件。如何將std :: vector <KeyPoint>保存爲C++中的文本文件

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 vecor保存到文本文件。

+0

如果可以的話,你可以給我提供代碼嗎? – posha

+1

沒有任何人可以在不知道KeyPoint對象是什麼樣的情況下回答這個問題。 –

回答

3

我認爲關鍵點是關鍵點OpenCV的類。在這種情況下,你可以只添加在您發佈的代碼的末尾:

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>  
+0

它像一個魅力。你可以告訴我如何讀回內容並將其插入到矢量。 – posha

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; 
} 

這一切

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,則會遇到它非常慢的問題。

相關問題