test_filestorage_io.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. #!/usr/bin/env python
  2. """Algorithm serialization test."""
  3. from __future__ import print_function
  4. import base64
  5. import json
  6. import tempfile
  7. import os
  8. import cv2 as cv
  9. import numpy as np
  10. from tests_common import NewOpenCVTests
  11. class MyData:
  12. def __init__(self):
  13. self.A = 97
  14. self.X = np.pi
  15. self.name = 'mydata1234'
  16. def write(self, fs, name):
  17. fs.startWriteStruct(name, cv.FileNode_MAP|cv.FileNode_FLOW)
  18. fs.write('A', self.A)
  19. fs.write('X', self.X)
  20. fs.write('name', self.name)
  21. fs.endWriteStruct()
  22. def read(self, node):
  23. if (not node.empty()):
  24. self.A = int(node.getNode('A').real())
  25. self.X = node.getNode('X').real()
  26. self.name = node.getNode('name').string()
  27. else:
  28. self.A = self.X = 0
  29. self.name = ''
  30. class filestorage_io_test(NewOpenCVTests):
  31. strings_data = ['image1.jpg', 'Awesomeness', '../data/baboon.jpg']
  32. R0 = np.eye(3,3)
  33. T0 = np.zeros((3,1))
  34. def write_data(self, fname):
  35. fs = cv.FileStorage(fname, cv.FileStorage_WRITE)
  36. R = self.R0
  37. T = self.T0
  38. m = MyData()
  39. fs.write('iterationNr', 100)
  40. fs.startWriteStruct('strings', cv.FileNode_SEQ)
  41. for elem in self.strings_data:
  42. fs.write('', elem)
  43. fs.endWriteStruct()
  44. fs.startWriteStruct('Mapping', cv.FileNode_MAP)
  45. fs.write('One', 1)
  46. fs.write('Two', 2)
  47. fs.endWriteStruct()
  48. fs.write('R_MAT', R)
  49. fs.write('T_MAT', T)
  50. m.write(fs, 'MyData')
  51. fs.release()
  52. def read_data_and_check(self, fname):
  53. fs = cv.FileStorage(fname, cv.FileStorage_READ)
  54. n = fs.getNode('iterationNr')
  55. itNr = int(n.real())
  56. self.assertEqual(itNr, 100)
  57. n = fs.getNode('strings')
  58. self.assertTrue(n.isSeq())
  59. self.assertEqual(n.size(), len(self.strings_data))
  60. for i in range(n.size()):
  61. self.assertEqual(n.at(i).string(), self.strings_data[i])
  62. n = fs.getNode('Mapping')
  63. self.assertEqual(int(n.getNode('Two').real()), 2)
  64. self.assertEqual(int(n.getNode('One').real()), 1)
  65. R = fs.getNode('R_MAT').mat()
  66. T = fs.getNode('T_MAT').mat()
  67. self.assertEqual(cv.norm(R, self.R0, cv.NORM_INF), 0)
  68. self.assertEqual(cv.norm(T, self.T0, cv.NORM_INF), 0)
  69. m0 = MyData()
  70. m = MyData()
  71. m.read(fs.getNode('MyData'))
  72. self.assertEqual(m.A, m0.A)
  73. self.assertEqual(m.X, m0.X)
  74. self.assertEqual(m.name, m0.name)
  75. n = fs.getNode('NonExisting')
  76. self.assertTrue(n.isNone())
  77. fs.release()
  78. def run_fs_test(self, ext):
  79. fd, fname = tempfile.mkstemp(prefix="opencv_python_sample_filestorage", suffix=ext)
  80. os.close(fd)
  81. self.write_data(fname)
  82. self.read_data_and_check(fname)
  83. os.remove(fname)
  84. def test_xml(self):
  85. self.run_fs_test(".xml")
  86. def test_yml(self):
  87. self.run_fs_test(".yml")
  88. def test_json(self):
  89. self.run_fs_test(".json")
  90. def test_base64(self):
  91. fd, fname = tempfile.mkstemp(prefix="opencv_python_sample_filestorage_base64", suffix=".json")
  92. os.close(fd)
  93. np.random.seed(42)
  94. self.write_base64_json(fname)
  95. os.remove(fname)
  96. @staticmethod
  97. def get_normal_2d_mat():
  98. rows = 10
  99. cols = 20
  100. cn = 3
  101. image = np.zeros((rows, cols, cn), np.uint8)
  102. image[:] = (1, 2, 127)
  103. for i in range(rows):
  104. for j in range(cols):
  105. image[i, j, 1] = (i + j) % 256
  106. return image
  107. @staticmethod
  108. def get_normal_nd_mat():
  109. shape = (2, 2, 1, 2)
  110. cn = 4
  111. image = np.zeros(shape + (cn,), np.float64)
  112. image[:] = (0.888, 0.111, 0.666, 0.444)
  113. return image
  114. @staticmethod
  115. def get_empty_2d_mat():
  116. shape = (0, 0)
  117. cn = 1
  118. image = np.zeros(shape + (cn,), np.uint8)
  119. return image
  120. @staticmethod
  121. def get_random_mat():
  122. rows = 8
  123. cols = 16
  124. cn = 1
  125. image = np.random.rand(rows, cols, cn)
  126. return image
  127. @staticmethod
  128. def decode(data):
  129. # strip $base64$
  130. encoded = data[8:]
  131. if len(encoded) == 0:
  132. return b''
  133. # strip info about datatype and padding
  134. return base64.b64decode(encoded)[24:]
  135. def write_base64_json(self, fname):
  136. fs = cv.FileStorage(fname, cv.FileStorage_WRITE_BASE64)
  137. mats = {'normal_2d_mat': self.get_normal_2d_mat(),
  138. 'normal_nd_mat': self.get_normal_nd_mat(),
  139. 'empty_2d_mat': self.get_empty_2d_mat(),
  140. 'random_mat': self.get_random_mat()}
  141. for name, mat in mats.items():
  142. fs.write(name, mat)
  143. fs.release()
  144. data = {}
  145. with open(fname) as file:
  146. data = json.load(file)
  147. for name, mat in mats.items():
  148. buffer = b''
  149. if mat.size != 0:
  150. if hasattr(mat, 'tobytes'):
  151. buffer = mat.tobytes()
  152. else:
  153. buffer = mat.tostring()
  154. self.assertEqual(buffer, self.decode(data[name]['data']))
  155. if __name__ == '__main__':
  156. NewOpenCVTests.bootstrap()