test_misc.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  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. def test_properties_with_reserved_keywords_names_are_transformed(self):
  101. obj = cv.utils.ClassWithKeywordProperties(except_arg=23)
  102. self.assertTrue(hasattr(obj, "lambda_"),
  103. msg="Class doesn't have RW property with converted name")
  104. try:
  105. obj.lambda_ = 32
  106. except Exception as e:
  107. self.fail("Failed to set value to RW property. Error: {}".format(e))
  108. self.assertTrue(hasattr(obj, "except_"),
  109. msg="Class doesn't have readonly property with converted name")
  110. self.assertEqual(obj.except_, 23,
  111. msg="Can't access readonly property value")
  112. with self.assertRaises(AttributeError):
  113. obj.except_ = 32
  114. def test_maketype(self):
  115. data = {
  116. cv.CV_8UC3: [cv.CV_8U, 3, cv.CV_8UC],
  117. cv.CV_16SC1: [cv.CV_16S, 1, cv.CV_16SC],
  118. cv.CV_32FC4: [cv.CV_32F, 4, cv.CV_32FC],
  119. cv.CV_64FC2: [cv.CV_64F, 2, cv.CV_64FC],
  120. cv.CV_8SC4: [cv.CV_8S, 4, cv.CV_8SC],
  121. cv.CV_16UC2: [cv.CV_16U, 2, cv.CV_16UC],
  122. cv.CV_32SC1: [cv.CV_32S, 1, cv.CV_32SC],
  123. cv.CV_16FC3: [cv.CV_16F, 3, cv.CV_16FC],
  124. }
  125. for ref, (depth, channels, func) in data.items():
  126. self.assertEqual(ref, cv.CV_MAKETYPE(depth, channels))
  127. self.assertEqual(ref, func(channels))
  128. class Arguments(NewOpenCVTests):
  129. def _try_to_convert(self, conversion, value):
  130. try:
  131. result = conversion(value).lower()
  132. except Exception as e:
  133. self.fail(
  134. '{} "{}" is risen for conversion {} of type {}'.format(
  135. type(e).__name__, e, value, type(value).__name__
  136. )
  137. )
  138. else:
  139. return result
  140. def test_InputArray(self):
  141. res1 = cv.utils.dumpInputArray(None)
  142. # self.assertEqual(res1, "InputArray: noArray()") # not supported
  143. self.assertEqual(res1, "InputArray: empty()=true kind=0x00010000 flags=0x01010000 total(-1)=0 dims(-1)=0 size(-1)=0x0 type(-1)=CV_8UC1")
  144. res2_1 = cv.utils.dumpInputArray((1, 2))
  145. self.assertEqual(res2_1, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=2 dims(-1)=2 size(-1)=1x2 type(-1)=CV_64FC1")
  146. res2_2 = cv.utils.dumpInputArray(1.5) # Scalar(1.5, 1.5, 1.5, 1.5)
  147. self.assertEqual(res2_2, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=4 dims(-1)=2 size(-1)=1x4 type(-1)=CV_64FC1")
  148. a = np.array([[1, 2], [3, 4], [5, 6]])
  149. res3 = cv.utils.dumpInputArray(a) # 32SC1
  150. self.assertEqual(res3, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=6 dims(-1)=2 size(-1)=2x3 type(-1)=CV_32SC1")
  151. a = np.array([[[1, 2], [3, 4], [5, 6]]], dtype='f')
  152. res4 = cv.utils.dumpInputArray(a) # 32FC2
  153. self.assertEqual(res4, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=3 dims(-1)=2 size(-1)=3x1 type(-1)=CV_32FC2")
  154. a = np.array([[[1, 2]], [[3, 4]], [[5, 6]]], dtype=float)
  155. res5 = cv.utils.dumpInputArray(a) # 64FC2
  156. self.assertEqual(res5, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=3 dims(-1)=2 size(-1)=1x3 type(-1)=CV_64FC2")
  157. a = np.zeros((2,3,4), dtype='f')
  158. res6 = cv.utils.dumpInputArray(a)
  159. self.assertEqual(res6, "InputArray: empty()=false kind=0x00010000 flags=0x01010000 total(-1)=6 dims(-1)=2 size(-1)=3x2 type(-1)=CV_32FC4")
  160. a = np.zeros((2,3,4,5), dtype='f')
  161. res7 = cv.utils.dumpInputArray(a)
  162. 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")
  163. def test_InputArrayOfArrays(self):
  164. res1 = cv.utils.dumpInputArrayOfArrays(None)
  165. # self.assertEqual(res1, "InputArray: noArray()") # not supported
  166. self.assertEqual(res1, "InputArrayOfArrays: empty()=true kind=0x00050000 flags=0x01050000 total(-1)=0 dims(-1)=1 size(-1)=0x0")
  167. res2_1 = cv.utils.dumpInputArrayOfArrays((1, 2)) # { Scalar:all(1), Scalar::all(2) }
  168. 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")
  169. res2_2 = cv.utils.dumpInputArrayOfArrays([1.5])
  170. 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")
  171. a = np.array([[1, 2], [3, 4], [5, 6]])
  172. b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  173. res3 = cv.utils.dumpInputArrayOfArrays([a, b])
  174. 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")
  175. c = np.array([[[1, 2], [3, 4], [5, 6]]], dtype='f')
  176. res4 = cv.utils.dumpInputArrayOfArrays([c, a, b])
  177. 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")
  178. a = np.zeros((2,3,4), dtype='f')
  179. res5 = cv.utils.dumpInputArrayOfArrays([a, b])
  180. 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")
  181. # TODO: fix conversion error
  182. #a = np.zeros((2,3,4,5), dtype='f')
  183. #res6 = cv.utils.dumpInputArray([a, b])
  184. #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]")
  185. def test_20968(self):
  186. pixel = np.uint8([[[40, 50, 200]]])
  187. _ = cv.cvtColor(pixel, cv.COLOR_RGB2BGR) # should not raise exception
  188. def test_parse_to_bool_convertible(self):
  189. try_to_convert = partial(self._try_to_convert, cv.utils.dumpBool)
  190. for convertible_true in (True, 1, 64, np.int8(123), np.int16(11), np.int32(2),
  191. np.int64(1), np.bool_(12)):
  192. actual = try_to_convert(convertible_true)
  193. self.assertEqual('bool: true', actual,
  194. msg=get_conversion_error_msg(convertible_true, 'bool: true', actual))
  195. for convertible_false in (False, 0, np.uint8(0), np.bool_(0), np.int_(0)):
  196. actual = try_to_convert(convertible_false)
  197. self.assertEqual('bool: false', actual,
  198. msg=get_conversion_error_msg(convertible_false, 'bool: false', actual))
  199. def test_parse_to_bool_not_convertible(self):
  200. for not_convertible in (1.2, np.float32(2.3), 's', 'str', (1, 2), [1, 2], complex(1, 1),
  201. complex(imag=2), complex(1.1), np.array([1, 0], dtype=bool)):
  202. with self.assertRaises((TypeError, OverflowError),
  203. msg=get_no_exception_msg(not_convertible)):
  204. _ = cv.utils.dumpBool(not_convertible)
  205. def test_parse_to_bool_convertible_extra(self):
  206. try_to_convert = partial(self._try_to_convert, cv.utils.dumpBool)
  207. _, max_size_t = get_limits(ctypes.c_size_t)
  208. for convertible_true in (-1, max_size_t):
  209. actual = try_to_convert(convertible_true)
  210. self.assertEqual('bool: true', actual,
  211. msg=get_conversion_error_msg(convertible_true, 'bool: true', actual))
  212. def test_parse_to_bool_not_convertible_extra(self):
  213. for not_convertible in (np.array([False]), np.array([True])):
  214. with self.assertRaises((TypeError, OverflowError),
  215. msg=get_no_exception_msg(not_convertible)):
  216. _ = cv.utils.dumpBool(not_convertible)
  217. def test_parse_to_int_convertible(self):
  218. try_to_convert = partial(self._try_to_convert, cv.utils.dumpInt)
  219. min_int, max_int = get_limits(ctypes.c_int)
  220. for convertible in (-10, -1, 2, int(43.2), np.uint8(15), np.int8(33), np.int16(-13),
  221. np.int32(4), np.int64(345), (23), min_int, max_int, np.int_(33)):
  222. expected = 'int: {0:d}'.format(convertible)
  223. actual = try_to_convert(convertible)
  224. self.assertEqual(expected, actual,
  225. msg=get_conversion_error_msg(convertible, expected, actual))
  226. def test_parse_to_int_not_convertible(self):
  227. min_int, max_int = get_limits(ctypes.c_int)
  228. for not_convertible in (1.2, float(3), np.float32(4), np.double(45), 's', 'str',
  229. np.array([1, 2]), (1,), [1, 2], min_int - 1, max_int + 1,
  230. complex(1, 1), complex(imag=2), complex(1.1)):
  231. with self.assertRaises((TypeError, OverflowError, ValueError),
  232. msg=get_no_exception_msg(not_convertible)):
  233. _ = cv.utils.dumpInt(not_convertible)
  234. def test_parse_to_int_not_convertible_extra(self):
  235. for not_convertible in (np.bool_(True), True, False, np.float32(2.3),
  236. np.array([3, ], dtype=int), np.array([-2, ], dtype=np.int32),
  237. np.array([11, ], dtype=np.uint8)):
  238. with self.assertRaises((TypeError, OverflowError),
  239. msg=get_no_exception_msg(not_convertible)):
  240. _ = cv.utils.dumpInt(not_convertible)
  241. def test_parse_to_int64_convertible(self):
  242. try_to_convert = partial(self._try_to_convert, cv.utils.dumpInt64)
  243. min_int64, max_int64 = get_limits(ctypes.c_longlong)
  244. for convertible in (-10, -1, 2, int(43.2), np.uint8(15), np.int8(33), np.int16(-13),
  245. np.int32(4), np.int64(345), (23), min_int64, max_int64, np.int_(33)):
  246. expected = 'int64: {0:d}'.format(convertible)
  247. actual = try_to_convert(convertible)
  248. self.assertEqual(expected, actual,
  249. msg=get_conversion_error_msg(convertible, expected, actual))
  250. def test_parse_to_int64_not_convertible(self):
  251. min_int64, max_int64 = get_limits(ctypes.c_longlong)
  252. for not_convertible in (1.2, np.float32(4), float(3), np.double(45), 's', 'str',
  253. np.array([1, 2]), (1,), [1, 2], min_int64 - 1, max_int64 + 1,
  254. complex(1, 1), complex(imag=2), complex(1.1), np.bool_(True),
  255. True, False, np.float32(2.3), np.array([3, ], dtype=int),
  256. np.array([-2, ], dtype=np.int32), np.array([11, ], dtype=np.uint8)):
  257. with self.assertRaises((TypeError, OverflowError, ValueError),
  258. msg=get_no_exception_msg(not_convertible)):
  259. _ = cv.utils.dumpInt64(not_convertible)
  260. def test_parse_to_size_t_convertible(self):
  261. try_to_convert = partial(self._try_to_convert, cv.utils.dumpSizeT)
  262. _, max_uint = get_limits(ctypes.c_uint)
  263. for convertible in (2, max_uint, (12), np.uint8(34), np.int8(12), np.int16(23),
  264. np.int32(123), np.int64(344), np.uint64(3), np.uint16(2), np.uint32(5),
  265. np.uint(44)):
  266. expected = 'size_t: {0:d}'.format(convertible).lower()
  267. actual = try_to_convert(convertible)
  268. self.assertEqual(expected, actual,
  269. msg=get_conversion_error_msg(convertible, expected, actual))
  270. def test_parse_to_size_t_not_convertible(self):
  271. min_long, _ = get_limits(ctypes.c_long)
  272. for not_convertible in (1.2, True, False, np.bool_(True), np.float32(4), float(3),
  273. np.double(45), 's', 'str', np.array([1, 2]), (1,), [1, 2],
  274. np.float64(6), complex(1, 1), complex(imag=2), complex(1.1),
  275. -1, min_long, np.int8(-35)):
  276. with self.assertRaises((TypeError, OverflowError),
  277. msg=get_no_exception_msg(not_convertible)):
  278. _ = cv.utils.dumpSizeT(not_convertible)
  279. def test_parse_to_size_t_convertible_extra(self):
  280. try_to_convert = partial(self._try_to_convert, cv.utils.dumpSizeT)
  281. _, max_size_t = get_limits(ctypes.c_size_t)
  282. for convertible in (max_size_t,):
  283. expected = 'size_t: {0:d}'.format(convertible).lower()
  284. actual = try_to_convert(convertible)
  285. self.assertEqual(expected, actual,
  286. msg=get_conversion_error_msg(convertible, expected, actual))
  287. def test_parse_to_size_t_not_convertible_extra(self):
  288. for not_convertible in (np.bool_(True), True, False, np.array([123, ], dtype=np.uint8),):
  289. with self.assertRaises((TypeError, OverflowError),
  290. msg=get_no_exception_msg(not_convertible)):
  291. _ = cv.utils.dumpSizeT(not_convertible)
  292. def test_parse_to_float_convertible(self):
  293. try_to_convert = partial(self._try_to_convert, cv.utils.dumpFloat)
  294. min_float, max_float = get_limits(ctypes.c_float)
  295. for convertible in (2, -13, 1.24, np.float32(32.45), float(32), np.double(12.23),
  296. np.float32(-12.3), np.float64(3.22), np.float_(-1.5), min_float,
  297. max_float, np.inf, -np.inf, float('Inf'), -float('Inf'),
  298. np.double(np.inf), np.double(-np.inf), np.double(float('Inf')),
  299. np.double(-float('Inf'))):
  300. expected = 'Float: {0:.2f}'.format(convertible).lower()
  301. actual = try_to_convert(convertible)
  302. self.assertEqual(expected, actual,
  303. msg=get_conversion_error_msg(convertible, expected, actual))
  304. # Workaround for Windows NaN tests due to Visual C runtime
  305. # special floating point values (indefinite NaN)
  306. for nan in (float('NaN'), np.nan, np.float32(np.nan), np.double(np.nan),
  307. np.double(float('NaN'))):
  308. actual = try_to_convert(nan)
  309. self.assertIn('nan', actual, msg="Can't convert nan of type {} to float. "
  310. "Actual: {}".format(type(nan).__name__, actual))
  311. min_double, max_double = get_limits(ctypes.c_double)
  312. for inf in (min_float * 10, max_float * 10, min_double, max_double):
  313. expected = 'float: {}inf'.format('-' if inf < 0 else '')
  314. actual = try_to_convert(inf)
  315. self.assertEqual(expected, actual,
  316. msg=get_conversion_error_msg(inf, expected, actual))
  317. def test_parse_to_float_not_convertible(self):
  318. for not_convertible in ('s', 'str', (12,), [1, 2], np.array([1, 2], dtype=float),
  319. np.array([1, 2], dtype=np.double), complex(1, 1), complex(imag=2),
  320. complex(1.1)):
  321. with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
  322. _ = cv.utils.dumpFloat(not_convertible)
  323. def test_parse_to_float_not_convertible_extra(self):
  324. for not_convertible in (np.bool_(False), True, False, np.array([123, ], dtype=int),
  325. np.array([1., ]), np.array([False]),
  326. np.array([True])):
  327. with self.assertRaises((TypeError, OverflowError),
  328. msg=get_no_exception_msg(not_convertible)):
  329. _ = cv.utils.dumpFloat(not_convertible)
  330. def test_parse_to_double_convertible(self):
  331. try_to_convert = partial(self._try_to_convert, cv.utils.dumpDouble)
  332. min_float, max_float = get_limits(ctypes.c_float)
  333. min_double, max_double = get_limits(ctypes.c_double)
  334. for convertible in (2, -13, 1.24, np.float32(32.45), float(2), np.double(12.23),
  335. np.float32(-12.3), np.float64(3.22), np.float_(-1.5), min_float,
  336. max_float, min_double, max_double, np.inf, -np.inf, float('Inf'),
  337. -float('Inf'), np.double(np.inf), np.double(-np.inf),
  338. np.double(float('Inf')), np.double(-float('Inf'))):
  339. expected = 'Double: {0:.2f}'.format(convertible).lower()
  340. actual = try_to_convert(convertible)
  341. self.assertEqual(expected, actual,
  342. msg=get_conversion_error_msg(convertible, expected, actual))
  343. # Workaround for Windows NaN tests due to Visual C runtime
  344. # special floating point values (indefinite NaN)
  345. for nan in (float('NaN'), np.nan, np.double(np.nan),
  346. np.double(float('NaN'))):
  347. actual = try_to_convert(nan)
  348. self.assertIn('nan', actual, msg="Can't convert nan of type {} to double. "
  349. "Actual: {}".format(type(nan).__name__, actual))
  350. def test_parse_to_double_not_convertible(self):
  351. for not_convertible in ('s', 'str', (12,), [1, 2], np.array([1, 2], dtype=np.float32),
  352. np.array([1, 2], dtype=np.double), complex(1, 1), complex(imag=2),
  353. complex(1.1)):
  354. with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
  355. _ = cv.utils.dumpDouble(not_convertible)
  356. def test_parse_to_double_not_convertible_extra(self):
  357. for not_convertible in (np.bool_(False), True, False, np.array([123, ], dtype=int),
  358. np.array([1., ]), np.array([False]),
  359. np.array([12.4], dtype=np.double), np.array([True])):
  360. with self.assertRaises((TypeError, OverflowError),
  361. msg=get_no_exception_msg(not_convertible)):
  362. _ = cv.utils.dumpDouble(not_convertible)
  363. def test_parse_to_cstring_convertible(self):
  364. try_to_convert = partial(self._try_to_convert, cv.utils.dumpCString)
  365. for convertible in ('', 's', 'str', str(123), ('char'), np.str_('test2')):
  366. expected = 'string: ' + convertible
  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_cstring_not_convertible(self):
  371. for not_convertible in ((12,), ('t', 'e', 's', 't'), np.array(['123', ]),
  372. np.array(['t', 'e', 's', 't']), 1, -1.4, True, False, None):
  373. with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
  374. _ = cv.utils.dumpCString(not_convertible)
  375. def test_parse_to_string_convertible(self):
  376. try_to_convert = partial(self._try_to_convert, cv.utils.dumpString)
  377. for convertible in (None, '', 's', 'str', str(123), np.str_('test2')):
  378. expected = 'string: ' + (convertible if convertible else '')
  379. actual = try_to_convert(convertible)
  380. self.assertEqual(expected, actual,
  381. msg=get_conversion_error_msg(convertible, expected, actual))
  382. def test_parse_to_string_not_convertible(self):
  383. for not_convertible in ((12,), ('t', 'e', 's', 't'), np.array(['123', ]),
  384. np.array(['t', 'e', 's', 't']), 1, True, False):
  385. with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
  386. _ = cv.utils.dumpString(not_convertible)
  387. def test_parse_to_rect_convertible(self):
  388. Rect = namedtuple('Rect', ('x', 'y', 'w', 'h'))
  389. try_to_convert = partial(self._try_to_convert, cv.utils.dumpRect)
  390. for convertible in ((1, 2, 4, 5), [5, 3, 10, 20], np.array([10, 20, 23, 10]),
  391. Rect(10, 30, 40, 55), tuple(np.array([40, 20, 24, 20])),
  392. list(np.array([20, 40, 30, 35]))):
  393. expected = 'rect: (x={}, y={}, w={}, h={})'.format(*convertible)
  394. actual = try_to_convert(convertible)
  395. self.assertEqual(expected, actual,
  396. msg=get_conversion_error_msg(convertible, expected, actual))
  397. def test_parse_to_rect_not_convertible(self):
  398. for not_convertible in (np.empty(shape=(4, 1)), (), [], np.array([]), (12, ),
  399. [3, 4, 5, 10, 123], {1: 2, 3:4, 5:10, 6:30},
  400. '1234', np.array([1, 2, 3, 4], dtype=np.float32),
  401. np.array([[1, 2], [3, 4], [5, 6], [6, 8]]), (1, 2, 5, 1.5)):
  402. with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
  403. _ = cv.utils.dumpRect(not_convertible)
  404. def test_parse_to_rotated_rect_convertible(self):
  405. RotatedRect = namedtuple('RotatedRect', ('center', 'size', 'angle'))
  406. try_to_convert = partial(self._try_to_convert, cv.utils.dumpRotatedRect)
  407. for convertible in (((2.5, 2.5), (10., 20.), 12.5), [[1.5, 10.5], (12.5, 51.5), 10],
  408. RotatedRect((10, 40), np.array([10.5, 20.5]), 5),
  409. np.array([[10, 6], [50, 50], 5.5], dtype=object)):
  410. center, size, angle = convertible
  411. expected = 'rotated_rect: (c_x={:.6f}, c_y={:.6f}, w={:.6f},' \
  412. ' h={:.6f}, a={:.6f})'.format(center[0], center[1],
  413. size[0], size[1], angle)
  414. actual = try_to_convert(convertible)
  415. self.assertEqual(expected, actual,
  416. msg=get_conversion_error_msg(convertible, expected, actual))
  417. def test_wrap_rotated_rect(self):
  418. center = (34.5, 52.)
  419. size = (565.0, 140.0)
  420. angle = -177.5
  421. rect1 = cv.RotatedRect(center, size, angle)
  422. self.assertEqual(rect1.center, center)
  423. self.assertEqual(rect1.size, size)
  424. self.assertEqual(rect1.angle, angle)
  425. pts = [[ 319.7845, -5.6109037],
  426. [ 313.6778, 134.25586],
  427. [-250.78448, 109.6109],
  428. [-244.6778, -30.25586]]
  429. self.assertLess(np.max(np.abs(rect1.points() - pts)), 1e-4)
  430. rect2 = cv.RotatedRect(pts[0], pts[1], pts[2])
  431. _, inter_pts = cv.rotatedRectangleIntersection(rect1, rect2)
  432. self.assertLess(np.max(np.abs(inter_pts.reshape(-1, 2) - pts)), 1e-4)
  433. def test_parse_to_rotated_rect_not_convertible(self):
  434. for not_convertible in ([], (), np.array([]), (123, (45, 34), 1), {1: 2, 3: 4}, 123,
  435. np.array([[123, 123, 14], [1, 3], 56], dtype=object), '123'):
  436. with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
  437. _ = cv.utils.dumpRotatedRect(not_convertible)
  438. def test_parse_to_term_criteria_convertible(self):
  439. TermCriteria = namedtuple('TermCriteria', ('type', 'max_count', 'epsilon'))
  440. try_to_convert = partial(self._try_to_convert, cv.utils.dumpTermCriteria)
  441. for convertible in ((1, 10, 1e-3), [2, 30, 1e-1], np.array([10, 20, 0.5], dtype=object),
  442. TermCriteria(0, 5, 0.1)):
  443. expected = 'term_criteria: (type={}, max_count={}, epsilon={:.6f}'.format(*convertible)
  444. actual = try_to_convert(convertible)
  445. self.assertEqual(expected, actual,
  446. msg=get_conversion_error_msg(convertible, expected, actual))
  447. def test_parse_to_term_criteria_not_convertible(self):
  448. for not_convertible in ([], (), np.array([]), [1, 4], (10,), (1.5, 34, 0.1),
  449. {1: 5, 3: 5, 10: 10}, '145'):
  450. with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
  451. _ = cv.utils.dumpTermCriteria(not_convertible)
  452. def test_parse_to_range_convertible_to_all(self):
  453. try_to_convert = partial(self._try_to_convert, cv.utils.dumpRange)
  454. for convertible in ((), [], np.array([])):
  455. expected = 'range: all'
  456. actual = try_to_convert(convertible)
  457. self.assertEqual(expected, actual,
  458. msg=get_conversion_error_msg(convertible, expected, actual))
  459. def test_parse_to_range_convertible(self):
  460. Range = namedtuple('Range', ('start', 'end'))
  461. try_to_convert = partial(self._try_to_convert, cv.utils.dumpRange)
  462. for convertible in ((10, 20), [-1, 3], np.array([10, 24]), Range(-4, 6)):
  463. expected = 'range: (s={}, e={})'.format(*convertible)
  464. actual = try_to_convert(convertible)
  465. self.assertEqual(expected, actual,
  466. msg=get_conversion_error_msg(convertible, expected, actual))
  467. def test_parse_to_range_not_convertible(self):
  468. for not_convertible in ((1, ), [40, ], np.array([1, 4, 6]), {'a': 1, 'b': 40},
  469. (1.5, 13.5), [3, 6.7], np.array([6.3, 2.1]), '14, 4'):
  470. with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)):
  471. _ = cv.utils.dumpRange(not_convertible)
  472. def test_reserved_keywords_are_transformed(self):
  473. default_lambda_value = 2
  474. default_from_value = 3
  475. format_str = "arg={}, lambda={}, from={}"
  476. self.assertEqual(
  477. cv.utils.testReservedKeywordConversion(20), format_str.format(20, default_lambda_value, default_from_value)
  478. )
  479. self.assertEqual(
  480. cv.utils.testReservedKeywordConversion(10, lambda_=10), format_str.format(10, 10, default_from_value)
  481. )
  482. self.assertEqual(
  483. cv.utils.testReservedKeywordConversion(10, from_=10), format_str.format(10, default_lambda_value, 10)
  484. )
  485. self.assertEqual(
  486. cv.utils.testReservedKeywordConversion(20, lambda_=-4, from_=12), format_str.format(20, -4, 12)
  487. )
  488. def test_parse_vector_int_convertible(self):
  489. np.random.seed(123098765)
  490. try_to_convert = partial(self._try_to_convert, cv.utils.dumpVectorOfInt)
  491. arr = np.random.randint(-20, 20, 40).astype(np.int32).reshape(10, 2, 2)
  492. int_min, int_max = get_limits(ctypes.c_int)
  493. for convertible in ((int_min, 1, 2, 3, int_max), [40, 50], tuple(),
  494. np.array([int_min, -10, 24, int_max], dtype=np.int32),
  495. np.array([10, 230, 12], dtype=np.uint8), arr[:, 0, 1],):
  496. expected = "[" + ", ".join(map(str, convertible)) + "]"
  497. actual = try_to_convert(convertible)
  498. self.assertEqual(expected, actual,
  499. msg=get_conversion_error_msg(convertible, expected, actual))
  500. def test_parse_vector_int_not_convertible(self):
  501. np.random.seed(123098765)
  502. arr = np.random.randint(-20, 20, 40).astype(np.float32).reshape(10, 2, 2)
  503. int_min, int_max = get_limits(ctypes.c_int)
  504. test_dict = {1: 2, 3: 10, 10: 20}
  505. for not_convertible in ((int_min, 1, 2.5, 3, int_max), [True, 50], 'test', test_dict,
  506. reversed([1, 2, 3]),
  507. np.array([int_min, -10, 24, [1, 2]], dtype=object),
  508. np.array([[1, 2], [3, 4]]), arr[:, 0, 1],):
  509. with self.assertRaises(TypeError, msg=get_no_exception_msg(not_convertible)):
  510. _ = cv.utils.dumpVectorOfInt(not_convertible)
  511. def test_parse_vector_double_convertible(self):
  512. np.random.seed(1230965)
  513. try_to_convert = partial(self._try_to_convert, cv.utils.dumpVectorOfDouble)
  514. arr = np.random.randint(-20, 20, 40).astype(np.int32).reshape(10, 2, 2)
  515. for convertible in ((1, 2.12, 3.5), [40, 50], tuple(),
  516. np.array([-10, 24], dtype=np.int32),
  517. np.array([-12.5, 1.4], dtype=np.double),
  518. np.array([10, 230, 12], dtype=np.float32), arr[:, 0, 1], ):
  519. expected = "[" + ", ".join(map(lambda v: "{:.2f}".format(v), convertible)) + "]"
  520. actual = try_to_convert(convertible)
  521. self.assertEqual(expected, actual,
  522. msg=get_conversion_error_msg(convertible, expected, actual))
  523. def test_parse_vector_double_not_convertible(self):
  524. test_dict = {1: 2, 3: 10, 10: 20}
  525. for not_convertible in (('t', 'e', 's', 't'), [True, 50.55], 'test', test_dict,
  526. np.array([-10.1, 24.5, [1, 2]], dtype=object),
  527. np.array([[1, 2], [3, 4]]),):
  528. with self.assertRaises(TypeError, msg=get_no_exception_msg(not_convertible)):
  529. _ = cv.utils.dumpVectorOfDouble(not_convertible)
  530. def test_parse_vector_rect_convertible(self):
  531. np.random.seed(1238765)
  532. try_to_convert = partial(self._try_to_convert, cv.utils.dumpVectorOfRect)
  533. arr_of_rect_int32 = np.random.randint(5, 20, 4 * 3).astype(np.int32).reshape(3, 4)
  534. arr_of_rect_cast = np.random.randint(10, 40, 4 * 5).astype(np.uint8).reshape(5, 4)
  535. for convertible in (((1, 2, 3, 4), (10, -20, 30, 10)), arr_of_rect_int32, arr_of_rect_cast,
  536. arr_of_rect_int32.astype(np.int8), [[5, 3, 1, 4]],
  537. ((np.int8(4), np.uint8(10), int(32), np.int16(55)),)):
  538. expected = "[" + ", ".join(map(lambda v: "[x={}, y={}, w={}, h={}]".format(*v), convertible)) + "]"
  539. actual = try_to_convert(convertible)
  540. self.assertEqual(expected, actual,
  541. msg=get_conversion_error_msg(convertible, expected, actual))
  542. def test_parse_vector_rect_not_convertible(self):
  543. np.random.seed(1238765)
  544. arr = np.random.randint(5, 20, 4 * 3).astype(np.float32).reshape(3, 4)
  545. for not_convertible in (((1, 2, 3, 4), (10.5, -20, 30.1, 10)), arr,
  546. [[5, 3, 1, 4], []],
  547. ((float(4), np.uint8(10), int(32), np.int16(55)),)):
  548. with self.assertRaises(TypeError, msg=get_no_exception_msg(not_convertible)):
  549. _ = cv.utils.dumpVectorOfRect(not_convertible)
  550. def test_vector_general_return(self):
  551. expected_number_of_mats = 5
  552. expected_shape = (10, 10, 3)
  553. expected_type = np.uint8
  554. mats = cv.utils.generateVectorOfMat(5, 10, 10, cv.CV_8UC3)
  555. self.assertTrue(isinstance(mats, tuple),
  556. "Vector of Mats objects should be returned as tuple. Got: {}".format(type(mats)))
  557. self.assertEqual(len(mats), expected_number_of_mats, "Returned array has wrong length")
  558. for mat in mats:
  559. self.assertEqual(mat.shape, expected_shape, "Returned Mat has wrong shape")
  560. self.assertEqual(mat.dtype, expected_type, "Returned Mat has wrong elements type")
  561. empty_mats = cv.utils.generateVectorOfMat(0, 10, 10, cv.CV_32FC1)
  562. self.assertTrue(isinstance(empty_mats, tuple),
  563. "Empty vector should be returned as empty tuple. Got: {}".format(type(mats)))
  564. self.assertEqual(len(empty_mats), 0, "Vector of size 0 should be returned as tuple of length 0")
  565. def test_vector_fast_return(self):
  566. expected_shape = (5, 4)
  567. rects = cv.utils.generateVectorOfRect(expected_shape[0])
  568. self.assertTrue(isinstance(rects, np.ndarray),
  569. "Vector of rectangles should be returned as numpy array. Got: {}".format(type(rects)))
  570. self.assertEqual(rects.dtype, np.int32, "Vector of rectangles has wrong elements type")
  571. self.assertEqual(rects.shape, expected_shape, "Vector of rectangles has wrong shape")
  572. empty_rects = cv.utils.generateVectorOfRect(0)
  573. self.assertTrue(isinstance(empty_rects, tuple),
  574. "Empty vector should be returned as empty tuple. Got: {}".format(type(empty_rects)))
  575. self.assertEqual(len(empty_rects), 0, "Vector of size 0 should be returned as tuple of length 0")
  576. expected_shape = (10,)
  577. ints = cv.utils.generateVectorOfInt(expected_shape[0])
  578. self.assertTrue(isinstance(ints, np.ndarray),
  579. "Vector of integers should be returned as numpy array. Got: {}".format(type(ints)))
  580. self.assertEqual(ints.dtype, np.int32, "Vector of integers has wrong elements type")
  581. self.assertEqual(ints.shape, expected_shape, "Vector of integers has wrong shape.")
  582. def test_result_rotated_rect_issue_20930(self):
  583. rr = cv.utils.testRotatedRect(10, 20, 100, 200, 45)
  584. self.assertTrue(isinstance(rr, tuple), msg=type(rr))
  585. self.assertEqual(len(rr), 3)
  586. rrv = cv.utils.testRotatedRectVector(10, 20, 100, 200, 45)
  587. self.assertTrue(isinstance(rrv, tuple), msg=type(rrv))
  588. self.assertEqual(len(rrv), 10)
  589. rr = rrv[0]
  590. self.assertTrue(isinstance(rr, tuple), msg=type(rrv))
  591. self.assertEqual(len(rr), 3)
  592. def test_nested_function_availability(self):
  593. self.assertTrue(hasattr(cv.utils, "nested"),
  594. msg="Module is not generated for nested namespace")
  595. self.assertTrue(hasattr(cv.utils.nested, "testEchoBooleanFunction"),
  596. msg="Function in nested module is not available")
  597. if sys.version_info[0] < 3:
  598. # Nested submodule is managed only by the global submodules dictionary
  599. # and parent native module
  600. expected_ref_count = 2
  601. else:
  602. # Nested submodule is managed by the global submodules dictionary,
  603. # parent native module and Python part of the submodule
  604. expected_ref_count = 3
  605. # `getrefcount` temporary increases reference counter by 1
  606. actual_ref_count = sys.getrefcount(cv.utils.nested) - 1
  607. self.assertEqual(actual_ref_count, expected_ref_count,
  608. msg="Nested submodule reference counter has wrong value\n"
  609. "Expected: {}. Actual: {}".format(expected_ref_count, actual_ref_count))
  610. for flag in (True, False):
  611. self.assertEqual(flag, cv.utils.nested.testEchoBooleanFunction(flag),
  612. msg="Function in nested module returns wrong result")
  613. def test_class_from_submodule_has_global_alias(self):
  614. self.assertTrue(hasattr(cv.ml, "Boost"),
  615. msg="Class is not registered in the submodule")
  616. self.assertTrue(hasattr(cv, "ml_Boost"),
  617. msg="Class from submodule doesn't have alias in the "
  618. "global module")
  619. self.assertEqual(cv.ml.Boost, cv.ml_Boost,
  620. msg="Classes from submodules and global module don't refer "
  621. "to the same type")
  622. def test_inner_class_has_global_alias(self):
  623. self.assertTrue(hasattr(cv.SimpleBlobDetector, "Params"),
  624. msg="Class is not registered as inner class")
  625. self.assertTrue(hasattr(cv, "SimpleBlobDetector_Params"),
  626. msg="Inner class doesn't have alias in the global module")
  627. self.assertEqual(cv.SimpleBlobDetector.Params, cv.SimpleBlobDetector_Params,
  628. msg="Inner class and class in global module don't refer "
  629. "to the same type")
  630. def test_export_class_with_different_name(self):
  631. self.assertTrue(hasattr(cv.utils.nested, "ExportClassName"),
  632. msg="Class with export alias is not registered in the submodule")
  633. self.assertTrue(hasattr(cv, "utils_nested_ExportClassName"),
  634. msg="Class with export alias doesn't have alias in the "
  635. "global module")
  636. self.assertEqual(cv.utils.nested.ExportClassName.originalName(), "OriginalClassName")
  637. instance = cv.utils.nested.ExportClassName.create()
  638. self.assertTrue(isinstance(instance, cv.utils.nested.ExportClassName),
  639. msg="Factory function returns wrong class instance: {}".format(type(instance)))
  640. self.assertTrue(hasattr(cv.utils.nested, "ExportClassName_create"),
  641. msg="Factory function should have alias in the same module as the class")
  642. # self.assertFalse(hasattr(cv.utils.nested, "OriginalClassName_create"),
  643. # msg="Factory function should not be registered with original class name, "\
  644. # "when class has different export name")
  645. def test_export_inner_class_of_class_exported_with_different_name(self):
  646. if not hasattr(cv.utils.nested, "ExportClassName"):
  647. raise unittest.SkipTest(
  648. "Outer class with export alias is not registered in the submodule")
  649. self.assertTrue(hasattr(cv.utils.nested.ExportClassName, "Params"),
  650. msg="Inner class with export alias is not registered in "
  651. "the outer class")
  652. self.assertTrue(hasattr(cv, "utils_nested_ExportClassName_Params"),
  653. msg="Inner class with export alias is not registered in "
  654. "global module")
  655. params = cv.utils.nested.ExportClassName.Params()
  656. params.int_value = 45
  657. params.float_value = 4.5
  658. instance = cv.utils.nested.ExportClassName.create(params)
  659. self.assertTrue(isinstance(instance, cv.utils.nested.ExportClassName),
  660. msg="Factory function returns wrong class instance: {}".format(type(instance)))
  661. self.assertEqual(
  662. params.int_value, instance.getIntParam(),
  663. msg="Class initialized with wrong integer parameter. Expected: {}. Actual: {}".format(
  664. params.int_value, instance.getIntParam()
  665. )
  666. )
  667. self.assertEqual(
  668. params.float_value, instance.getFloatParam(),
  669. msg="Class initialized with wrong integer parameter. Expected: {}. Actual: {}".format(
  670. params.float_value, instance.getFloatParam()
  671. )
  672. )
  673. def test_named_arguments_without_parameters(self):
  674. src = np.ones((5, 5, 3), dtype=np.uint8)
  675. arguments_dump, src_copy = cv.utils.copyMatAndDumpNamedArguments(src)
  676. np.testing.assert_equal(src, src_copy)
  677. self.assertEqual(arguments_dump, 'lambda=-1, sigma=0.0')
  678. def test_named_arguments_without_output_argument(self):
  679. src = np.zeros((2, 2, 3), dtype=np.uint8)
  680. arguments_dump, src_copy = cv.utils.copyMatAndDumpNamedArguments(
  681. src, lambda_=15, sigma=3.5
  682. )
  683. np.testing.assert_equal(src, src_copy)
  684. self.assertEqual(arguments_dump, 'lambda=15, sigma=3.5')
  685. def test_named_arguments_with_output_argument(self):
  686. src = np.zeros((3, 3, 3), dtype=np.uint8)
  687. dst = np.ones_like(src)
  688. arguments_dump, src_copy = cv.utils.copyMatAndDumpNamedArguments(
  689. src, dst, lambda_=25, sigma=5.5
  690. )
  691. np.testing.assert_equal(src, src_copy)
  692. np.testing.assert_equal(dst, src_copy)
  693. self.assertEqual(arguments_dump, 'lambda=25, sigma=5.5')
  694. class CanUsePurePythonModuleFunction(NewOpenCVTests):
  695. def test_can_get_ocv_version(self):
  696. import sys
  697. if sys.version_info[0] < 3:
  698. raise unittest.SkipTest('Python 2.x is not supported')
  699. self.assertEqual(cv.misc.get_ocv_version(), cv.__version__,
  700. "Can't get package version using Python misc module")
  701. def test_native_method_can_be_patched(self):
  702. import sys
  703. if sys.version_info[0] < 3:
  704. raise unittest.SkipTest('Python 2.x is not supported')
  705. res = cv.utils.testOverwriteNativeMethod(10)
  706. self.assertTrue(isinstance(res, Sequence),
  707. msg="Overwritten method should return sequence. "
  708. "Got: {} of type {}".format(res, type(res)))
  709. self.assertSequenceEqual(res, (11, 10),
  710. msg="Failed to overwrite native method")
  711. res = cv.utils._native.testOverwriteNativeMethod(123)
  712. self.assertEqual(res, 123, msg="Failed to call native method implementation")
  713. def test_default_matx_argument(self):
  714. res = cv.utils.dumpVec2i()
  715. self.assertEqual(res, "Vec2i(42, 24)",
  716. msg="Default argument is not properly handled")
  717. res = cv.utils.dumpVec2i((12, 21))
  718. self.assertEqual(res, "Vec2i(12, 21)")
  719. class SamplesFindFile(NewOpenCVTests):
  720. def test_ExistedFile(self):
  721. res = cv.samples.findFile('lena.jpg', False)
  722. self.assertNotEqual(res, '')
  723. def test_MissingFile(self):
  724. res = cv.samples.findFile('non_existed.file', False)
  725. self.assertEqual(res, '')
  726. def test_MissingFileException(self):
  727. try:
  728. _res = cv.samples.findFile('non_existed.file', True)
  729. self.assertEqual("Dead code", 0)
  730. except cv.error as _e:
  731. pass
  732. if __name__ == '__main__':
  733. NewOpenCVTests.bootstrap()