保存

#include <opencv2/opencv.hpp>
#include <iostream>
#include <fstream>

void saveMatToBinary(const cv::Mat& mat, const std::string& filename) {
    std::ofstream ofs(filename, std::ios::binary);
    if (!ofs.is_open()) {
        std::cerr << "Failed to open file for writing: " << filename << std::endl;
        return;
    }

    // Write the matrix type and size
    int type = mat.type();
    int rows = mat.rows;
    int cols = mat.cols;
    ofs.write((char*)&type, sizeof(type));
    ofs.write((char*)&rows, sizeof(rows));
    ofs.write((char*)&cols, sizeof(cols));

    // Write the matrix data
    ofs.write((char*)mat.data, mat.total() * mat.elemSize());

    ofs.close();
}

int main() {
    cv::Mat image = cv::imread("path_to_your_image.jpg");
    if (image.empty()) {
        std::cerr << "Failed to load image" << std::endl;
        return -1;
    }

    saveMatToBinary(image, "output.bin");
    return 0;
}

读取

#include <opencv2/opencv.hpp>
#include <iostream>
#include <fstream>

cv::Mat loadMatFromBinary(const std::string& filename) {
    std::ifstream ifs(filename, std::ios::binary);
    if (!ifs.is_open()) {
        std::cerr << "Failed to open file for reading: " << filename << std::endl;
        return cv::Mat();
    }

    // Read the matrix type and size
    int type, rows, cols;
    ifs.read((char*)&type, sizeof(type));
    ifs.read((char*)&rows, sizeof(rows));
    ifs.read((char*)&cols, sizeof(cols));

    // Create the matrix
    cv::Mat mat(rows, cols, type);

    // Read the matrix data
    ifs.read((char*)mat.data, mat.total() * mat.elemSize());

    ifs.close();
    return mat;
}

int main() {
    cv::Mat loadedImage = loadMatFromBinary("output.bin");
    if (loadedImage.empty()) {
        std::cerr << "Failed to load image from binary file" << std::endl;
        return -1;
    }

    cv::imshow("Loaded Image", loadedImage);
    cv::waitKey(0);
    return 0;
}

 

 

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