test_misc.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. import sys
  4. import ctypes
  5. from functools import partial
  6. from collections import namedtuple
  7. import sys
  8. if sys.version_info[0] < 3:
  9. from collections import Sequence
  10. else:
  11. from collections.abc import Sequence
  12. import numpy as np
  13. import cv2 as cv
  14. from tests_common import NewOpenCVTests, unittest
  15. def is_numeric(dtype):
  16. return np.issubdtype(dtype, np.integer) or np.issubdtype(dtype, np.floating)
  17. def get_limits(dtype):
  18. if not is_numeric(dtype):
  19. return None, None
  20. if np.issubdtype(dtype, np.integer):
  21. info = np.iinfo(dtype)
  22. else:
  23. info = np.finfo(dtype)
  24. return info.min, info.max
  25. def get_conversion_error_msg(value, expected, actual):
  26. return 'Conversion "{}" of type "{}" failed\nExpected: "{}" vs Actual "{}"'.format(
  27. value, type(value).__name__, expected, actual
  28. )
  29. def get_no_exception_msg(value):
  30. return 'Exception is not risen for {} of type {}'.format(value, type(value).__name__)
  31. class Bindings(NewOpenCVTests):
  32. def test_inheritance(self):
  33. bm = cv.StereoBM_create()
  34. bm.getPreFilterCap() # from StereoBM
  35. bm.getBlockSize() # from SteroMatcher
  36. boost = cv.ml.Boost_create()
  37. boost.getBoostType() # from ml::Boost
  38. boost.getMaxDepth() # from ml::DTrees
  39. boost.isClassifier() # from ml::StatModel
  40. def test_raiseGeneralException(self):
  41. with self.assertRaises((cv.error,),
  42. msg='C++ exception is not propagated to Python in the right way') as cm:
  43. cv.utils.testRaiseGeneralException()
  44. self.assertEqual(str(cm.exception), 'exception text')
  45. def test_redirectError(self):
  46. try:
  47. cv.imshow("", None) # This causes an assert
  48. self.assertEqual("Dead code", 0)
  49. except cv.error as _e:
  50. pass
  51. handler_called = [False]
  52. def test_error_handler(status, func_name, err_msg, file_name, line):
  53. handler_called[0] = True
  54. cv.redirectError(test_error_handler)
  55. try:
  56. cv.imshow("", None) # This causes an assert
  57. self.assertEqual("Dead code", 0)
  58. except cv.error as _e:
  59. self.assertEqual(handler_called[0], True)
  60. pass
  61. cv.redirectError(None)
  62. try:
  63. cv.imshow("", None) # This causes an assert
  64. self.assertEqual("Dead code", 0)
  65. except cv.error as _e:
  66. pass
  67. def test_overload_resolution_can_choose_correct_overload(self):
  68. val = 123
  69. point = (51, 165)
  70. self.assertEqual(cv.utils.testOverloadResolution(val, point),
  71. 'overload (int={}, point=(x={}, y={}))'.format(val, *point),
  72. "Can't select first overload if all arguments are provided as positional")
  73. self.assertEqual(cv.utils.testOverloadResolution(val, point=point),
  74. 'overload (int={}, point=(x={}, y={}))'.format(val, *point),
  75. "Can't select first overload if one of the arguments are provided as keyword")
  76. self.assertEqual(cv.utils.testOverloadResolution(val),
  77. 'overload (int={}, point=(x=42, y=24))'.format(val),
  78. "Can't select first overload if one of the arguments has default value")
  79. rect = (1, 5, 10, 23)
  80. self.assertEqual(cv.utils.testOverloadResolution(rect),
  81. 'overload (rect=(x={}, y={}, w={}, h={}))'.format(*rect),
  82. "Can't select second overload if all arguments are provided")
  83. def test_overload_resolution_fails(self):
  84. def test_overload_resolution(msg, *args, **kwargs):
  85. no_exception_msg = 'Overload resolution failed without any exception for: "{}"'.format(msg)
  86. wrong_exception_msg = 'Overload resolution failed with wrong exception type for: "{}"'.format(msg)
  87. with self.assertRaises((cv.error, Exception), msg=no_exception_msg) as cm:
  88. res = cv.utils.testOverloadResolution(*args, **kwargs)
  89. self.fail("Unexpected result for {}: '{}'".format(msg, res))
  90. self.assertEqual(type(cm.exception), cv.error, wrong_exception_msg)
  91. test_overload_resolution('wrong second arg type (keyword arg)', 5, point=(1, 2, 3))
  92. test_overload_resolution('wrong second arg type', 5, 2)
  93. test_overload_resolution('wrong first arg', 3.4, (12, 21))
  94. test_overload_resolution('wrong first arg, no second arg', 4.5)
  95. test_overload_resolution('wrong args number for first overload', 3, (12, 21), 123)
  96. test_overload_resolution('wrong args number for second overload', (3, 12, 12, 1), (12, 21))
  97. # One of the common problems
  98. test_overload_resolution('rect with float coordinates', (4.5, 4, 2, 1))
  99. test_overload_resolution('rect with wrong number of coordinates', (4, 4, 1))
  100. class Arguments(NewOpenCVTests):
  101. def _try_to_convert(self, conversion, value):
  102. try:
  103. result = conversion(value).lower()
  104. except Exception as e:
  105. self.fail(
  106. '{} "{}" is risen for conversion {} of type {}'.format(
  107. type(e).__name__, e, value, type(value).__name__
  108. )
  109. )
  110. else:
  111. return result
  112. def test_InputArray(self):
  113. res1 = cv.utils.dumpInputArray(None)
  114. # self.assertEqual(res1, "InputArray: noArray()") # not supported
  115. self.assertEqual(res1, "InputArray: empty()=true kind=0x00010000 flags=0x01010000 total(-1)=0 dims(-1)=0 size(-1)=0x0 type(-1)=CV_8UC1")
  116. res2_1 = cv.utils.dumpInputArray((1, 2))
  117. self.assertEqual(res2_1, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=2 dims(-1)=2 size(-1)=1x2 type(-1)=CV_64FC1")
  118. res2_2 = cv.utils.dumpInputArray(1.5) # Scalar(1.5, 1.5, 1.5, 1.5)
  119. self.assertEqual(res2_2, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=4 dims(-1)=2 size(-1)=1x4 type(-1)=CV_64FC1")
  120. a = np.array([[1, 2], [3, 4], [5, 6]])
  121. res3 = cv.utils.dumpInputArray(a) # 32SC1
  122. self.assertEqual(res3, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=6 dims(-1)=2 size(-1)=2x3 type(-1)=CV_32SC1")
  123. a = np.array([[[1, 2], [3, 4], [5, 6]]], dtype='f')
  124. res4 = cv.utils.dumpInputArray(a) # 32FC2
  125. self.assertEqual(res4, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=3 dims(-1)=2 size(-1)=3x1 type(-1)=CV_32FC2")
  126. a = np.array([[[1, 2]], [[3, 4]], [[5, 6]]], dtype=float)
  127. res5 = cv.utils.dumpInputArray(a) # 64FC2
  128. self.assertEqual(res5, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=3 dims(-1)=2 size(-1)=1x3 type(-1)=CV_64FC2")
  129. a = np.zeros((2,3,4), dtype='f')
  130. res6 = cv.utils.dumpInputArray(a)
  131. self.assertEqual(res6, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=6 dims(-1)=2 size(-1)=3x2 type(-1)=CV_32FC4")
  132. a = np.zeros((2,3,4,5), dtype='f')
  133. res7 = cv.utils.dumpInputArray(a)
  134. self.assertEqual(res7, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=120 dims(-1)=4 size(-1)=[2 3 4 5] type(-1)=CV_32FC1")
  135. def test_InputArrayOfArrays(self):
  136. res1 = cv.utils.dumpInputArrayOfArrays(None)
  137. # self.assertEqual(res1, "InputArray: noArray()") # not supported
  138. self.assertEqual(res1, "InputArrayOfArrays: empty()=true kind=0x00050000 flags=0x01050000 total(-1)=0 dims(-1)=1 size(-1)=0x0")
  139. res2_1 = cv.utils.dumpInputArrayOfArrays((1, 2)) # { Scalar:all(1), Scalar::all(2) }
  140. self.assertEqual(res2_1, "InputArrayOfArrays: empty()=false kind=0x00050000 flags=0x01050000 total(-1)=2 dims(-1)=1 size(-1)=2x1 type(0)=CV_64FC1 dims(0)=2 size(0)=1x4")
  141. res2_2 = cv.utils.dumpInputArrayOfArrays([1.5])
  142. self.assertEqual(res2_2, "InputArrayOfArrays: empty()=false kind=0x00050000 flags=0x01050000 total(-1)=1 dims(-1)=1 size(-1)=1x1 type(0)=CV_64FC1 dims(0)=2 size(0)=1x4")
  143. a = np.array([[1, 2], [3, 4], [5, 6]])
  144. b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  145. res3 = cv.utils.dumpInputArrayOfArrays([a, b])
  146. self.assertEqual(res3, "InputArrayOfArrays: empty()=false kind=0x00050000 flags=0x01050000 total(-1)=2 dims(-1)=1 size(-1)=2x1 type(0)=CV_32SC1 dims(0)=2 size(0)=2x3")
  147. c = np.array([[[1, 2], [3, 4], [5, 6]]], dtype='f')
  148. res4 = cv.utils.dumpInputArrayOfArrays([c, a, b])
  149. self.assertEqual(res4, "InputArrayOfArrays: empty()=false kind=0x00050000 flags=0x01050000 total(-1)=3 dims(-1)=1 size(-1)=3x1 type(0)=CV_32FC2 dims(0)=2 size(0)=3x1")
  150. a = np.zeros((2,3,4), dtype='f')
  151. res5 = cv.utils.dumpInputArrayOfArrays([a, b])
  152. self.assertEqual(res5, "InputArrayOfArrays: empty()=false kind=0x00050000 flags=0x01050000 total(-1)=2 dims(-1)=1 size(-1)=2x1 type(0)=CV_32FC4 dims(0)=2 size(0)=3x2")
  153. # TODO: fix conversion error
  154. #a = np.zeros((2,3,4,5), dtype='f')
  155. #res6 = cv.utils.dumpInputArray([a, b])
  156. #self.assertEqual(res6, "InputArrayOfArrays: empty()=false kind=0x00050000 flags=0x01050000 total(-1)=2 dims(-1)=1 size(-1)=2x1 type(0)=CV_32FC1 dims(0)=4 size(0)=[2 3 4 5]")
  157. def test_20968(self):
  158. pixel = np.uint8([[[40, 50, 200]]])
  159. _ = cv.cvtColor(pixel, cv.COLOR_RGB2BGR) # should not raise exception
  160. def test_parse_to_bool_convertible(self):
  161. try_to_convert = partial(self._try_to_convert, cv.utils.dumpBool)
  162. for convertible_true in (True, 1, 64, np.bool(1), np.int8(123), np.int16(11), np.int32(2),
  163. np.int64(1), np.bool_(3), np.bool8(12)):
  164. actual = try_to_convert(convertible_true)
  165. self.assertEqual('bool: true', actual,
  166. msg=get_conversion_error_msg(convertible_true, 'bool: true', actual))
  167. for convertible_false in (False, 0, np.uint8(0), np.bool_(0), np.int_(0)):
  168. actual = try_to_convert(convertible_false)
  169. self.assertEqual('bool: false', actual,
  170. msg=get_conversion_error_msg(convertible_false, 'bool: false', actual))
  171. def test_parse_to_bool_not_convertible(self):
  172. for not_convertible in (1.2, np.float(2.3), 's', 'str', (1, 2), [1, 2], complex(1, 1),
  173. complex(imag=2), complex(1.1), np.array([1, 0], dtype=np.bool)):
  174. with self.assertRaises((TypeError, OverflowError),
  175. msg=get_no_exception_msg(not_convertible)):
  176. _ = cv.utils.dumpBool(not_convertible)
  177. def test_parse_to_bool_convertible_extra(self):
  178. try_to_convert = partial(self._try_to_convert, cv.utils.dumpBool)
  179. _, max_size_t = get_limits(ctypes.c_size_t)
  180. for convertible_true in (-1, max_size_t):
  181. actual = try_to_convert(convertible_true)
  182. self.assertEqual('bool: true', actual,
  183. msg=get_conversion_error_msg(convertible_true, 'bool: true', actual))
  184. def test_parse_to_bool_not_convertible_extra(self):
  185. for not_convertible in (np.array([False]), np.array([True], dtype=np.bool)):
  186. with self.assertRaises((TypeError, OverflowError),
  187. msg=get_no_exception_msg(not_convertible)):
  188. _ = cv.utils.dumpBool(not_convertible)
  189. def test_parse_to_int_convertible(self):
  190. try_to_convert = partial(self._try_to_convert, cv.utils.dumpInt)
  191. min_int, max_int = get_limits(ctypes.c_int)
  192. for convertible in (-10, -1, 2, int(43.2), np.uint8(15), np.int8(33), np.int16(-13),
  193. np.int32(4), np.int64(345), (23), min_int, max_int, np.int_(33)):
  194. expected = 'int: {0:d}'.format(convertible)
  195. actual = try_to_convert(convertible)
  196. self.assertEqual(expected, actual,
  197. msg=get_conversion_error_msg(convertible, expected, actual))
  198. def test_parse_to_int_not_convertible(self):
  199. min_int, max_int = get_limits(ctypes.c_int)
  200. for not_convertible in (1.2, np.float(4), float(3), np.double(45), 's', 'str',
  201. np.array([1, 2]), (1,), [1, 2], min_int - 1, max_int + 1,
  202. complex(1, 1), complex(imag=2), complex(1.1)):
  203. with self.assertRaises((TypeError, OverflowError, ValueError),
  204. msg=get_no_exception_msg(not_convertible)):
  205. _ = cv.utils.dumpInt(not_convertible)
  206. def test_parse_to_int_not_convertible_extra(self):
  207. for not_convertible in (np.bool_(True), True, False, np.float32(2.3),
  208. np.array([3, ], dtype=int), np.array([-2, ], dtype=np.int32),
  209. np.array([1, ], dtype=np.int), np.array([11, ], dtype=np.uint8)):
  210. with self.assertRaises((TypeError, OverflowError),
  211. msg=get_no_exception_msg(not_convertible)):
  212. _ = cv.utils.dumpInt(not_convertible)
  213. def test_parse_to_size_t_convertible(self):
  214. try_to_convert = partial(self._try_to_convert, cv.utils.dumpSizeT)
  215. _, max_uint = get_limits(ctypes.c_uint)
  216. for convertible in (2, max_uint, (12), np.uint8(34), np.int8(12), np.int16(23),
  217. np.int32(123), np.int64(344), np.uint64(3), np.uint16(2), np.uint32(5),
  218. np.uint(44)):
  219. expected = 'size_t: {0:d}'.format(convertible).lower()
  220. actual = try_to_convert(convertible)
  221. self.assertEqual(expected, actual,
  222. msg=get_conversion_error_msg(convertible, expected, actual))
  223. def test_parse_to_size_t_not_convertible(self):
  224. min_long, _ = get_limits(ctypes.c_long)
  225. for not_convertible in (1.2, True, False, np.bool_(True), np.float(4), float(3),
  226. np.double(45), 's', 'str', np.array([1, 2]), (1,), [1, 2],
  227. np.float64(6), complex(1, 1), complex(imag=2), complex(1.1),
  228. -1, min_long, np.int8(-35)):
  229. with self.assertRaises((TypeError, OverflowError),
  230. msg=get_no_exception_msg(not_convertible)):
  231. _ = cv.utils.dumpSizeT(not_convertible)
  232. def test_parse_to_size_t_convertible_extra(self):
  233. try_to_convert = partial(self._try_to_convert, cv.utils.dumpSizeT)
  234. _, max_size_t = get_limits(ctypes.c_size_t)
  235. for convertible in (max_size_t,):
  236. expected = 'size_t: {0:d}'.format(convertible).lower()
  237. actual = try_to_convert(convertible)
  238. self.assertEqual(expected, actual,
  239. msg=get_conversion_error_msg(convertible, expected, actual))
  240. def test_parse_to_size_t_not_convertible_extra(self):
  241. for not_convertible in (np.bool_(True), True, False, np.array([123, ], dtype=np.uint8),):
  242. with self.assertRaises((TypeError, OverflowError),
  243. msg=get_no_exception_msg(not_convertible)):
  244. _ = cv.utils.dumpSizeT(not_convertible)
  245. def test_parse_to_float_convertible(self):
  246. try_to_convert = partial(self._try_to_convert, cv.utils.dumpFloat)
  247. min_float, max_float = get_limits(ctypes.c_float)
  248. for convertible in (2, -13, 1.24, float(32), np.float(32.45), np.double(12.23),
  249. np.float32(-12.3), np.float64(3.22), np.float_(-1.5), min_float,
  250. max_float, np.inf, -np.inf, float('Inf'), -float('Inf'),
  251. np.double(np.inf), np.double(-np.inf), np.double(float('Inf')),
  252. np.double(-float('Inf'))):
  253. expected = 'Float: {0:.2f}'.format(convertible).lower()
  254. actual = try_to_convert(convertible)
  255. self.assertEqual(expected, actual,
  256. msg=get_conversion_error_msg(convertible, expected, actual))
  257. # Workaround for Windows NaN tests due to Visual C runtime
  258. # special floating point values (indefinite NaN)
  259. for nan in (float('NaN'), np.nan, np.float32(np.nan), np.double(np.nan),
  260. np.double(float('NaN'))):
  261. actual = try_to_convert(nan)
  262. self.assertIn('nan', actual, msg="Can't convert nan of type {} to float. "
  263. "Actual: {}".format(type(nan).__name__, actual))
  264. min_double, max_double = get_limits(ctypes.c_double)
  265. for inf in (min_float * 10, max_float * 10, min_double, max_double):
  266. expected = 'float: {}inf'.format('-' if inf < 0 else '')
  267. actual = try_to_convert(inf)
  268. self.assertEqual(expected, actual,
  269. msg=get_conversion_error_msg(inf, expected, actual))
  270. def test_parse_to_float_not_convertible(self):
  271. for not_convertible in ('s', 'str', (12,), [1, 2], np.array([1, 2], dtype=np.float),
  272. np.array([1, 2], dtype=np.double), complex(1, 1), complex(imag=2),
  273. complex(1.1)):
  274. with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
  275. _ = cv.utils.dumpFloat(not_convertible)
  276. def test_parse_to_float_not_convertible_extra(self):
  277. for not_convertible in (np.bool_(False), True, False, np.array([123, ], dtype=int),
  278. np.array([1., ]), np.array([False]),
  279. np.array([True], dtype=np.bool)):
  280. with self.assertRaises((TypeError, OverflowError),
  281. msg=get_no_exception_msg(not_convertible)):
  282. _ = cv.utils.dumpFloat(not_convertible)
  283. def test_parse_to_double_convertible(self):
  284. try_to_convert = partial(self._try_to_convert, cv.utils.dumpDouble)
  285. min_float, max_float = get_limits(ctypes.c_float)
  286. min_double, max_double = get_limits(ctypes.c_double)
  287. for convertible in (2, -13, 1.24, np.float(32.45), float(2), np.double(12.23),
  288. np.float32(-12.3), np.float64(3.22), np.float_(-1.5), min_float,
  289. max_float, min_double, max_double, np.inf, -np.inf, float('Inf'),
  290. -float('Inf'), np.double(np.inf), np.double(-np.inf),
  291. np.double(float('Inf')), np.double(-float('Inf'))):
  292. expected = 'Double: {0:.2f}'.format(convertible).lower()
  293. actual = try_to_convert(convertible)
  294. self.assertEqual(expected, actual,
  295. msg=get_conversion_error_msg(convertible, expected, actual))
  296. # Workaround for Windows NaN tests due to Visual C runtime
  297. # special floating point values (indefinite NaN)
  298. for nan in (float('NaN'), np.nan, np.double(np.nan),
  299. np.double(float('NaN'))):
  300. actual = try_to_convert(nan)
  301. self.assertIn('nan', actual, msg="Can't convert nan of type {} to double. "
  302. "Actual: {}".format(type(nan).__name__, actual))
  303. def test_parse_to_double_not_convertible(self):
  304. for not_convertible in ('s', 'str', (12,), [1, 2], np.array([1, 2], dtype=np.float),
  305. np.array([1, 2], dtype=np.double), complex(1, 1), complex(imag=2),
  306. complex(1.1)):
  307. with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
  308. _ = cv.utils.dumpDouble(not_convertible)
  309. def test_parse_to_double_not_convertible_extra(self):
  310. for not_convertible in (np.bool_(False), True, False, np.array([123, ], dtype=int),
  311. np.array([1., ]), np.array([False]),
  312. np.array([12.4], dtype=np.double), np.array([True], dtype=np.bool)):
  313. with self.assertRaises((TypeError, OverflowError),
  314. msg=get_no_exception_msg(not_convertible)):
  315. _ = cv.utils.dumpDouble(not_convertible)
  316. def test_parse_to_cstring_convertible(self):
  317. try_to_convert = partial(self._try_to_convert, cv.utils.dumpCString)
  318. for convertible in ('', 's', 'str', str(123), ('char'), np.str('test1'), np.str_('test2')):
  319. expected = 'string: ' + convertible
  320. actual = try_to_convert(convertible)
  321. self.assertEqual(expected, actual,
  322. msg=get_conversion_error_msg(convertible, expected, actual))
  323. def test_parse_to_cstring_not_convertible(self):
  324. for not_convertible in ((12,), ('t', 'e', 's', 't'), np.array(['123', ]),
  325. np.array(['t', 'e', 's', 't']), 1, -1.4, True, False, None):
  326. with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
  327. _ = cv.utils.dumpCString(not_convertible)
  328. def test_parse_to_string_convertible(self):
  329. try_to_convert = partial(self._try_to_convert, cv.utils.dumpString)
  330. for convertible in (None, '', 's', 'str', str(123), np.str('test1'), np.str_('test2')):
  331. expected = 'string: ' + (convertible if convertible else '')
  332. actual = try_to_convert(convertible)
  333. self.assertEqual(expected, actual,
  334. msg=get_conversion_error_msg(convertible, expected, actual))
  335. def test_parse_to_string_not_convertible(self):
  336. for not_convertible in ((12,), ('t', 'e', 's', 't'), np.array(['123', ]),
  337. np.array(['t', 'e', 's', 't']), 1, True, False):
  338. with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
  339. _ = cv.utils.dumpString(not_convertible)
  340. def test_parse_to_rect_convertible(self):
  341. Rect = namedtuple('Rect', ('x', 'y', 'w', 'h'))
  342. try_to_convert = partial(self._try_to_convert, cv.utils.dumpRect)
  343. for convertible in ((1, 2, 4, 5), [5, 3, 10, 20], np.array([10, 20, 23, 10]),
  344. Rect(10, 30, 40, 55), tuple(np.array([40, 20, 24, 20])),
  345. list(np.array([20, 40, 30, 35]))):
  346. expected = 'rect: (x={}, y={}, w={}, h={})'.format(*convertible)
  347. actual = try_to_convert(convertible)
  348. self.assertEqual(expected, actual,
  349. msg=get_conversion_error_msg(convertible, expected, actual))
  350. def test_parse_to_rect_not_convertible(self):
  351. for not_convertible in (np.empty(shape=(4, 1)), (), [], np.array([]), (12, ),
  352. [3, 4, 5, 10, 123], {1: 2, 3:4, 5:10, 6:30},
  353. '1234', np.array([1, 2, 3, 4], dtype=np.float32),
  354. np.array([[1, 2], [3, 4], [5, 6], [6, 8]]), (1, 2, 5, 1.5)):
  355. with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
  356. _ = cv.utils.dumpRect(not_convertible)
  357. def test_parse_to_rotated_rect_convertible(self):
  358. RotatedRect = namedtuple('RotatedRect', ('center', 'size', 'angle'))
  359. try_to_convert = partial(self._try_to_convert, cv.utils.dumpRotatedRect)
  360. for convertible in (((2.5, 2.5), (10., 20.), 12.5), [[1.5, 10.5], (12.5, 51.5), 10],
  361. RotatedRect((10, 40), np.array([10.5, 20.5]), 5),
  362. np.array([[10, 6], [50, 50], 5.5], dtype=object)):
  363. center, size, angle = convertible
  364. expected = 'rotated_rect: (c_x={:.6f}, c_y={:.6f}, w={:.6f},' \
  365. ' h={:.6f}, a={:.6f})'.format(center[0], center[1],
  366. size[0], size[1], angle)
  367. actual = try_to_convert(convertible)
  368. self.assertEqual(expected, actual,
  369. msg=get_conversion_error_msg(convertible, expected, actual))
  370. def test_parse_to_rotated_rect_not_convertible(self):
  371. for not_convertible in ([], (), np.array([]), (123, (45, 34), 1), {1: 2, 3: 4}, 123,
  372. np.array([[123, 123, 14], [1, 3], 56], dtype=object), '123'):
  373. with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
  374. _ = cv.utils.dumpRotatedRect(not_convertible)
  375. def test_parse_to_term_criteria_convertible(self):
  376. TermCriteria = namedtuple('TermCriteria', ('type', 'max_count', 'epsilon'))
  377. try_to_convert = partial(self._try_to_convert, cv.utils.dumpTermCriteria)
  378. for convertible in ((1, 10, 1e-3), [2, 30, 1e-1], np.array([10, 20, 0.5], dtype=object),
  379. TermCriteria(0, 5, 0.1)):
  380. expected = 'term_criteria: (type={}, max_count={}, epsilon={:.6f}'.format(*convertible)
  381. actual = try_to_convert(convertible)
  382. self.assertEqual(expected, actual,
  383. msg=get_conversion_error_msg(convertible, expected, actual))
  384. def test_parse_to_term_criteria_not_convertible(self):
  385. for not_convertible in ([], (), np.array([]), [1, 4], (10,), (1.5, 34, 0.1),
  386. {1: 5, 3: 5, 10: 10}, '145'):
  387. with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
  388. _ = cv.utils.dumpTermCriteria(not_convertible)
  389. def test_parse_to_range_convertible_to_all(self):
  390. try_to_convert = partial(self._try_to_convert, cv.utils.dumpRange)
  391. for convertible in ((), [], np.array([])):
  392. expected = 'range: all'
  393. actual = try_to_convert(convertible)
  394. self.assertEqual(expected, actual,
  395. msg=get_conversion_error_msg(convertible, expected, actual))
  396. def test_parse_to_range_convertible(self):
  397. Range = namedtuple('Range', ('start', 'end'))
  398. try_to_convert = partial(self._try_to_convert, cv.utils.dumpRange)
  399. for convertible in ((10, 20), [-1, 3], np.array([10, 24]), Range(-4, 6)):
  400. expected = 'range: (s={}, e={})'.format(*convertible)
  401. actual = try_to_convert(convertible)
  402. self.assertEqual(expected, actual,
  403. msg=get_conversion_error_msg(convertible, expected, actual))
  404. def test_parse_to_range_not_convertible(self):
  405. for not_convertible in ((1, ), [40, ], np.array([1, 4, 6]), {'a': 1, 'b': 40},
  406. (1.5, 13.5), [3, 6.7], np.array([6.3, 2.1]), '14, 4'):
  407. with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
  408. _ = cv.utils.dumpRange(not_convertible)
  409. def test_reserved_keywords_are_transformed(self):
  410. default_lambda_value = 2
  411. default_from_value = 3
  412. format_str = "arg={}, lambda={}, from={}"
  413. self.assertEqual(
  414. cv.utils.testReservedKeywordConversion(20), format_str.format(20, default_lambda_value, default_from_value)
  415. )
  416. self.assertEqual(
  417. cv.utils.testReservedKeywordConversion(10, lambda_=10), format_str.format(10, 10, default_from_value)
  418. )
  419. self.assertEqual(
  420. cv.utils.testReservedKeywordConversion(10, from_=10), format_str.format(10, default_lambda_value, 10)
  421. )
  422. self.assertEqual(
  423. cv.utils.testReservedKeywordConversion(20, lambda_=-4, from_=12), format_str.format(20, -4, 12)
  424. )
  425. def test_parse_vector_int_convertible(self):
  426. np.random.seed(123098765)
  427. try_to_convert = partial(self._try_to_convert, cv.utils.dumpVectorOfInt)
  428. arr = np.random.randint(-20, 20, 40).astype(np.int32).reshape(10, 2, 2)
  429. int_min, int_max = get_limits(ctypes.c_int)
  430. for convertible in ((int_min, 1, 2, 3, int_max), [40, 50], tuple(),
  431. np.array([int_min, -10, 24, int_max], dtype=np.int32),
  432. np.array([10, 230, 12], dtype=np.uint8), arr[:, 0, 1],):
  433. expected = "[" + ", ".join(map(str, convertible)) + "]"
  434. actual = try_to_convert(convertible)
  435. self.assertEqual(expected, actual,
  436. msg=get_conversion_error_msg(convertible, expected, actual))
  437. def test_parse_vector_int_not_convertible(self):
  438. np.random.seed(123098765)
  439. arr = np.random.randint(-20, 20, 40).astype(np.float).reshape(10, 2, 2)
  440. int_min, int_max = get_limits(ctypes.c_int)
  441. test_dict = {1: 2, 3: 10, 10: 20}
  442. for not_convertible in ((int_min, 1, 2.5, 3, int_max), [True, 50], 'test', test_dict,
  443. reversed([1, 2, 3]),
  444. np.array([int_min, -10, 24, [1, 2]], dtype=np.object),
  445. np.array([[1, 2], [3, 4]]), arr[:, 0, 1],):
  446. with self.assertRaises(TypeError, msg=get_no_exception_msg(not_convertible)):
  447. _ = cv.utils.dumpVectorOfInt(not_convertible)
  448. def test_parse_vector_double_convertible(self):
  449. np.random.seed(1230965)
  450. try_to_convert = partial(self._try_to_convert, cv.utils.dumpVectorOfDouble)
  451. arr = np.random.randint(-20, 20, 40).astype(np.int32).reshape(10, 2, 2)
  452. for convertible in ((1, 2.12, 3.5), [40, 50], tuple(),
  453. np.array([-10, 24], dtype=np.int32),
  454. np.array([-12.5, 1.4], dtype=np.double),
  455. np.array([10, 230, 12], dtype=np.float), arr[:, 0, 1], ):
  456. expected = "[" + ", ".join(map(lambda v: "{:.2f}".format(v), convertible)) + "]"
  457. actual = try_to_convert(convertible)
  458. self.assertEqual(expected, actual,
  459. msg=get_conversion_error_msg(convertible, expected, actual))
  460. def test_parse_vector_double_not_convertible(self):
  461. test_dict = {1: 2, 3: 10, 10: 20}
  462. for not_convertible in (('t', 'e', 's', 't'), [True, 50.55], 'test', test_dict,
  463. np.array([-10.1, 24.5, [1, 2]], dtype=np.object),
  464. np.array([[1, 2], [3, 4]]),):
  465. with self.assertRaises(TypeError, msg=get_no_exception_msg(not_convertible)):
  466. _ = cv.utils.dumpVectorOfDouble(not_convertible)
  467. def test_parse_vector_rect_convertible(self):
  468. np.random.seed(1238765)
  469. try_to_convert = partial(self._try_to_convert, cv.utils.dumpVectorOfRect)
  470. arr_of_rect_int32 = np.random.randint(5, 20, 4 * 3).astype(np.int32).reshape(3, 4)
  471. arr_of_rect_cast = np.random.randint(10, 40, 4 * 5).astype(np.uint8).reshape(5, 4)
  472. for convertible in (((1, 2, 3, 4), (10, -20, 30, 10)), arr_of_rect_int32, arr_of_rect_cast,
  473. arr_of_rect_int32.astype(np.int8), [[5, 3, 1, 4]],
  474. ((np.int8(4), np.uint8(10), np.int(32), np.int16(55)),)):
  475. expected = "[" + ", ".join(map(lambda v: "[x={}, y={}, w={}, h={}]".format(*v), convertible)) + "]"
  476. actual = try_to_convert(convertible)
  477. self.assertEqual(expected, actual,
  478. msg=get_conversion_error_msg(convertible, expected, actual))
  479. def test_parse_vector_rect_not_convertible(self):
  480. np.random.seed(1238765)
  481. arr = np.random.randint(5, 20, 4 * 3).astype(np.float).reshape(3, 4)
  482. for not_convertible in (((1, 2, 3, 4), (10.5, -20, 30.1, 10)), arr,
  483. [[5, 3, 1, 4], []],
  484. ((np.float(4), np.uint8(10), np.int(32), np.int16(55)),)):
  485. with self.assertRaises(TypeError, msg=get_no_exception_msg(not_convertible)):
  486. _ = cv.utils.dumpVectorOfRect(not_convertible)
  487. def test_vector_general_return(self):
  488. expected_number_of_mats = 5
  489. expected_shape = (10, 10, 3)
  490. expected_type = np.uint8
  491. mats = cv.utils.generateVectorOfMat(5, 10, 10, cv.CV_8UC3)
  492. self.assertTrue(isinstance(mats, tuple),
  493. "Vector of Mats objects should be returned as tuple. Got: {}".format(type(mats)))
  494. self.assertEqual(len(mats), expected_number_of_mats, "Returned array has wrong length")
  495. for mat in mats:
  496. self.assertEqual(mat.shape, expected_shape, "Returned Mat has wrong shape")
  497. self.assertEqual(mat.dtype, expected_type, "Returned Mat has wrong elements type")
  498. empty_mats = cv.utils.generateVectorOfMat(0, 10, 10, cv.CV_32FC1)
  499. self.assertTrue(isinstance(empty_mats, tuple),
  500. "Empty vector should be returned as empty tuple. Got: {}".format(type(mats)))
  501. self.assertEqual(len(empty_mats), 0, "Vector of size 0 should be returned as tuple of length 0")
  502. def test_vector_fast_return(self):
  503. expected_shape = (5, 4)
  504. rects = cv.utils.generateVectorOfRect(expected_shape[0])
  505. self.assertTrue(isinstance(rects, np.ndarray),
  506. "Vector of rectangles should be returned as numpy array. Got: {}".format(type(rects)))
  507. self.assertEqual(rects.dtype, np.int32, "Vector of rectangles has wrong elements type")
  508. self.assertEqual(rects.shape, expected_shape, "Vector of rectangles has wrong shape")
  509. empty_rects = cv.utils.generateVectorOfRect(0)
  510. self.assertTrue(isinstance(empty_rects, tuple),
  511. "Empty vector should be returned as empty tuple. Got: {}".format(type(empty_rects)))
  512. self.assertEqual(len(empty_rects), 0, "Vector of size 0 should be returned as tuple of length 0")
  513. expected_shape = (10,)
  514. ints = cv.utils.generateVectorOfInt(expected_shape[0])
  515. self.assertTrue(isinstance(ints, np.ndarray),
  516. "Vector of integers should be returned as numpy array. Got: {}".format(type(ints)))
  517. self.assertEqual(ints.dtype, np.int32, "Vector of integers has wrong elements type")
  518. self.assertEqual(ints.shape, expected_shape, "Vector of integers has wrong shape.")
  519. def test_result_rotated_rect_issue_20930(self):
  520. rr = cv.utils.testRotatedRect(10, 20, 100, 200, 45)
  521. self.assertTrue(isinstance(rr, tuple), msg=type(rr))
  522. self.assertEqual(len(rr), 3)
  523. rrv = cv.utils.testRotatedRectVector(10, 20, 100, 200, 45)
  524. self.assertTrue(isinstance(rrv, tuple), msg=type(rrv))
  525. self.assertEqual(len(rrv), 10)
  526. rr = rrv[0]
  527. self.assertTrue(isinstance(rr, tuple), msg=type(rrv))
  528. self.assertEqual(len(rr), 3)
  529. def test_nested_function_availability(self):
  530. self.assertTrue(hasattr(cv.utils, "nested"),
  531. msg="Module is not generated for nested namespace")
  532. self.assertTrue(hasattr(cv.utils.nested, "testEchoBooleanFunction"),
  533. msg="Function in nested module is not available")
  534. if sys.version_info[0] < 3:
  535. # Nested submodule is managed only by the global submodules dictionary
  536. # and parent native module
  537. expected_ref_count = 2
  538. else:
  539. # Nested submodule is managed by the global submodules dictionary,
  540. # parent native module and Python part of the submodule
  541. expected_ref_count = 3
  542. # `getrefcount` temporary increases reference counter by 1
  543. actual_ref_count = sys.getrefcount(cv.utils.nested) - 1
  544. self.assertEqual(actual_ref_count, expected_ref_count,
  545. msg="Nested submodule reference counter has wrong value\n"
  546. "Expected: {}. Actual: {}".format(expected_ref_count, actual_ref_count))
  547. for flag in (True, False):
  548. self.assertEqual(flag, cv.utils.nested.testEchoBooleanFunction(flag),
  549. msg="Function in nested module returns wrong result")
  550. class CanUsePurePythonModuleFunction(NewOpenCVTests):
  551. def test_can_get_ocv_version(self):
  552. import sys
  553. if sys.version_info[0] < 3:
  554. raise unittest.SkipTest('Python 2.x is not supported')
  555. self.assertEqual(cv.misc.get_ocv_version(), cv.__version__,
  556. "Can't get package version using Python misc module")
  557. def test_native_method_can_be_patched(self):
  558. import sys
  559. if sys.version_info[0] < 3:
  560. raise unittest.SkipTest('Python 2.x is not supported')
  561. res = cv.utils.testOverwriteNativeMethod(10)
  562. self.assertTrue(isinstance(res, Sequence),
  563. msg="Overwritten method should return sequence. "
  564. "Got: {} of type {}".format(res, type(res)))
  565. self.assertSequenceEqual(res, (11, 10),
  566. msg="Failed to overwrite native method")
  567. res = cv.utils._native.testOverwriteNativeMethod(123)
  568. self.assertEqual(res, 123, msg="Failed to call native method implementation")
  569. class SamplesFindFile(NewOpenCVTests):
  570. def test_ExistedFile(self):
  571. res = cv.samples.findFile('lena.jpg', False)
  572. self.assertNotEqual(res, '')
  573. def test_MissingFile(self):
  574. res = cv.samples.findFile('non_existed.file', False)
  575. self.assertEqual(res, '')
  576. def test_MissingFileException(self):
  577. try:
  578. _res = cv.samples.findFile('non_existed.file', True)
  579. self.assertEqual("Dead code", 0)
  580. except cv.error as _e:
  581. pass
  582. if __name__ == '__main__':
  583. NewOpenCVTests.bootstrap()