FileStorage for OpenCV Python API

You can use PyYAML to parse the YAML file.

Since PyYAML doesn’t understand OpenCV data types, you need to specify a constructor for each OpenCV data type that you are trying to load. For example:

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)

Once you’ve done that, loading the yaml file is simple:

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

Result will be a dict, where the keys are the names of whatever you saved in the YAML.

Leave a Comment