如何加载 Java 中使用 FileStorage 保存的 OpenCV 矩阵?

How to load OpenCV Matrices saved with FileStorage in Java?

在 C++ 中,OpenCV 有一个很好的 FileStorage class 使保存和加载 Mat 变得轻而易举。

就像

一样简单
//To save
FileStorage fs(outputFile, FileStorage::WRITE);
fs << "variable_name" << variable;

//To load
FileStorage fs(outputFile, FileStorage::READ);
fs["variable_name"] >> variable;

文件格式为YAML。

我想使用我在 Java 中用 C++ 程序创建的 Mat,理想情况下,从保存的 YAML 文件加载它。但是,我在 Java 绑定中找不到与 FileStorage 等效的 class。一个存在吗?如果没有,我有什么选择?

一种可能的解决方案是使用 Java 库(例如 yamlbeans or snakeyaml)编写 YAML 解析器。

我选择使用yamlbeans,因为默认的FileStorage编码是YAML 1.0,而snakeyaml需要1.1。

我的 C++ 代码

FileStorage fs(path, FileStorage::WRITE);
fs << "M" << variable;

保存以下示例 YAML 文件

%YAML:1.0
codebook: !!opencv-matrix
   rows: 1
   cols: 3
   dt: f
   data: [ 1.03692314e+02, 1.82692322e+02, 8.46153831e+00 ]

删除 header、“%YAML:1.0”后,我可以使用

将其加载到 Java
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import org.opencv.core.CvType;
import org.opencv.core.Mat;

import net.sourceforge.yamlbeans.YamlException;
import net.sourceforge.yamlbeans.YamlReader;

public class YamlMatLoader {
    // This nested class specifies the expected variables in the file
    // Mat cannot be used directly because it lacks rows and cols variables
    protected static class MatStorage {
        public int rows;
        public int cols;
        public String dt;
        public List<String> data;

        // The empty constructor is required by YamlReader
        public MatStorage() {
        }

        public double[] getData() {
            double[] dataOut = new double[data.size()];
            for (int i = 0; i < dataOut.length; i++) {
                dataOut[i] = Double.parseDouble(data.get(i));
            }

            return dataOut;
        }
    }

    // Loading function
    private Mat getMatYml(String path) {
        try {  
            YamlReader reader = new YamlReader(new FileReader(path));

            // Set the tag "opencv-matrix" to process as MatStorage
            // I'm not sure why the tag is parsed as
            // "tag:yaml.org,2002:opencv-matrix"
            // rather than "opencv-matrix", but I determined this value by
            // debugging
            reader.getConfig().setClassTag("tag:yaml.org,2002:opencv-matrix", MatStorage.class);

            // Read the string
            Map map = (Map) reader.read();

            // In file, the variable name for the Mat is "M"
            MatStorage data = (MatStorage) map.get("M");

            // Create a new Mat to hold the extracted data
            Mat m = new Mat(data.rows, data.cols, CvType.CV_32FC1);
            m.put(0, 0, data.getData());
            return m;
        } catch (FileNotFoundException | YamlException e) {
            e.printStackTrace();
        }
        return null;
    }
}