• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2
3from __future__ import print_function
4import unittest
5import random
6import time
7import math
8import sys
9import array
10import tarfile
11import hashlib
12import os
13import getopt
14import operator
15import functools
16import numpy as np
17import cv2
18import argparse
19
20# Python 3 moved urlopen to urllib.requests
21try:
22    from urllib.request import urlopen
23except ImportError:
24    from urllib import urlopen
25
26class NewOpenCVTests(unittest.TestCase):
27
28    # path to local repository folder containing 'samples' folder
29    repoPath = None
30    # github repository url
31    repoUrl = 'https://raw.github.com/Itseez/opencv/master'
32
33    def get_sample(self, filename, iscolor = cv2.IMREAD_COLOR):
34        if not filename in self.image_cache:
35            filedata = None
36            if NewOpenCVTests.repoPath is not None:
37                candidate = NewOpenCVTests.repoPath + '/' + filename
38                if os.path.isfile(candidate):
39                    with open(candidate, 'rb') as f:
40                        filedata = f.read()
41            if filedata is None:
42                filedata = urlopen(NewOpenCVTests.repoUrl + '/' + filename).read()
43            self.image_cache[filename] = cv2.imdecode(np.fromstring(filedata, dtype=np.uint8), iscolor)
44        return self.image_cache[filename]
45
46    def setUp(self):
47        self.image_cache = {}
48
49    def hashimg(self, im):
50        """ Compute a hash for an image, useful for image comparisons """
51        return hashlib.md5(im.tostring()).digest()
52
53    if sys.version_info[:2] == (2, 6):
54        def assertLess(self, a, b, msg=None):
55            if not a < b:
56                self.fail('%s not less than %s' % (repr(a), repr(b)))
57
58        def assertLessEqual(self, a, b, msg=None):
59            if not a <= b:
60                self.fail('%s not less than or equal to %s' % (repr(a), repr(b)))
61
62        def assertGreater(self, a, b, msg=None):
63            if not a > b:
64                self.fail('%s not greater than %s' % (repr(a), repr(b)))
65
66# Tests to run first; check the handful of basic operations that the later tests rely on
67
68class Hackathon244Tests(NewOpenCVTests):
69
70    def test_int_array(self):
71        a = np.array([-1, 2, -3, 4, -5])
72        absa0 = np.abs(a)
73        self.assertTrue(cv2.norm(a, cv2.NORM_L1) == 15)
74        absa1 = cv2.absdiff(a, 0)
75        self.assertEqual(cv2.norm(absa1, absa0, cv2.NORM_INF), 0)
76
77    def test_imencode(self):
78        a = np.zeros((480, 640), dtype=np.uint8)
79        flag, ajpg = cv2.imencode("img_q90.jpg", a, [cv2.IMWRITE_JPEG_QUALITY, 90])
80        self.assertEqual(flag, True)
81        self.assertEqual(ajpg.dtype, np.uint8)
82        self.assertGreater(ajpg.shape[0], 1)
83        self.assertEqual(ajpg.shape[1], 1)
84
85    def test_projectPoints(self):
86        objpt = np.float64([[1,2,3]])
87        imgpt0, jac0 = cv2.projectPoints(objpt, np.zeros(3), np.zeros(3), np.eye(3), np.float64([]))
88        imgpt1, jac1 = cv2.projectPoints(objpt, np.zeros(3), np.zeros(3), np.eye(3), None)
89        self.assertEqual(imgpt0.shape, (objpt.shape[0], 1, 2))
90        self.assertEqual(imgpt1.shape, imgpt0.shape)
91        self.assertEqual(jac0.shape, jac1.shape)
92        self.assertEqual(jac0.shape[0], 2*objpt.shape[0])
93
94    def test_estimateAffine3D(self):
95        pattern_size = (11, 8)
96        pattern_points = np.zeros((np.prod(pattern_size), 3), np.float32)
97        pattern_points[:,:2] = np.indices(pattern_size).T.reshape(-1, 2)
98        pattern_points *= 10
99        (retval, out, inliers) = cv2.estimateAffine3D(pattern_points, pattern_points)
100        self.assertEqual(retval, 1)
101        if cv2.norm(out[2,:]) < 1e-3:
102            out[2,2]=1
103        self.assertLess(cv2.norm(out, np.float64([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])), 1e-3)
104        self.assertEqual(cv2.countNonZero(inliers), pattern_size[0]*pattern_size[1])
105
106    def test_fast(self):
107        fd = cv2.FastFeatureDetector_create(30, True)
108        img = self.get_sample("samples/data/right02.jpg", 0)
109        img = cv2.medianBlur(img, 3)
110        imgc = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
111        keypoints = fd.detect(img)
112        self.assertTrue(600 <= len(keypoints) <= 700)
113        for kpt in keypoints:
114            self.assertNotEqual(kpt.response, 0)
115
116    def check_close_angles(self, a, b, angle_delta):
117        self.assertTrue(abs(a - b) <= angle_delta or
118                        abs(360 - abs(a - b)) <= angle_delta)
119
120    def check_close_pairs(self, a, b, delta):
121        self.assertLessEqual(abs(a[0] - b[0]), delta)
122        self.assertLessEqual(abs(a[1] - b[1]), delta)
123
124    def check_close_boxes(self, a, b, delta, angle_delta):
125        self.check_close_pairs(a[0], b[0], delta)
126        self.check_close_pairs(a[1], b[1], delta)
127        self.check_close_angles(a[2], b[2], angle_delta)
128
129    def test_geometry(self):
130        npt = 100
131        np.random.seed(244)
132        a = np.random.randn(npt,2).astype('float32')*50 + 150
133
134        img = np.zeros((300, 300, 3), dtype='uint8')
135        be = cv2.fitEllipse(a)
136        br = cv2.minAreaRect(a)
137        mc, mr = cv2.minEnclosingCircle(a)
138
139        be0 = ((150.2511749267578, 150.77322387695312), (158.024658203125, 197.57696533203125), 37.57804489135742)
140        br0 = ((161.2974090576172, 154.41793823242188), (199.2301483154297, 207.7177734375), -9.164555549621582)
141        mc0, mr0 = (160.41790771484375, 144.55152893066406), 136.713500977
142
143        self.check_close_boxes(be, be0, 5, 15)
144        self.check_close_boxes(br, br0, 5, 15)
145        self.check_close_pairs(mc, mc0, 5)
146        self.assertLessEqual(abs(mr - mr0), 5)
147
148    def test_inheritance(self):
149        bm = cv2.StereoBM_create()
150        bm.getPreFilterCap() # from StereoBM
151        bm.getBlockSize() # from SteroMatcher
152
153        boost = cv2.ml.Boost_create()
154        boost.getBoostType() # from ml::Boost
155        boost.getMaxDepth() # from ml::DTrees
156        boost.isClassifier() # from ml::StatModel
157
158if __name__ == '__main__':
159    parser = argparse.ArgumentParser(description='run OpenCV python tests')
160    parser.add_argument('--repo', help='use sample image files from local git repository (path to folder), '
161                                       'if not set, samples will be downloaded from github.com')
162    parser.add_argument('--data', help='<not used> use data files from local folder (path to folder), '
163                                        'if not set, data files will be downloaded from docs.opencv.org')
164    args, other = parser.parse_known_args()
165    print("Testing OpenCV", cv2.__version__)
166    print("Local repo path:", args.repo)
167    NewOpenCVTests.repoPath = args.repo
168    random.seed(0)
169    unit_argv = [sys.argv[0]] + other;
170    unittest.main(argv=unit_argv)
171