How to write a Float Mat to a file in OpenCV

opencv save mat to binary file
opencv mat
opencv save mat to file java
opencv read mat from file
opencv save mat to image
opencv write video to file
opencv imwrite

I have a matrix

Mat B(480,640,CV_32FC1);

containing floating values..I want to write this matrix to a file which could be opened in notepad or Ms word or Excel to see the values inside and for storage....imwrite function can save 8-bit or 16-bit image only..

Drop in your suggestions if this could be done?? if yes, how ??

Using pure OpenCV API calls:

// Declare what you need
cv::FileStorage file("some_name.ext", cv::FileStorage::WRITE);
cv::Mat someMatrixOfAnyType;

// Write to file!
file << "matName" << someMatrixOfAnyType;

The file extension can be xml or yml. In both cases you get a small header that you can easily remove/parse, then you have access to the data in a floating point format. I used this approach successfully (with yml files) to get data into Matlab and Matplotlib

To get the data:

  1. open the file with any editor
  2. then suppress all the text and numbers except the content of the data tag (i.e., the pixel values).
  3. When done, save your file with a txt or csv extension and open it with matlab (drag-and-drop works).

Voilà. You may have to reshape the resulting matrix in matlab command line if it didn't guess correctly the image size.

How to write a Float Mat to a file in OpenCV - c++ - android, I have a matrix Mat B(480,640,CV_32FC1); containing floating values..I want to write this matrix to a file which could be opened in notepad or Ms word or Excel  Creating a Mat object explicitly . In the Load, Modify, and Save an Image tutorial you have already learned how to write a matrix to an image file by using the cv::imwrite() function. However, for debugging purposes it's much more convenient to see the actual values. You can do this using the << operator of Mat. Be aware that this only works

You can write cv::Mat to text file using simple C++ file handling.

Here is how you can do it:

#include <iostream>
#include <fstream>

using namespace std;

void writeMatToFile(cv::Mat& m, const char* filename)
    ofstream fout(filename);

        cout<<"File Not Opened"<<endl;  return;

    for(int i=0; i<m.rows; i++)
        for(int j=0; j<m.cols; j++)


int main()
    cv::Mat m = cv::Mat::eye(5,5,CV_32FC1);

    const char* filename = "output.txt";



