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

时间:2015-12-15 19:24:41

标签: java yaml opencv3.0

在C ++中,OpenCV有一个很好的FileStorage类,可以轻松地保存和加载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等效的类。有人存在吗?如果没有,我有什么替代方案?

1 个答案:

答案 0 :(得分:2)

一种可能的解决方案是使用诸如yamlbeanssnakeyaml之类的Java库编写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 ]

删除标题“%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;
    }
}