mat保存至txt文件
写入PLeft48.txt
fstream PLeft48("PLeft48.txt", ios::out);
if (!PLeft48.fail())
{
cout << "start writing PLeft48.txt" << endl;
for (int i = 0; i < I.rows; i++)
{
for (int j = 0; j < I.cols; j++)
{
PLeft48 << int(I.at<uchar>(i, j)) << "\t";
}
PLeft48 << std::endl;
}
cout << "finish writing PLeft48.txt" << endl;
}
else
cout << "can not open" << endl;
PLeft48.close();
注意:
- 文件格式可用txt,也可用xml等
- 代码第10行,int是用来将uchar转换为整数,不加int的话输出就变成了uchar字符
- 代码第10行,uchar是灰度图使用的数据类型,其他的应根据mat中数据类型相应更改
读取txt文件至mat
ifstream fin("I_matlab.txt");
for (int i = 0; i < gray.rows; i++)
{
for (int j = 0; j < gray.cols; j++)
{
int a;
fin >> a;
gray.at<uchar>(i, j) = a;//
}
}
注意:
- 文件格式可用txt,也可用xml等
- 代码第6、7、8行不能省略为
fin >> gray.at<uchar>(i,j);
,这样写的话读进来的数与txt文件的不相同,原因未知 - 代码第8行,uchar是灰度图使用的数据类型,其他的应根据mat中数据类型相应更改