FileStorage for OpenCV Python API

后端 未结 6 1035
面向向阳花
面向向阳花 2020-12-08 15:54

I\'m currently using FileStorage class for storing matrices XML/YAML using OpenCV C++ API.

However, I have to writ

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 16:26

    In addition to @misha's response, OpenCV YAML's are somewhat incompatible with Python.

    Few reasons for incompatibility are:

    1. Yaml created by OpenCV doesn't have a space after ":". Whereas Python requires it. [Ex: It should be a: 2, and not a:2 for Python]
    2. First line of YAML file created by OpenCV is wrong. Either convert "%YAML:1.0" to "%YAML 1.0". Or skip the first line while reading.

    The following function takes care of providing that:

    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")
    

    NOTE: Above response is applicable only for yaml's. XML's have their own share of problems, something I haven't explored completely.

提交回复
热议问题