How to write a Float Mat to a file in OpenCV

后端 未结 5 2056
一个人的身影
一个人的身影 2020-12-01 09:09

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 M

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 09:35

    I wrote this code:

    #include "opencv2/opencv.hpp"
    
    using namespace cv;
    using namespace std;
    
    /*
    Will save in the file:
    cols\n
    rows\n
    elemSize\n
    type\n
    DATA
    */
    void serializeMatbin(cv::Mat& mat, std::string filename){
        if (!mat.isContinuous()) {
            std::cout << "Not implemented yet" << std::endl;
            exit(1);
        }
    
        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.data, mat.cols * mat.rows, elemSizeInBytes, FP);
        fclose(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="<

提交回复
热议问题