【问题标题】:How to save/read arrays of data in a file (C++)如何在文件中保存/读取数据数组(C++)
【发布时间】:2015-01-27 16:39:25
【问题描述】:

我正在使用从图像计算 SIFT 描述符的代码。我必须处理视频中的每一帧并存储每个计算描述符的序列。对于每个图像,描述符由两个数组组成:

Frames = (double*)realloc(Frames, 4 * sizeof(double)* nframes); 
Descr = (vl_uint8*)realloc(Descr, 128 * sizeof(vl_uint8)* nframes);

如何将这两个数组的序列保存在一个文件中,然后从文件中恢复这些数据(针对视频的每一帧)?

【问题讨论】:

  • 在 Google 中搜索“C/C++ 中的二进制 IO”。
  • 在网上搜索“c++ 序列化图像”。
  • @Mgetz OP 的要求是您必须将多个图像存储为文件,而不是单个,所以我不会称它为重复的。 Thomas 对序列化有一个很好的想法。
  • @marol 从根本上说,OP 要求的是将二进制数据保存到文件中。这是重复的。

标签: c++ arrays pointers opencv writefile


【解决方案1】:

您可以使用ofstream 写入文件。下面的代码可能无法直接使用,但应该指向正确的方向。

#include <fstream>
#include <iterator>
#include <algorithm>

void writeDescriptors() {

    std::ofstream output( "C:\\descriptors.txt", std::ios::binary );
    for ( int i = 1 ; i < Frames.size(); i++ )
    {
        out << ",  " << Frames[i];
    }
}

为了读回描述符,只需使用 ifstream 并反转算法

【讨论】:

  • 写应该可以,那读呢?只是“逆向”算法,例如 std::ifstream?
  • 我觉得不错,+1。用那句话编辑答案怎么样?
【解决方案2】:

尝试查找 fwrite 和 fread。

如果您有可变数量的帧 (nframes),使用文件中的前 2*4 字节存储文件包含的确切帧数可能会有所帮助。

编辑: http://www.cplusplus.com/reference/cstdio/fwrite/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多