c++读入txt文件,存储为opencv Mat类型中

c++读入txt文件,存储为opencv Mat类型中,c++代码如下:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <iostream>
#include <fstream>
#include <iterator>
#include <cassert>
#include <vector>
#include <opencv2/opencv.hpp>
#include <core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>  
#include <opencv2/highgui/highgui.hpp>  

template <class Type>
Type stringToNum(const string& str)
{
    istringstream iss(str);
    Type num;
    iss >> num;
    return num;
}

void main()
{
    string file = "npoints.txt";
    ifstream infile;
    infile.open(file.data());   //将文件流对象与文件连接起来 
    assert(infile.is_open());   //若失败,则输出错误消息,并终止程序运行 
    vector<Mat> pointvec;
    while (!infile.eof())
    {
        string s;
        getline(infile, s);//s,每行的数据
        Mat tmpdata = Mat::zeros(1, 3, CV_32FC1);
        string result;
        stringstream input(s);//将字符串读到input中
        U8 n = 0;
        FLT* daVec = tmpdata.ptr<FLT>(0);
        while (input >> result)//依次输出到result中,并存入tmpdata中 
        {
            FLT td = stringToNum<FLT>(result);//将string转为float型
            daVec[n] = td;
            n++;
        }
        pointvec.push_back(tmpdata);
    }
    infile.close(); //关闭文件输入流 

    Mat pointdata = Mat(Size(3, pointvec.size() - 1), CV_32FC1);//w,h,读入.txt数据最后一行为空
    FLT* pointVec = pointdata.ptr<FLT>(0);
    for (S32 i = 0; i < pointdata.rows; i++)
    {
        pointVec = pointdata.ptr<FLT>(i);
        Mat tmppoint = pointvec[i];
        FLT* tmppointVec = tmppoint.ptr<FLT>(0);
        for (S32 j = 0; j < pointdata.cols; j++)
        {
            pointVec[j] = tmppointVec[j];
        }
    }
}

其中输入文件npoints.txt的文件格式为(一行3个float型数据,每个数据间有一个空格):

猜你喜欢

转载自blog.csdn.net/u013925378/article/details/83069725