读取txt文件数据保存到vector,并转换为Mat

Mat Vec2Mat(vector<vector<float>> vec)    //二维Vector转Mat
{
	int row = vec.size();
	int col = vec[0].size();

    Mat img(row ,col,  CV_32F);
    float *ptmp = NULL;
    for (int i = 0; i <row; ++i)
    {
        ptmp = img.ptr<float>(i);
 
        for (int j = 0; j < col; ++j)
        {
            ptmp[j] = vec[i][j];
        }
    }
    
    return img;
 
}



ifstream f1;
f1.open("淡蓝色.txt");     //每行的各个数据必须以空格隔开
string str;
vector<vector<float> > num;
while(getline(f1, str))       //将淡蓝色.txt中的数据保存到num中
{
	istringstream input(str);      //istringstream 类的作用自行百度
	vector<float> tmp;
	float a;
	while(input >> a)
		tmp.push_back(a);
 
	num.push_back(tmp);
}
cv::Mat trainingDataMat; 
trainingDataMat = Vec2Mat(num);
//cout<<trainingDataMat<<endl;




注:一维vector转Mat可以直接用Mat的构造函数trainingDataMat = Mat(num, true);,但是二维vector转Mat这个方法并不成功。

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用OpenCV和SciPy中的函数来实现将Mat数据保存为Python的Scipy.io.savemat格式。下面是一个简单的示例代码: ```c++ #include <opencv2/opencv.hpp> #include <iostream> #include <fstream> #include <vector> #include <string> #include <algorithm> #include <numeric> #include <cmath> #include <cstdlib> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <boost/filesystem.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/algorithm/string.hpp> #include "json.hpp" using namespace std; using namespace cv; namespace pt = boost::property_tree; using json = nlohmann::json; int main(int argc, char** argv) { // 读取Mat数据 Mat img = imread("test.jpg"); // 将Mat数据转换为数组形式 vector<int> img_data; for(int i=0;i<img.rows;i++) { for(int j=0;j<img.cols;j++) { Vec3b pixel = img.at<Vec3b>(i, j); img_data.push_back(pixel[0]); img_data.push_back(pixel[1]); img_data.push_back(pixel[2]); } } // 定义保存数据的json对象 json data; data["img"] = img_data; // 将json对象保存文件 ofstream out_file("test.mat"); out_file << data; out_file.close(); return 0; } ``` 这个示例程序将OpenCV读取的图像数据转换为一个vector<int>形式的数组,然后将这个数组保存到一个json对象中,最后使用ofstream将这个json对象保存文件中。由于Scipy.io.savemat格式也是以JSON格式保存数据的,所以这个程序可以将Mat数据保存为Scipy.io.savemat格式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值