What OpenCV functions can read/write floating point arrays , Neither imread nor imwrite seem to support 32-bit floating point If you want your values also in .txt file you can have a look at the cv::formater , there is an example Mat matrix = imread("filename.exr", IMREAD_ANYCOLOR  To get the data: open the file with any editor. then suppress all the text and numbers except the content of the data tag (i.e., the pixel values). When done, save your file with a txt or csv extension and open it with matlab (drag-and-drop works).

OpenCV can serialize (save) its objects in JSON, XML or YAML formats. You can use any editors, which understand these formats, in order to read these files, or use OpenCV to download data (de-serialize) from these files. Detailed explanation how this is done can be found here. In short, to store the data into xml-file, you have to call

cv::FileStorage fs("/path/to/file.xml", cv::FileStorage::WRITE); // create FileStorage object
cv::Mat cameraM; // matrix, which you need to save, do not forget to fill it with some data
fs << "cameraMatrix" << cameraM; // command to save the data
fs.release(); // releasing the file.

If you want to use JSON or YAML, just change the extension to .json or .yaml/.yml - openCV will automatically understand your intentions.

The important thing is the command

fs << "cameraMatrix" << cameraM;

the string "cameraMatrix" is the tag name, under which this matrix will be stored and using which this matrix can be found later in the file.

Note that xml format will not allow you to use tag names with spaces and some special characters, since only alphanumeric values, dots, dashes and underscores are allowed (see XML specification for details), while in YAML and JSON you can have something like

fs << "Camera Matrix" << cameraM;

Basic Structures, For example, the matrix B initialization above is compiled because OpenCV typedef Size_<int> Size2i; typedef Size2i Size; typedef Size_<float> Size2f; the file will be closed automatically by the Ptr<FILE> destructor. Note. The optional step argument is not required because our data pointer points to continuous memory. I used this method to pass Mat as Uint8Array between nodejs and C++. This avoided writing C++ bindings for cv::Mat with node-addon-api. References: Create memory continuous Mat; OpenCV Mat data layout; Mat from array

use write binary :

FILE* FP = fopen("D.bin","wb");
    int sizeImg[2] = { D.cols , D.rows };
    fwrite(sizeImg, 2, sizeof(int), FP);
    fwrite(, D.cols * D.rows, sizeof(float), FP);

then you can read in in matlab read size and then reshape (type=single)

width = data(1); height = data(2);
B = fread(fp,Inf,type);

imageOut = reshape(B,[width,height])';


Operations with images, If you read a jpg file, a 3 channel image is created by default. If you need a grayscale image, use: C++. Mat img = imread(filename, IMREAD_GRAYSCALE); You can use the same method for floating-point images (for example, you can get  I wrote some code to generate an .xml file that contains the RGB data from a Mat file in OpenCV. I would like to recreate this image in MATLAB from the data points in the xml file. I am however unsure of the formatting of the xml file, since when I open it it looks something like this:

I wrote this code:

#include "opencv2/opencv.hpp"

using namespace cv;
using namespace std;

Will save in the file:
void serializeMatbin(cv::Mat& mat, std::string filename){
    if (!mat.isContinuous()) {
        std::cout << "Not implemented yet" << std::endl;

    int elemSizeInBytes = (int)mat.elemSize();
    int elemType        = (int)mat.type();
    int dataSize        = (int)(mat.cols * mat.rows * mat.elemSize());

    FILE* FP = fopen(filename.c_str(), "wb");
    int sizeImg[4] = {mat.cols, mat.rows, elemSizeInBytes, elemType };
    fwrite(/* buffer */ sizeImg, /* how many elements */ 4, /* size of each element */ sizeof(int), /* file */ FP);
    fwrite(, mat.cols * mat.rows, elemSizeInBytes, FP);

cv::Mat deserializeMatbin(std::string filename){
    FILE* fp = fopen(filename.c_str(), "rb");
    int header[4];
    fread(header, sizeof(int), 4, fp);
    int cols            = header[0]; 
    int rows            = header[1];
    int elemSizeInBytes = header[2];
    int elemType        = header[3];

    //std::cout << "rows="<<rows<<" cols="<<cols<<" elemSizeInBytes=" << elemSizeInBytes << std::endl;

    cv::Mat outputMat = cv::Mat::ones(rows, cols, elemType);

    size_t result = fread(, elemSizeInBytes, (size_t)(cols * rows), fp);

    if (result != (size_t)(cols * rows)) {
        fputs ("Reading error", stderr);

    std::cout << ((float*)[200] << std::endl;
    return outputMat;

void testSerializeMatbin(){
    cv::Mat a = cv::Mat::ones(/*cols*/ 10, /* rows */ 5, CV_32F) * -2;
    std::string filename = "test.matbin";
    serializeMatbin(a, filename);
    cv::Mat b = deserializeMatbin(filename);
    std::cout << "Rows: " << b.rows << " Cols: " << b.cols << " type: " << b.type()<< std::endl;

Saving a matrix of float as bin and reading opencv c++, bin file using fwrite and read it using fread. Example for use of fwrite: cv::Mat file_matrix;; file_matrix = (cv::Mat_<float>(3, 3) <  Now you may ask if the matrix itself may belong to multiple Mat objects who takes responsibility for cleaning it up when it’s no longer needed. The short answer is: the last object that used it. This is handled by using a reference counting mechanism. Whenever somebody copies a header of a Mat object, a counter is increased for the matrix. Whenever a header is cleaned this counter is decreased.

How to save an image of type float32 in opencv?, to just dump the floating point values from a CvMat structure in a (textual) matrix form. For example, something like this (for a CvMat* called "workspace"): FILE  Imwrite PNG specific flags used to tune the compression algorithm. Returns true if the specified image can be decoded by OpenCV. Returns true if an image with the specified filename can be encoded by OpenCV. Reads an image from a buffer in memory. Encodes an image into a memory buffer. If set, return the loaded image as is (with alpha channel

OpenCV Tutorial: Creating Mat Objects - 2020, OpenCV Tutorial: Creating Mat Objects, cmake, single channel, two channels, multi channels. We'll learn how we can write a matrix to an image file, however, Mat img(2, 4, CV_32F ); // 2x4 single-channel array with 32 bit floating point  OpenCV from char to float. GitHub Gist: instantly share code, notes, and snippets.

OpenCV - Writing an Image, OpenCV - Writing an Image - The write() method of the Imgcodecs class is it in to a Matrix object String file ="C:/EXAMPLES/OpenCV/sample.jpg"; Mat matrix  The XmlDocument can be save to a text file (see MSDN documents). If you wants the data to be compressed, you can set the SerializationCompressionRatio to 9 before performing the XML serialization. The save function just call the OpenCV's save function, which I believe will attemps to save the matrix as an image (try to apply a .jpg extension to

  • you can [write the matrix in a xml or yaml file][1]. [1]:…
  • see best answer IMHO
  • Thank you... I can open the file using gedit ..Can you tell me how to load this xml file in Matlab or Excel???..
  • I think you need to give the matrix a name, like file << "matName" << someMatrixOfAnyType; otherwise I get this error: OpenCV Error: Unspecified error (No element name has been given) in operator<<, file /usr/local/include/opencv2/core/operations.hpp, line 2910
  • This should be followed by file.release(). As a general rule of thumb, It's good to close and release resources for any file IO.
  • @dev_nut: FileStorage destructor calls release(), no need to call it explicitly.
  • Found this:…
  • Want to accept this answer too... But only 1 can be given... anyway this simple approach also works great !1
  • @smttsp I don't think so. OpenCV implementation may be optimized.
  • Thanks, I suspected of if compiler optimizations could make both approaches have the same speed.
  • I have checked both answer and yours is 50-60% more slower than the other answer for an 1024x1024 double matrice to be written to xml file.
  • @smttsp... Yes of course, my solution is just a basic approach. While OpenCV's implementation is far more optimized.