用C++和Python将RGB图像(.jpg)保存为二进制文件(.bin)。

2 人不认可

我想把一张RGB图像(.jpg)保存为二进制文件(.bin),并使用python和c++获得相同的保存数据(在.bin文件中)。

下面是我用Python和C++将图像保存到bin文件中的代码,但我在比较两个.bin文件时得到了不同的结果。

Python

image = cv2.imread('image.jpg')
filename1 = "/image.bin"   # save data as bin file
bin_file = image.astype('float32').tofile(filename1)
byte_list = []
with open(filename1, "rb") as f:
    while (byte := f.read(1)):
        byte_list.append(byte)
int IMAGE_SIZE = 224;
void matwrite(const string& filename, const Mat& mat)
    ofstream fs(filename, fstream::binary);
    // Header
    int type = mat.type();
    int channels = mat.channels();
    fs.write((char*)&mat.rows, sizeof(int));    // rows
    fs.write((char*)&mat.cols, sizeof(int));    // cols
    fs.write((char*)&type, sizeof(int));        // type
    fs.write((char*)&channels, sizeof(int));    // channels
    // Data
    if (mat.isContinuous())
        fs.write(mat.ptr<char>(0), (mat.dataend - mat.datastart));
        int rowsz = CV_ELEM_SIZE(type) * mat.cols;
        for (int r = 0; r < mat.rows; ++r)
            fs.write(mat.ptr<char>(r), rowsz);
int main()
    // Save data
        cv::Mat noisyImg = cv::imread("image.jpg");
        //randu(m, 0, 5);
        matwrite("bin_file.bin", data);
return 0 ;

我所寻找的是将c++和python中的RGB图像保存到一个二进制文件(.bin)中,用同样的方法获得保存在两个bin文件中的匹配数据(来自python和C++)。

5 个评论
这些文件有什么不同?如果能看到一个区别的例子,也许从每个文件的开头看几行hexdump,会有帮助。
它们是.bin文件,我用md5sum比较了它们
好吧,由于我们不能访问这些文件,你可能必须自己做一些侦查工作,并提供一些更多的细节。它们的大小相同吗?你是否对它们进行过比较,看看有什么不同?为什么你的c++例子将文件读入一个名为 noisyImg 的变量,然后将一个代码中没有显示的名为 data 的变量传递给 matwrite 的函数?
我猜测是Python脚本上的浮点数转换给你带来了问题。你的C++矩阵也是浮动的吗?
你为什么希望它们是一样的呢?这些代码并不等同。你只是从某个地方复制了它们,而没有理解它们的作用吗?C++代码写了某种头,而Python/numpy代码没有。你甚至试图用十六进制编辑器查看文件内容吗?
python
c++
image
opencv
binary
ベスマ・ゲスミ
ベスマ・ゲスミ
发布于 2022-05-08
1 个回答
ベスマ・ゲスミ
ベスマ・ゲスミ
发布于 2022-05-09
已采纳
0 人赞同

Solved!

Python

filename1 = "./image.bin"   # save data as bin file
bin_file = image.tofile(filename1)
    // Data
    int type = mat.type();
    if (mat.isContinuous())
        fs.write(mat.ptr<char>(0), (mat.dataend - mat.datastart));
        int rowsz = CV_ELEM_SIZE(type) * mat.cols;
        for (int r = 0; r < mat.rows; ++r)
            fs.write(mat.ptr<char>(r), rowsz);
int main()
    // Save data
        cv::Mat Img = cv::imread("image.jpg");
        //randu(m, 0, 5);