tests_common.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. import os
  4. import sys
  5. import unittest
  6. import hashlib
  7. import random
  8. import argparse
  9. import numpy as np
  10. #sys.OpenCV_LOADER_DEBUG = True
  11. import cv2 as cv
  12. # Python 3 moved urlopen to urllib.requests
  13. try:
  14. from urllib.request import urlopen
  15. except ImportError:
  16. from urllib import urlopen
  17. class NewOpenCVTests(unittest.TestCase):
  18. # path to local repository folder containing 'samples' folder
  19. repoPath = None
  20. extraTestDataPath = None
  21. # github repository url
  22. repoUrl = 'https://raw.github.com/opencv/opencv/4.x'
  23. def find_file(self, filename, searchPaths=[], required=True):
  24. searchPaths = searchPaths if searchPaths else [self.repoPath, self.extraTestDataPath]
  25. for path in searchPaths:
  26. if path is not None:
  27. candidate = path + '/' + filename
  28. if os.path.isfile(candidate):
  29. return candidate
  30. if required:
  31. self.fail('File ' + filename + ' not found')
  32. return None
  33. def get_sample(self, filename, iscolor = None):
  34. if iscolor is None:
  35. iscolor = cv.IMREAD_COLOR
  36. if not filename in self.image_cache:
  37. filepath = self.find_file(filename)
  38. with open(filepath, 'rb') as f:
  39. filedata = f.read()
  40. self.image_cache[filename] = cv.imdecode(np.fromstring(filedata, dtype=np.uint8), iscolor)
  41. return self.image_cache[filename]
  42. def setUp(self):
  43. cv.setRNGSeed(10)
  44. self.image_cache = {}
  45. def hashimg(self, im):
  46. """ Compute a hash for an image, useful for image comparisons """
  47. return hashlib.md5(im.tostring()).hexdigest()
  48. if sys.version_info[:2] == (2, 6):
  49. def assertLess(self, a, b, msg=None):
  50. if not a < b:
  51. self.fail('%s not less than %s' % (repr(a), repr(b)))
  52. def assertLessEqual(self, a, b, msg=None):
  53. if not a <= b:
  54. self.fail('%s not less than or equal to %s' % (repr(a), repr(b)))
  55. def assertGreater(self, a, b, msg=None):
  56. if not a > b:
  57. self.fail('%s not greater than %s' % (repr(a), repr(b)))
  58. @staticmethod
  59. def bootstrap():
  60. parser = argparse.ArgumentParser(description='run OpenCV python tests')
  61. parser.add_argument('--repo', help='use sample image files from local git repository (path to folder), '
  62. 'if not set, samples will be downloaded from github.com')
  63. parser.add_argument('--data', help='<not used> use data files from local folder (path to folder), '
  64. 'if not set, data files will be downloaded from docs.opencv.org')
  65. args, other = parser.parse_known_args()
  66. print("Testing OpenCV", cv.__version__)
  67. print("Local repo path:", args.repo)
  68. NewOpenCVTests.repoPath = args.repo
  69. try:
  70. NewOpenCVTests.extraTestDataPath = os.environ['OPENCV_TEST_DATA_PATH']
  71. except KeyError:
  72. print('Missing opencv extra repository. Some of tests may fail.')
  73. random.seed(0)
  74. unit_argv = [sys.argv[0]] + other
  75. unittest.main(argv=unit_argv)
  76. def intersectionRate(s1, s2):
  77. x1, y1, x2, y2 = s1
  78. s1 = np.array([[x1, y1], [x2,y1], [x2, y2], [x1, y2]])
  79. x1, y1, x2, y2 = s2
  80. s2 = np.array([[x1, y1], [x2,y1], [x2, y2], [x1, y2]])
  81. area, _intersection = cv.intersectConvexConvex(s1, s2)
  82. return 2 * area / (cv.contourArea(s1) + cv.contourArea(s2))
  83. def isPointInRect(p, rect):
  84. if rect[0] <= p[0] and rect[1] <=p[1] and p[0] <= rect[2] and p[1] <= rect[3]:
  85. return True
  86. else:
  87. return False