21

我目前正在使用FileStorage类来使用 OpenCV C++ API存储矩阵XML/YAML 。

但是,我必须编写一个 Python 脚本来读取这些XML/YAML文件。

我正在寻找可以读取OpenCV C++ API生成的XML/YAML文件的现有 OpenCV Python API

4

6 回答 6

22

您可以使用PyYAML来解析 YAML 文件。

由于 PyYAML 不理解 OpenCV 数据类型,因此您需要为尝试加载的每个 OpenCV 数据类型指定一个构造函数。例如:

import yaml
def opencv_matrix(loader, node):
    mapping = loader.construct_mapping(node, deep=True)
    mat = np.array(mapping["data"])
    mat.resize(mapping["rows"], mapping["cols"])
    return mat
yaml.add_constructor(u"tag:yaml.org,2002:opencv-matrix", opencv_matrix)

完成后,加载 yaml 文件很简单:

with open(file_name) as fin:
    result = yaml.load(fin.read())

结果将是一个字典,其中的键是您保存在 YAML 中的任何内容的名称。

于 2013-04-11T06:52:34.133 回答
8

除了@misha 的回复,OpenCV YAML 与 Python 有点不兼容。

不兼容的几个原因是:

  1. OpenCV 创建的 Yaml 在“:”之后没有空格。而 Python 需要它。[例如:应该是a: 2,而不是a:2Python ]
  2. OpenCV 创建的 YAML 文件的第一行是错误的。将“%YAML:1.0”转换为“%YAML 1.0”。或者在阅读时跳过第一行。

以下函数负责提供:

import yaml
import re
def readYAMLFile(fileName):
    ret = {}
    skip_lines=1    # Skip the first line which says "%YAML:1.0". Or replace it with "%YAML 1.0"
    with open(scoreFileName) as fin:
        for i in range(skip_lines):
            fin.readline()
        yamlFileOut = fin.read()
        myRe = re.compile(r":([^ ])")   # Add space after ":", if it doesn't exist. Python yaml requirement
        yamlFileOut = myRe.sub(r': \1', yamlFileOut)
        ret = yaml.load(yamlFileOut)
    return ret

outDict = readYAMLFile("file.yaml")

注意:以上响应仅适用于 yaml。XML 有自己的问题,我还没有完全探索过。

于 2016-02-23T09:07:09.053 回答
8

使用 OpenCV 3.2 中可用的 FileStorage 函数,我成功地使用了它:

import cv2
fs = cv2.FileStorage("calibration.xml", cv2.FILE_STORAGE_READ)
fn = fs.getNode("Camera_Matrix")
print (fn.mat())
于 2017-07-28T14:12:46.707 回答
4

我写了一个小片段来用 Python 读写 FileStorage 兼容的 YAML:

# A yaml constructor is for loading from a yaml node.
# This is taken from @misha 's answer: http://stackoverflow.com/a/15942429
def opencv_matrix_constructor(loader, node):
    mapping = loader.construct_mapping(node, deep=True)
    mat = np.array(mapping["data"])
    mat.resize(mapping["rows"], mapping["cols"])
    return mat
yaml.add_constructor(u"tag:yaml.org,2002:opencv-matrix", opencv_matrix_constructor)

# A yaml representer is for dumping structs into a yaml node.
# So for an opencv_matrix type (to be compatible with c++'s FileStorage) we save the rows, cols, type and flattened-data
def opencv_matrix_representer(dumper, mat):
    mapping = {'rows': mat.shape[0], 'cols': mat.shape[1], 'dt': 'd', 'data': mat.reshape(-1).tolist()}
    return dumper.represent_mapping(u"tag:yaml.org,2002:opencv-matrix", mapping)
yaml.add_representer(np.ndarray, opencv_matrix_representer)

#examples 

with open('output.yaml', 'w') as f:
    yaml.dump({"a matrix": np.zeros((10,10)), "another_one": np.zeros((2,4))}, f)

with open('output.yaml', 'r') as f:
    print yaml.load(f)
于 2016-03-02T21:53:16.397 回答
1

为了改进@Roy_Shilkrot 先前的答案,我添加了对 numpy 向量和矩阵的支持:

# A yaml constructor is for loading from a yaml node.
# This is taken from @misha 's answer: http://stackoverflow.com/a/15942429
def opencv_matrix_constructor(loader, node):
    mapping = loader.construct_mapping(node, deep=True)
    mat = np.array(mapping["data"])
    if mapping["cols"] > 1:
        mat.resize(mapping["rows"], mapping["cols"])
    else:
        mat.resize(mapping["rows"], )
    return mat
yaml.add_constructor(u"tag:yaml.org,2002:opencv-matrix", opencv_matrix_constructor)


# A yaml representer is for dumping structs into a yaml node.
# So for an opencv_matrix type (to be compatible with c++'s FileStorage) we save the rows, cols, type and flattened-data
def opencv_matrix_representer(dumper, mat):
    if mat.ndim > 1:
        mapping = {'rows': mat.shape[0], 'cols': mat.shape[1], 'dt': 'd', 'data': mat.reshape(-1).tolist()}
    else:
        mapping = {'rows': mat.shape[0], 'cols': 1, 'dt': 'd', 'data': mat.tolist()}
    return dumper.represent_mapping(u"tag:yaml.org,2002:opencv-matrix", mapping)
yaml.add_representer(np.ndarray, opencv_matrix_representer)

例子:

with open('output.yaml', 'w') as f:
    yaml.dump({"a matrix": np.zeros((10,10)), "another_one": np.zeros((5,))}, f)

with open('output.yaml', 'r') as f:
    print yaml.load(f)

输出:

a matrix: !!opencv-matrix
  cols: 10
  data: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
    0.0, 0.0, 0.0, 0.0, 0.0]
  dt: d
  rows: 10
another_one: !!opencv-matrix
  cols: 1
  data: [0.0, 0.0, 0.0, 0.0, 0.0]
  dt: d
  rows: 5

虽然我无法控制行、列、dt、数据的顺序。

于 2016-09-15T15:01:47.590 回答
0

pip install opencv-contrib-python 用于视频支持安装特定版本使用 pip install opencv-contrib-python

于 2020-03-27T02:56:51.757 回答