不能使用 OpenCV 在 YAML 文件中放置多个 Mat 对象

Can't put more than one Mat object in YAML file using OpenCV

我需要使用相机采集并保存大量图像几个小时。我使用 BitFlow SDK 来处理相机采集,OpenCV 主要用于显示和图像处理。我需要找到一种方法以紧凑、易于访问的形式保存所有这些数据(创建多页 tiff 文件是第一个 objective,但几乎没有任何支持)。

无论如何,我现在正在尝试使用 OpenCV 的 FileStorage class 将多张图像保存在一个 YAML 文件中,但没有取得太大成功。我可以从我创建的 YAML 文件中成功写入然后读取 one 图像,但是一旦我尝试使用 << 运算符将多个 Mat 对象放入文件中,我就会得到以下错误:

First-chance exception at 0x74E2C42D in BFBi_test.exe: Microsoft C++ exception: cv::Exception at memory location 0x0045F6B4. First-chance exception at 0x74E2C42D in BFBi_test.exe: Microsoft C++ exception: cv::Exception at memory location 0x0045F6B4. Unhandled exception at at 0x74E2C42D in BFBi_test.exe: Microsoft C++ exception: cv::Exception at memory location 0x0045F6B4.

我的部分代码:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include "resource.h"
#include "SequenceInterface.h"

#include "opencv2/core/core.hpp"
#include "persistence.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

using namespace std;
using namespace cv;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{   
    // Control variables
    BFU32   numBuffers = 10;    // Allocate 10 buffers
    BFU32   setupOptions = 0;   // Use default setup options.

    FileStorage firstImg("FirstImage.yml", FileStorage::WRITE);
    FileStorage secondImg("SecondImage.yml", FileStorage::WRITE);

    cout << "Creating instance of sequence interface." << endl;
    SequenceInterface board(0, numBuffers, 0);
    PBFU32* pBufferArray= board.getBufferArrayPointers();

    Mat test(Size(1024, 1024),CV_8UC1, (void *)pBufferArray[0], (size_t)1024);
    Mat test2(Size(1024, 1024),CV_8UC1, (void *)pBufferArray[1], (size_t)1024);

// -- Acquisition done here --- 
...
...
// -- End of acquisition --  

    firstImg<<"firsttest"<< test;
    firstImg<< "secondtest" << test2; // Runtime error on this line;
    firstImg.release();

}

如果我将 test2 写入 secondImg,则不会出现问题。我还尝试将随机字符串对象添加到 firstImg 并且那里也没有问题。切换到 XML 也没有任何改变。 YAML 文件是否有最大大小,这意味着我的图像对于该用途来说太大了?

可以 将多个 Mat 写入同一个 FileStorage,就像您所做的那样。可能您的代码的其他部分有问题。

例如,这按预期工作:

#include <opencv2\opencv.hpp>
#include <vector>

using namespace std;
using namespace cv;

int main()
{
    vector<uchar> v1(1024 * 1024, 7);
    vector<uchar> v2(1024 * 1024, 9);

    Mat m1(1024, 1024, CV_8UC1, v1.data(), 1024);
    Mat m2(1024, 1024, CV_8UC1, v2.data(), 1024);

    FileStorage fs("test.yml", FileStorage::WRITE);
    fs << "m1" << m1;
    fs << "m2" << m2;

    return 0;
}

但是,您需要

save large amount of images using a camera for several hours. I need to find a way to save all this data in a compact, easily accessible form.

所以您可能不想将所有数据以文本格式保存在同一个文件中,但是:

  • 保存压缩 (jpg) 图片,imwrite.
  • 保存原始二进制数据。例如,参见 here