How to write vector to FileStorage

2020-04-21 05:32发布

问题:

I've been able to successfully write keypoints (vector), descriptors (Mat) and other things to yml files using FileStorage. However, after I compute the matches between a pair of images I am unable to write the matches to a file.

I am assuming it is because DMatch seems to be a struct that has distance, trainIdx etc. fields, but does anyone have a good way of writing this to a file?

Or should I just write a distance vector, a trainIdx vector etc?

Edited to show some code:

std::vector<cv::DMatch> matches;
for(int i=0;i<numims-1;i++){    
    for(int j=i+1;j<min(i+10,numims);j++){
        matches = MatchImagePair(i,j);
        //write the matches
        std::string matchfile = matchpath + "matchesij.yml";
        cv::FileStorage fs(matchfile, cv::FileStorage::WRITE);
        write(fs, "matches", matches);
        fs.release();
    }
}

matchesij should contain the numbers for i and j but I edited for brevity.

Also, MatchImagePair looks something like:

std::vector<cv::DMatch> Matches::MatchImagePair(int idx1, int idx2){
    //matcher type
    cv::BFMatcher matcher(cv::NORM_L2);

    //given descrs1 and descrs2, match the 2 descriptors
    matcher.knnMatch(descrs1, descrs2, matches12, 2);
    matcher.knnMatch(descrs2, descrs1, matches21, 2);

    //various tests, returns vector<DMatch> given keypts1, keypts2 (for RANSAC)
    matches = DoVariousTests(matches12, matches21, keypts1, keypts2);

    return matches;
}

回答1:

You could overload >> operator for file storage.

A working example code for cv::TermCriteria from here:

void operator>>(const cv::FileNode &node,
        cv::TermCriteria &termCrit) {
    node["type"] >> termCrit.type;
    node["maxCount"] >> termCrit.maxCount;
    node["epsilon"] >> termCrit.epsilon;
}

cv::FileStorage &operator<<(cv::FileStorage &fs,
        const cv::TermCriteria &termCrit) {
    fs << "{" << "type" << termCrit.type << "maxCount"
            << termCrit.maxCount << "epsilon" << termCrit.epsilon
            << "}";
    return fs;
}