1. 程式人生 > >C++——將TXT檔案儲存在cv::Mat資料結構

C++——將TXT檔案儲存在cv::Mat資料結構

#include <iostream>
#include <fstream>
#include <opencv2/core/core.hpp>
#include <string>
#include <opencv2/flann/flann.hpp>
#include <opencv2/features2d/features2d.hpp>

cv::Mat Img1, Img2;

//函式的形參和返回值都不能是IO流物件,而應該是IO流引用(且不能為const)。
//注意這裡使用了cv::Mat的引用為形參
//TxtToMat()函式將TXT檔案裡儲存的內容轉換成cv::Mat資料結構
void TxtToMat(std::ifstream & infile, cv::Mat & Img); int main() { std::ifstream file("gendercenter1_1.txt"); TxtToMat(file, Img1); Img1.convertTo(Img1, CV_32F); std::ifstream file1("agecenter1_1.txt"); TxtToMat(file1, Img2); Img2.convertTo(Img2, CV_32F); cv::Ptr<cv::DescriptorMatcher> matchers = cv::DescriptorMatcher::create("FlannBased"); //cv::BFMatcher matchers;         //cv::FlannBasedMatcher matchers;
        std::vector<cv::DMatch> matches;         //match(descriptor1, descriptor2, matches),這裡的descriptor要求是CV_32F,而cv::Mat預設的是CV_8U資料型別         matchers->match(Img1, Img2, matches); for (auto i = matches.begin(); i != matches.end(); i++) { std::cout << i->queryIdx << "------" << i->trainIdx << "-------" << i->distance << std::endl; } return 0; } void TxtToMat(std::ifstream & infile, cv::Mat & Img) { std::string line; int num = 0; while (std::getline(infile, line)) { std::istringstream stream(line); double x; while (stream >> x) { Img.push_back(x); } num++; } Img = Img.reshape(1, num); }

    如果不將特徵向量轉換成CV_32F,會出現以下報錯: