FileStorage对象

import cv2
import numpy as np

type_dict = {0: 'NONE',
             1: 'INT',
             2: 'FLOAT',
             3: 'STR',
             4: 'REF',
             5: 'SEQ',
             6: 'MAP',
             7: 'TYPE_MASK',
             8: 'FLOW',
             16: 'USER',
             32: 'EMPTY',
             64: 'NAMED'}

# ------------------------Write------------------------
# 创建FileStorage对象,参数为WRITE,用于写入
fs = cv2.FileStorage("config.zip.xml", cv2.FILE_STORAGE_WRITE)

# 开始写入数据内容,支持浮点数、字符串和矩阵类型
fs.write('realNode', 900)
fs.write('strNode', 'test text')
fs.write('mapNode', np.array([[1, 2, 3],
                              [4, 5, 6]]))

# 写入完成后,释放对象
fs.release()
# ------------------------Write------------------------


# -------------------------Read-------------------------
# 创建FileStorage对象,参数为READ,用于读取
fs = cv2.FileStorage("config.zip.xml", cv2.FILE_STORAGE_READ)

# 调用getNode函数获取节点,按节点名称获取
realNode = fs.getNode("realNode")
strNode = fs.getNode('strNode')
mapNode = fs.getNode('mapNode')

# 对于不同类型的节点用不同的函数进行读取
# 对实数类型节点用real()函数读取
realNodeValue = realNode.real()
# 对字符串型节点用string()函数读取
strNodeValue = strNode.string()
# 对矩阵型节点用mat()函数读取
mapNodeValue = mapNode.mat()

print(realNodeValue)
print(strNodeValue)
print(mapNodeValue)
print('read success\n')
# -------------------------Read-------------------------


# -------------------------Other functions-------------------------
# 除此之外,FileNode类型还有其它函数可以使用
# name()函数可以获取当前节点名称
realNodeName = realNode.name()
# type()函数可以获取当前节点数据类型
realNodeType = realNode.type()
# empty()函数可以判断当前节点是否为空
isEmpty = realNode.empty()
# isMap() isReal() isString()等函数用于判断当前节点数据是否为指定类型
isMap = realNode.isMap()
# size()用于返回节点中元素个数
num = realNode.size()
print('NodeName:' + realNodeName)
print('Type:' + type_dict[realNodeType])
print('Value:' + realNodeValue.__str__())
print('isEmpty:' + isEmpty.__str__())
print('isMap:' + isMap.__str__())
print('ElementSize:' + num.__str__())

结果:

900.0
test text
[[1 2 3]
[4 5 6]]
read success

NodeName:realNode
Type:INT
Value:900.0
isEmpty:False
isMap:False
ElementSize:1

posted @ 2021-02-22 21:02  为红颜  阅读(281)  评论(0编辑  收藏  举报