Store mat data in txt
I am trying to write a mat file to txt file. I am using the above function to do so:
void writeMatToFile(cv::Mat& m, const char* filename){
ofstream fout(filename);
for(int i=0; i<m.rows; i++){
for(int j=0; j<m.cols; j++){
fout<<m.at<float>(i,j)<<"\t";
}
fout<<endl;
}
fout.close();
}
And the main code:
string file = "output.txt";
writeMatToFile(image,file.c_str());
However I am receiving unhandled exceptions. Any idea how can i store mat data in txt?
m.at<float>(i,j); // is your Mat really float type ?
I am trying to figure out what is the type of my Mat file. I ve just used mage = imread(filename, 0); to read the file, where filename is a .jpg file.
m.at<uchar>(i,j); in this case. you can't choose the type arbitrarily, it has to fit the underlying data.
Ok know it works without exceptions, but in the txt file, weird characters it is stored.
h < E ^ W r ; C 9 1 6 7 4 % m b ¦ ¦ † ‹ J k ] < ( / O * C ¬ Ζ Ξ Τ Μ Ή ‚ \ V B L D - 0 / ' Ε ά Τ Ψ Υ Ι Ά ‚ \ B V < 4 ? ; | Ξ Σ ά Ω Ϊ Ϊ Ρ Ζ ± d B > F 6 A ¨ „ d Τ ή ά Ϊ Χ Υ Δ ± 2 H L 9 Q ³ r p † ² Χ Ψ ‹ X } p ? a 2 V • ~ Σ Ε Ύ 3 ( « n – ‰
lol.
the stream sees uchar and tries to print characters ... try:
fout<<(int)m.at<uchar>(i,j)
Yea, thanks int casting works!
You guys realize that the Mat class has builtin write and read functions associated with the "<<" and ">>" operators ? To write a matrix to a stream just do : fout << m.
@Guido, unfortunately, the reverse op does not work.
Idd, the read operator doesn't work unless you use opencv's xml formatting. However, if you just need to write, the stream operator is a good alternative.