c_cpp 如何序列化opencv矩阵

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 如何序列化opencv矩阵相关的知识,希望对你有一定的参考价值。

void serializeCVMat(std::ofstream* os, const cv::Mat& mat) {
    int type = mat.type();
    int cols = mat.cols;
    int rows = mat.rows;
    int channels = mat.channels();
    os->write(reinterpret_cast<char *>(&type), sizeof(int));
    os->write(reinterpret_cast<char *>(&cols), sizeof(int));
    os->write(reinterpret_cast<char *>(&rows), sizeof(int));
    os->write(reinterpret_cast<char *>(&channels), sizeof(int));

//  The depth defines the size of the memory elements:
//  -   CV_8U - 8-bit unsigned integers ( 0..255 )
//  -   CV_8S - 8-bit signed integers ( -128..127 )
//  -   CV_16U - 16-bit unsigned integers ( 0..65535 )
//  -   CV_16S - 16-bit signed integers ( -32768..32767 )
//  -   CV_32S - 32-bit signed integers ( -2147483648..2147483647 )
//  -   CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN )
//  -   CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN )
    int depth = type & 7;
    int elementSize = 1;
    switch(depth) {
    case 0:
    case 1:
        elementSize = 1;
        break;
    case 2:
    case 3:
        elementSize = 2;
        break;
    case 4:
    case 5:
        elementSize = 4;
        break;
    case 6:
        elementSize = 8;
        break;
    }

    int dataSize = cols * rows * channels * elementSize;
    os->write(reinterpret_cast<char *>(mat.data), dataSize);
}

void serializeCVMat(std::ifstream* is, cv::Mat* mat) {
    int type, cols, rows, channels;
    is->read(reinterpret_cast<char *>(&type), sizeof(int));
    is->read(reinterpret_cast<char *>(&cols), sizeof(int));
    is->read(reinterpret_cast<char *>(&rows), sizeof(int));
    is->read(reinterpret_cast<char *>(&channels), sizeof(int));

//  The depth defines the size of the memory elements:
//  -   CV_8U - 8-bit unsigned integers ( 0..255 )
//  -   CV_8S - 8-bit signed integers ( -128..127 )
//  -   CV_16U - 16-bit unsigned integers ( 0..65535 )
//  -   CV_16S - 16-bit signed integers ( -32768..32767 )
//  -   CV_32S - 32-bit signed integers ( -2147483648..2147483647 )
//  -   CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN )
//  -   CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN )
    int depth = type & 7;
    int elementSize = 1;
    switch(depth) {
    case 0:
    case 1:
        elementSize = 1;
        break;
    case 2:
    case 3:
        elementSize = 2;
        break;
    case 4:
    case 5:
        elementSize = 4;
        break;
    case 6:
        elementSize = 8;
        break;
    }

    int dataSize = cols * rows * channels * elementSize;
    *mat = cv::Mat(rows, cols, type);
    is->read(reinterpret_cast<char *>(mat->data), dataSize);
}

以上是关于c_cpp 如何序列化opencv矩阵的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 将不同类型的矩阵转换为opencv矩阵

c_cpp 如何在图像上绘制方向矩阵

c_cpp 如何从3D矢量计算轴旋转或旋转矩阵

如何获取矩阵二范数 opencv

如何在openCV中获取像素矩阵和重塑矩阵

opencv - 如何返回与比较矩阵相同类型的比较矩阵