[英]How to load OpenCV Matrices saved with FileStorage in Java?
在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
的等效類。 是否存在? 如果沒有,我有什么選擇?
一種可能的解決方案是使用Java庫(例如yamlbeans或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 ]
刪除標頭“%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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.