Merge pull request #9548 from alalek:python_tests

pull/9551/head
Maksim Shabunin 8 years ago
commit 791a11f949
  1. 1
      CMakeLists.txt
  2. 198
      modules/python/test/test.py
  3. 10
      modules/python/test/test_calibration.py
  4. 8
      modules/python/test/test_camshift.py
  5. 6
      modules/python/test/test_dft.py
  6. 10
      modules/python/test/test_digits.py
  7. 8
      modules/python/test/test_facedetect.py
  8. 8
      modules/python/test/test_feature_homography.py
  9. 6
      modules/python/test/test_fitline.py
  10. 10
      modules/python/test/test_gaussian_mix.py
  11. 18
      modules/python/test/test_goodfeatures.py
  12. 6
      modules/python/test/test_grabcut.py
  13. 7
      modules/python/test/test_houghcircles.py
  14. 6
      modules/python/test/test_houghlines.py
  15. 10
      modules/python/test/test_kmeans.py
  16. 89
      modules/python/test/test_legacy.py
  17. 22
      modules/python/test/test_letter_recog.py
  18. 16
      modules/python/test/test_lk_homography.py
  19. 10
      modules/python/test/test_lk_track.py
  20. 22
      modules/python/test/test_misc.py
  21. 5
      modules/python/test/test_morphology.py
  22. 5
      modules/python/test/test_mser.py
  23. 7
      modules/python/test/test_peopledetect.py
  24. 7
      modules/python/test/test_shape.py
  25. 11
      modules/python/test/test_squares.py
  26. 5
      modules/python/test/test_stitching.py
  27. 3
      modules/python/test/test_texture_flow.py
  28. 86
      modules/python/test/test_umat.py
  29. 5
      modules/python/test/test_watershed.py
  30. 29
      modules/python/test/tests_common.py

@ -853,6 +853,7 @@ if(ANDROID OR NOT UNIX)
endif()
if(COMMAND ocv_pylint_finalize)
ocv_pylint_add_directory(${CMAKE_CURRENT_LIST_DIR}/modules/python/test)
ocv_pylint_add_directory(${CMAKE_CURRENT_LIST_DIR}/samples/python)
ocv_pylint_add_directory(${CMAKE_CURRENT_LIST_DIR}/samples/dnn)
ocv_pylint_add_directory_recurse(${CMAKE_CURRENT_LIST_DIR}/samples/python/tutorial_code)

@ -1,21 +1,9 @@
#!/usr/bin/env python
from __future__ import print_function
import unittest
import random
import time
import math
import sys
import array
import tarfile
import hashlib
import os
import getopt
import operator
import functools
import numpy as np
import cv2
import argparse
import unittest
# Python 3 moved urlopen to urllib.requests
try:
@ -25,7 +13,6 @@ except ImportError:
from tests_common import NewOpenCVTests
# Tests to run first; check the handful of basic operations that the later tests rely on
basedir = os.path.abspath(os.path.dirname(__file__))
@ -33,184 +20,5 @@ def load_tests(loader, tests, pattern):
tests.addTests(loader.discover(basedir, pattern='test_*.py'))
return tests
class Hackathon244Tests(NewOpenCVTests):
def test_int_array(self):
a = np.array([-1, 2, -3, 4, -5])
absa0 = np.abs(a)
self.assertTrue(cv2.norm(a, cv2.NORM_L1) == 15)
absa1 = cv2.absdiff(a, 0)
self.assertEqual(cv2.norm(absa1, absa0, cv2.NORM_INF), 0)
def test_imencode(self):
a = np.zeros((480, 640), dtype=np.uint8)
flag, ajpg = cv2.imencode("img_q90.jpg", a, [cv2.IMWRITE_JPEG_QUALITY, 90])
self.assertEqual(flag, True)
self.assertEqual(ajpg.dtype, np.uint8)
self.assertGreater(ajpg.shape[0], 1)
self.assertEqual(ajpg.shape[1], 1)
def test_projectPoints(self):
objpt = np.float64([[1,2,3]])
imgpt0, jac0 = cv2.projectPoints(objpt, np.zeros(3), np.zeros(3), np.eye(3), np.float64([]))
imgpt1, jac1 = cv2.projectPoints(objpt, np.zeros(3), np.zeros(3), np.eye(3), None)
self.assertEqual(imgpt0.shape, (objpt.shape[0], 1, 2))
self.assertEqual(imgpt1.shape, imgpt0.shape)
self.assertEqual(jac0.shape, jac1.shape)
self.assertEqual(jac0.shape[0], 2*objpt.shape[0])
def test_estimateAffine3D(self):
pattern_size = (11, 8)
pattern_points = np.zeros((np.prod(pattern_size), 3), np.float32)
pattern_points[:,:2] = np.indices(pattern_size).T.reshape(-1, 2)
pattern_points *= 10
(retval, out, inliers) = cv2.estimateAffine3D(pattern_points, pattern_points)
self.assertEqual(retval, 1)
if cv2.norm(out[2,:]) < 1e-3:
out[2,2]=1
self.assertLess(cv2.norm(out, np.float64([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])), 1e-3)
self.assertEqual(cv2.countNonZero(inliers), pattern_size[0]*pattern_size[1])
def test_fast(self):
fd = cv2.FastFeatureDetector_create(30, True)
img = self.get_sample("samples/data/right02.jpg", 0)
img = cv2.medianBlur(img, 3)
imgc = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
keypoints = fd.detect(img)
self.assertTrue(600 <= len(keypoints) <= 700)
for kpt in keypoints:
self.assertNotEqual(kpt.response, 0)
def check_close_angles(self, a, b, angle_delta):
self.assertTrue(abs(a - b) <= angle_delta or
abs(360 - abs(a - b)) <= angle_delta)
def check_close_pairs(self, a, b, delta):
self.assertLessEqual(abs(a[0] - b[0]), delta)
self.assertLessEqual(abs(a[1] - b[1]), delta)
def check_close_boxes(self, a, b, delta, angle_delta):
self.check_close_pairs(a[0], b[0], delta)
self.check_close_pairs(a[1], b[1], delta)
self.check_close_angles(a[2], b[2], angle_delta)
def test_geometry(self):
npt = 100
np.random.seed(244)
a = np.random.randn(npt,2).astype('float32')*50 + 150
img = np.zeros((300, 300, 3), dtype='uint8')
be = cv2.fitEllipse(a)
br = cv2.minAreaRect(a)
mc, mr = cv2.minEnclosingCircle(a)
be0 = ((150.2511749267578, 150.77322387695312), (158.024658203125, 197.57696533203125), 37.57804489135742)
br0 = ((161.2974090576172, 154.41793823242188), (199.2301483154297, 207.7177734375), -9.164555549621582)
mc0, mr0 = (160.41790771484375, 144.55152893066406), 136.713500977
self.check_close_boxes(be, be0, 5, 15)
self.check_close_boxes(br, br0, 5, 15)
self.check_close_pairs(mc, mc0, 5)
self.assertLessEqual(abs(mr - mr0), 5)
def test_inheritance(self):
bm = cv2.StereoBM_create()
bm.getPreFilterCap() # from StereoBM
bm.getBlockSize() # from SteroMatcher
boost = cv2.ml.Boost_create()
boost.getBoostType() # from ml::Boost
boost.getMaxDepth() # from ml::DTrees
boost.isClassifier() # from ml::StatModel
def test_umat_construct(self):
data = np.random.random([512, 512])
# UMat constructors
data_um = cv2.UMat(data) # from ndarray
data_sub_um = cv2.UMat(data_um, [128, 256], [128, 256]) # from UMat
data_dst_um = cv2.UMat(128, 128, cv2.CV_64F) # from size/type
# test continuous and submatrix flags
assert data_um.isContinuous() and not data_um.isSubmatrix()
assert not data_sub_um.isContinuous() and data_sub_um.isSubmatrix()
# test operation on submatrix
cv2.multiply(data_sub_um, 2., dst=data_dst_um)
assert np.allclose(2. * data[128:256, 128:256], data_dst_um.get())
def test_umat_handle(self):
a_um = cv2.UMat(256, 256, cv2.CV_32F)
ctx_handle = cv2.UMat.context() # obtain context handle
queue_handle = cv2.UMat.queue() # obtain queue handle
a_handle = a_um.handle(cv2.ACCESS_READ) # obtain buffer handle
offset = a_um.offset # obtain buffer offset
def test_umat_matching(self):
img1 = self.get_sample("samples/data/right01.jpg")
img2 = self.get_sample("samples/data/right02.jpg")
orb = cv2.ORB_create()
img1, img2 = cv2.UMat(img1), cv2.UMat(img2)
ps1, descs_umat1 = orb.detectAndCompute(img1, None)
ps2, descs_umat2 = orb.detectAndCompute(img2, None)
self.assertIsInstance(descs_umat1, cv2.UMat)
self.assertIsInstance(descs_umat2, cv2.UMat)
self.assertGreater(len(ps1), 0)
self.assertGreater(len(ps2), 0)
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
res_umats = bf.match(descs_umat1, descs_umat2)
res = bf.match(descs_umat1.get(), descs_umat2.get())
self.assertGreater(len(res), 0)
self.assertEqual(len(res_umats), len(res))
def test_umat_optical_flow(self):
img1 = self.get_sample("samples/data/right01.jpg", cv2.IMREAD_GRAYSCALE)
img2 = self.get_sample("samples/data/right02.jpg", cv2.IMREAD_GRAYSCALE)
# Note, that if you want to see performance boost by OCL implementation - you need enough data
# For example you can increase maxCorners param to 10000 and increase img1 and img2 in such way:
# img = np.hstack([np.vstack([img] * 6)] * 6)
feature_params = dict(maxCorners=239,
qualityLevel=0.3,
minDistance=7,
blockSize=7)
p0 = cv2.goodFeaturesToTrack(img1, mask=None, **feature_params)
p0_umat = cv2.goodFeaturesToTrack(cv2.UMat(img1), mask=None, **feature_params)
self.assertEqual(p0_umat.get().shape, p0.shape)
p0 = np.array(sorted(p0, key=lambda p: tuple(p[0])))
p0_umat = cv2.UMat(np.array(sorted(p0_umat.get(), key=lambda p: tuple(p[0]))))
self.assertTrue(np.allclose(p0_umat.get(), p0))
p1_mask_err = cv2.calcOpticalFlowPyrLK(img1, img2, p0, None)
p1_mask_err_umat0 = map(cv2.UMat.get, cv2.calcOpticalFlowPyrLK(img1, img2, p0_umat, None))
p1_mask_err_umat1 = map(cv2.UMat.get, cv2.calcOpticalFlowPyrLK(cv2.UMat(img1), img2, p0_umat, None))
p1_mask_err_umat2 = map(cv2.UMat.get, cv2.calcOpticalFlowPyrLK(img1, cv2.UMat(img2), p0_umat, None))
# # results of OCL optical flow differs from CPU implementation, so result can not be easily compared
# for p1_mask_err_umat in [p1_mask_err_umat0, p1_mask_err_umat1, p1_mask_err_umat2]:
# for data, data_umat in zip(p1_mask_err, p1_mask_err_umat):
# self.assertTrue(np.allclose(data, data_umat))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='run OpenCV python tests')
parser.add_argument('--repo', help='use sample image files from local git repository (path to folder), '
'if not set, samples will be downloaded from github.com')
parser.add_argument('--data', help='<not used> use data files from local folder (path to folder), '
'if not set, data files will be downloaded from docs.opencv.org')
args, other = parser.parse_known_args()
print("Testing OpenCV", cv2.__version__)
print("Local repo path:", args.repo)
NewOpenCVTests.repoPath = args.repo
try:
NewOpenCVTests.extraTestDataPath = os.environ['OPENCV_TEST_DATA_PATH']
except KeyError:
print('Missing opencv extra repository. Some of tests may fail.')
random.seed(0)
unit_argv = [sys.argv[0]] + other;
unittest.main(argv=unit_argv)
NewOpenCVTests.bootstrap()

@ -16,8 +16,6 @@ from tests_common import NewOpenCVTests
class calibration_test(NewOpenCVTests):
def test_calibration(self):
from glob import glob
img_names = []
for i in range(1, 15):
if i < 10:
@ -34,7 +32,6 @@ class calibration_test(NewOpenCVTests):
obj_points = []
img_points = []
h, w = 0, 0
img_names_undistort = []
for fn in img_names:
img = self.get_sample(fn, 0)
if img is None:
@ -53,7 +50,7 @@ class calibration_test(NewOpenCVTests):
obj_points.append(pattern_points)
# calculate camera distortion
rms, camera_matrix, dist_coefs, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, (w, h), None, None, flags = 0)
rms, camera_matrix, dist_coefs, _rvecs, _tvecs = cv2.calibrateCamera(obj_points, img_points, (w, h), None, None, flags = 0)
eps = 0.01
normCamEps = 10.0
@ -69,3 +66,8 @@ class calibration_test(NewOpenCVTests):
self.assertLess(abs(rms - 0.196334638034), eps)
self.assertLess(cv2.norm(camera_matrix - cameraMatrixTest, cv2.NORM_L1), normCamEps)
self.assertLess(cv2.norm(dist_coefs - distCoeffsTest, cv2.NORM_L1), normDistEps)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -73,7 +73,7 @@ class camshift_test(NewOpenCVTests):
prob = cv2.calcBackProject([hsv], [0], self.hist, [0, 180], 1)
prob &= mask
term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )
track_box, self.track_window = cv2.CamShift(prob, self.track_window, term_crit)
_track_box, self.track_window = cv2.CamShift(prob, self.track_window, term_crit)
trackingRect = np.array(self.track_window)
trackingRect[2] += trackingRect[0]
@ -89,4 +89,8 @@ class camshift_test(NewOpenCVTests):
def test_camshift(self):
self.prepareRender()
self.runTracker()
self.runTracker()
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -43,4 +43,8 @@ class dft_test(NewOpenCVTests):
img_backTest = cv2.normalize(img_backTest, 0.0, 1.0, cv2.NORM_MINMAX)
img_back = cv2.normalize(img_back, 0.0, 1.0, cv2.NORM_MINMAX)
self.assertLess(cv2.norm(img_back - img_backTest), eps)
self.assertLess(cv2.norm(img_back - img_backTest), eps)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -71,7 +71,7 @@ class KNearest(StatModel):
self.model.train(samples, cv2.ml.ROW_SAMPLE, responses)
def predict(self, samples):
retval, results, neigh_resp, dists = self.model.findNearest(samples, self.k)
_retval, results, _neigh_resp, _dists = self.model.findNearest(samples, self.k)
return results.ravel()
class SVM(StatModel):
@ -147,7 +147,7 @@ class digits_test(NewOpenCVTests):
samples = preprocess_hog(digits2)
train_n = int(0.9*len(samples))
digits_train, digits_test = np.split(digits2, [train_n])
_digits_train, digits_test = np.split(digits2, [train_n])
samples_train, samples_test = np.split(samples, [train_n])
labels_train, labels_test = np.split(labels, [train_n])
errors = list()
@ -194,4 +194,8 @@ class digits_test(NewOpenCVTests):
self.assertLess(cv2.norm(confusionMatrixes[1] - confusionSVM, cv2.NORM_L1), normEps)
self.assertLess(errors[0] - 0.034, eps)
self.assertLess(errors[1] - 0.018, eps)
self.assertLess(errors[1] - 0.018, eps)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -23,8 +23,6 @@ from tests_common import NewOpenCVTests, intersectionRate
class facedetect_test(NewOpenCVTests):
def test_facedetect(self):
import sys, getopt
cascade_fn = self.repoPath + '/data/haarcascades/haarcascade_frontalface_alt.xml'
nested_fn = self.repoPath + '/data/haarcascades/haarcascade_eye.xml'
@ -87,4 +85,8 @@ class facedetect_test(NewOpenCVTests):
eyes_matches += 1
self.assertEqual(faces_matches, 2)
self.assertEqual(eyes_matches, 2)
self.assertEqual(eyes_matches, 2)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -28,7 +28,7 @@ def intersectionRate(s1, s2):
x1, y1, x2, y2 = s1
s1 = np.array([[x1, y1], [x2,y1], [x2, y2], [x1, y2]])
area, intersection = cv2.intersectConvexConvex(s1, np.array(s2))
area, _intersection = cv2.intersectConvexConvex(s1, np.array(s2))
return 2 * area / (cv2.contourArea(s1) + cv2.contourArea(np.array(s2)))
from tests_common import NewOpenCVTests
@ -157,4 +157,8 @@ class PlaneTracker:
keypoints, descrs = self.detector.detectAndCompute(frame, None)
if descrs is None: # detectAndCompute returns descs=None if no keypoints found
descrs = []
return keypoints, descrs
return keypoints, descrs
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -63,4 +63,8 @@ class fitline_test(NewOpenCVTests):
refVec = (np.float32(p1) - p0) / cv2.norm(np.float32(p1) - p0)
for i in range(len(lines)):
self.assertLessEqual(cv2.norm(refVec - lines[i][0:2], cv2.NORM_L2), eps)
self.assertLessEqual(cv2.norm(refVec - lines[i][0:2], cv2.NORM_L2), eps)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -15,7 +15,7 @@ import cv2
def make_gaussians(cluster_n, img_size):
points = []
ref_distrs = []
for i in xrange(cluster_n):
for _ in xrange(cluster_n):
mean = (0.1 + 0.8*random.rand(2)) * img_size
a = (random.rand(2, 2)-0.5)*img_size*0.1
cov = np.dot(a.T, a) + img_size*0.05*np.eye(2)
@ -44,7 +44,7 @@ class gaussian_mix_test(NewOpenCVTests):
em.trainEM(points)
means = em.getMeans()
covs = em.getCovs() # Known bug: https://github.com/opencv/opencv/pull/4232
found_distrs = zip(means, covs)
#found_distrs = zip(means, covs)
matches_count = 0
@ -57,4 +57,8 @@ class gaussian_mix_test(NewOpenCVTests):
cv2.norm(covs[i] - ref_distrs[j][1], cv2.NORM_L2) / cv2.norm(ref_distrs[j][1], cv2.NORM_L2) < covEps):
matches_count += 1
self.assertEqual(matches_count, cluster_n)
self.assertEqual(matches_count, cluster_n)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -27,10 +27,14 @@ class TestGoodFeaturesToTrack_test(NewOpenCVTests):
self.assertTrue(cv2.norm(results[t][i][0] - results2[t][i][0]) == 0)
for t0,t1 in zip(threshes, threshes[1:]):
r0 = results[t0]
r1 = results[t1]
# Increasing thresh should make result list shorter
self.assertTrue(len(r0) > len(r1))
# Increasing thresh should monly truncate result list
for i in range(len(r1)):
self.assertTrue(cv2.norm(r1[i][0] - r0[i][0])==0)
r0 = results[t0]
r1 = results[t1]
# Increasing thresh should make result list shorter
self.assertTrue(len(r0) > len(r1))
# Increasing thresh should monly truncate result list
for i in range(len(r1)):
self.assertTrue(cv2.norm(r1[i][0] - r0[i][0])==0)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -64,4 +64,8 @@ class grabcut_test(NewOpenCVTests):
exp_mask2 = self.scaleMask(mask)
cv2.imwrite(self.extraTestDataPath + '/cv/grabcut/exp_mask2py.png', exp_mask2)
self.assertEqual(self.verify(self.scaleMask(mask), exp_mask2), True)
self.assertEqual(self.verify(self.scaleMask(mask), exp_mask2), True)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -17,7 +17,6 @@ from tests_common import NewOpenCVTests
def circleApproximation(circle):
nPoints = 30
phi = 0
dPhi = 2*pi / nPoints
contour = []
for i in range(nPoints):
@ -78,4 +77,8 @@ class houghcircles_test(NewOpenCVTests):
matches_counter += 1
self.assertGreater(float(matches_counter) / len(testCircles), .5)
self.assertLess(float(len(circles) - matches_counter) / len(circles), .75)
self.assertLess(float(len(circles) - matches_counter) / len(circles), .75)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -62,4 +62,8 @@ class houghlines_test(NewOpenCVTests):
if linesDiff(testLines[i], lines[j]) < eps:
matches_counter += 1
self.assertGreater(float(matches_counter) / len(testLines), .7)
self.assertGreater(float(matches_counter) / len(testLines), .7)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -21,7 +21,7 @@ def make_gaussians(cluster_n, img_size):
points = []
ref_distrs = []
sizes = []
for i in xrange(cluster_n):
for _ in xrange(cluster_n):
mean = (0.1 + 0.8*random.rand(2)) * img_size
a = (random.rand(2, 2)-0.5)*img_size*0.1
cov = np.dot(a.T, a) + img_size*0.05*np.eye(2)
@ -59,7 +59,7 @@ class kmeans_test(NewOpenCVTests):
points, _, clusterSizes = make_gaussians(cluster_n, img_size)
term_crit = (cv2.TERM_CRITERIA_EPS, 30, 0.1)
ret, labels, centers = cv2.kmeans(points, cluster_n, None, term_crit, 10, 0)
_ret, labels, centers = cv2.kmeans(points, cluster_n, None, term_crit, 10, 0)
self.assertEqual(len(centers), cluster_n)
@ -67,4 +67,8 @@ class kmeans_test(NewOpenCVTests):
for i in range(cluster_n):
confidence = getMainLabelConfidence(labels[offset : (offset + clusterSizes[i])], cluster_n)
offset += clusterSizes[i]
self.assertGreater(confidence, 0.9)
self.assertGreater(confidence, 0.9)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -0,0 +1,89 @@
#!/usr/bin/env python
from __future__ import print_function
import numpy as np
import cv2
from tests_common import NewOpenCVTests
class Hackathon244Tests(NewOpenCVTests):
def test_int_array(self):
a = np.array([-1, 2, -3, 4, -5])
absa0 = np.abs(a)
self.assertTrue(cv2.norm(a, cv2.NORM_L1) == 15)
absa1 = cv2.absdiff(a, 0)
self.assertEqual(cv2.norm(absa1, absa0, cv2.NORM_INF), 0)
def test_imencode(self):
a = np.zeros((480, 640), dtype=np.uint8)
flag, ajpg = cv2.imencode("img_q90.jpg", a, [cv2.IMWRITE_JPEG_QUALITY, 90])
self.assertEqual(flag, True)
self.assertEqual(ajpg.dtype, np.uint8)
self.assertGreater(ajpg.shape[0], 1)
self.assertEqual(ajpg.shape[1], 1)
def test_projectPoints(self):
objpt = np.float64([[1,2,3]])
imgpt0, jac0 = cv2.projectPoints(objpt, np.zeros(3), np.zeros(3), np.eye(3), np.float64([]))
imgpt1, jac1 = cv2.projectPoints(objpt, np.zeros(3), np.zeros(3), np.eye(3), None)
self.assertEqual(imgpt0.shape, (objpt.shape[0], 1, 2))
self.assertEqual(imgpt1.shape, imgpt0.shape)
self.assertEqual(jac0.shape, jac1.shape)
self.assertEqual(jac0.shape[0], 2*objpt.shape[0])
def test_estimateAffine3D(self):
pattern_size = (11, 8)
pattern_points = np.zeros((np.prod(pattern_size), 3), np.float32)
pattern_points[:,:2] = np.indices(pattern_size).T.reshape(-1, 2)
pattern_points *= 10
(retval, out, inliers) = cv2.estimateAffine3D(pattern_points, pattern_points)
self.assertEqual(retval, 1)
if cv2.norm(out[2,:]) < 1e-3:
out[2,2]=1
self.assertLess(cv2.norm(out, np.float64([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])), 1e-3)
self.assertEqual(cv2.countNonZero(inliers), pattern_size[0]*pattern_size[1])
def test_fast(self):
fd = cv2.FastFeatureDetector_create(30, True)
img = self.get_sample("samples/data/right02.jpg", 0)
img = cv2.medianBlur(img, 3)
keypoints = fd.detect(img)
self.assertTrue(600 <= len(keypoints) <= 700)
for kpt in keypoints:
self.assertNotEqual(kpt.response, 0)
def check_close_angles(self, a, b, angle_delta):
self.assertTrue(abs(a - b) <= angle_delta or
abs(360 - abs(a - b)) <= angle_delta)
def check_close_pairs(self, a, b, delta):
self.assertLessEqual(abs(a[0] - b[0]), delta)
self.assertLessEqual(abs(a[1] - b[1]), delta)
def check_close_boxes(self, a, b, delta, angle_delta):
self.check_close_pairs(a[0], b[0], delta)
self.check_close_pairs(a[1], b[1], delta)
self.check_close_angles(a[2], b[2], angle_delta)
def test_geometry(self):
npt = 100
np.random.seed(244)
a = np.random.randn(npt,2).astype('float32')*50 + 150
be = cv2.fitEllipse(a)
br = cv2.minAreaRect(a)
mc, mr = cv2.minEnclosingCircle(a)
be0 = ((150.2511749267578, 150.77322387695312), (158.024658203125, 197.57696533203125), 37.57804489135742)
br0 = ((161.2974090576172, 154.41793823242188), (199.2301483154297, 207.7177734375), -9.164555549621582)
mc0, mr0 = (160.41790771484375, 144.55152893066406), 136.713500977
self.check_close_boxes(be, be0, 5, 15)
self.check_close_boxes(br, br0, 5, 15)
self.check_close_pairs(mc, mc0, 5)
self.assertLessEqual(abs(mr - mr0), 5)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -59,12 +59,12 @@ class RTrees(LetterStatModel):
self.model = cv2.ml.RTrees_create()
def train(self, samples, responses):
sample_n, var_n = samples.shape
#sample_n, var_n = samples.shape
self.model.setMaxDepth(20)
self.model.train(samples, cv2.ml.ROW_SAMPLE, responses.astype(int))
def predict(self, samples):
ret, resp = self.model.predict(samples)
_ret, resp = self.model.predict(samples)
return resp.ravel()
@ -76,7 +76,7 @@ class KNearest(LetterStatModel):
self.model.train(samples, cv2.ml.ROW_SAMPLE, responses)
def predict(self, samples):
retval, results, neigh_resp, dists = self.model.findNearest(samples, k = 10)
_retval, results, _neigh_resp, _dists = self.model.findNearest(samples, k = 10)
return results.ravel()
@ -85,7 +85,7 @@ class Boost(LetterStatModel):
self.model = cv2.ml.Boost_create()
def train(self, samples, responses):
sample_n, var_n = samples.shape
_sample_n, var_n = samples.shape
new_samples = self.unroll_samples(samples)
new_responses = self.unroll_responses(responses)
var_types = np.array([cv2.ml.VAR_NUMERICAL] * var_n + [cv2.ml.VAR_CATEGORICAL, cv2.ml.VAR_CATEGORICAL], np.uint8)
@ -96,7 +96,7 @@ class Boost(LetterStatModel):
def predict(self, samples):
new_samples = self.unroll_samples(samples)
ret, resp = self.model.predict(new_samples)
_ret, resp = self.model.predict(new_samples)
return resp.ravel().reshape(-1, self.class_n).argmax(1)
@ -113,7 +113,7 @@ class SVM(LetterStatModel):
self.model.train(samples, cv2.ml.ROW_SAMPLE, responses.astype(int))
def predict(self, samples):
ret, resp = self.model.predict(samples)
_ret, resp = self.model.predict(samples)
return resp.ravel()
@ -122,7 +122,7 @@ class MLP(LetterStatModel):
self.model = cv2.ml.ANN_MLP_create()
def train(self, samples, responses):
sample_n, var_n = samples.shape
_sample_n, var_n = samples.shape
new_responses = self.unroll_responses(responses).reshape(-1, self.class_n)
layer_sizes = np.int32([var_n, 100, 100, self.class_n])
@ -136,7 +136,7 @@ class MLP(LetterStatModel):
self.model.train(samples, cv2.ml.ROW_SAMPLE, np.float32(new_responses))
def predict(self, samples):
ret, resp = self.model.predict(samples)
_ret, resp = self.model.predict(samples)
return resp.argmax(-1)
from tests_common import NewOpenCVTests
@ -164,4 +164,8 @@ class letter_recog_test(NewOpenCVTests):
test_rate = np.mean(classifier.predict(samples[train_n:]) == responses[train_n:].astype(int))
self.assertLess(train_rate - testErrors[Model][0], eps)
self.assertLess(test_rate - testErrors[Model][1], eps)
self.assertLess(test_rate - testErrors[Model][1], eps)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -27,8 +27,8 @@ feature_params = dict( maxCorners = 1000,
blockSize = 19 )
def checkedTrace(img0, img1, p0, back_threshold = 1.0):
p1, st, err = cv2.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params)
p0r, st, err = cv2.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params)
p1, _st, _err = cv2.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params)
p0r, _st, _err = cv2.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params)
d = abs(p0-p0r).reshape(-1, 2).max(-1)
status = d < back_threshold
return p1, status
@ -77,11 +77,11 @@ class lk_homography_test(NewOpenCVTests):
if len(self.p0) < 4:
self.p0 = None
continue
H, status = cv2.findHomography(self.p0, self.p1, cv2.RANSAC, 5.0)
_H, status = cv2.findHomography(self.p0, self.p1, cv2.RANSAC, 5.0)
goodPointsInRect = 0
goodPointsOutsideRect = 0
for (x0, y0), (x1, y1), good in zip(self.p0[:,0], self.p1[:,0], status[:,0]):
for (_x0, _y0), (x1, y1), good in zip(self.p0[:,0], self.p1[:,0], status[:,0]):
if good:
if isPointInRect((x1,y1), self.render.getCurrentRect()):
goodPointsInRect += 1
@ -91,6 +91,10 @@ class lk_homography_test(NewOpenCVTests):
isForegroundHomographyFound = True
self.assertGreater(float(goodPointsInRect) / (self.numFeaturesInRectOnStart + 1), 0.6)
else:
p = cv2.goodFeaturesToTrack(frame_gray, **feature_params)
self.p0 = cv2.goodFeaturesToTrack(frame_gray, **feature_params)
self.assertEqual(isForegroundHomographyFound, True)
self.assertEqual(isForegroundHomographyFound, True)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -63,8 +63,8 @@ class lk_track_test(NewOpenCVTests):
if len(self.tracks) > 0:
img0, img1 = self.prev_gray, frame_gray
p0 = np.float32([tr[-1][0] for tr in self.tracks]).reshape(-1, 1, 2)
p1, st, err = cv2.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params)
p0r, st, err = cv2.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params)
p1, _st, _err = cv2.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params)
p0r, _st, _err = cv2.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params)
d = abs(p0-p0r).reshape(-1, 2).max(-1)
good = d < 1
new_tracks = []
@ -108,4 +108,8 @@ class lk_track_test(NewOpenCVTests):
self.prev_gray = frame_gray
if self.frame_idx > 300:
break
break
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -0,0 +1,22 @@
#!/usr/bin/env python
from __future__ import print_function
import numpy as np
import cv2
from tests_common import NewOpenCVTests
class Bindings(NewOpenCVTests):
def test_inheritance(self):
bm = cv2.StereoBM_create()
bm.getPreFilterCap() # from StereoBM
bm.getBlockSize() # from SteroMatcher
boost = cv2.ml.Boost_create()
boost.getBoostType() # from ml::Boost
boost.getMaxDepth() # from ml::DTrees
boost.isClassifier() # from ml::StatModel
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -48,4 +48,7 @@ class morphology_test(NewOpenCVTests):
for mode in modes:
res = update(mode)
self.assertEqual(self.hashimg(res), referenceHashes[mode])
self.assertEqual(self.hashimg(res), referenceHashes[mode])
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -37,7 +37,7 @@ class mser_test(NewOpenCVTests):
mserExtractor.setDelta(kDelta)
np.random.seed(10)
for i in range(100):
for _i in range(100):
use_big_image = int(np.random.rand(1,1)*7) != 0
invert = int(np.random.rand(1,1)*2) != 0
@ -67,3 +67,6 @@ class mser_test(NewOpenCVTests):
self.assertEqual(nmsers, len(boxes))
self.assertLessEqual(minRegs, nmsers)
self.assertGreaterEqual(maxRegs, nmsers)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -38,7 +38,7 @@ class peopledetect_test(NewOpenCVTests):
img = self.get_sample(dirPath + sample, 0)
found, w = hog.detectMultiScale(img, winStride=(8,8), padding=(32,32), scale=1.05)
found, _w = hog.detectMultiScale(img, winStride=(8,8), padding=(32,32), scale=1.05)
found_filtered = []
for ri, r in enumerate(found):
for qi, q in enumerate(found):
@ -59,4 +59,7 @@ class peopledetect_test(NewOpenCVTests):
if intersectionRate(found_rect, testPeople[j][0]) > eps or intersectionRate(found_rect, testPeople[j][1]) > eps:
matches += 1
self.assertGreater(matches, 0)
self.assertGreater(matches, 0)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -7,8 +7,8 @@ class shape_test(NewOpenCVTests):
def test_computeDistance(self):
a = self.get_sample('samples/data/shape_sample/1.png', cv2.IMREAD_GRAYSCALE);
b = self.get_sample('samples/data/shape_sample/2.png', cv2.IMREAD_GRAYSCALE);
a = self.get_sample('samples/data/shape_sample/1.png', cv2.IMREAD_GRAYSCALE)
b = self.get_sample('samples/data/shape_sample/2.png', cv2.IMREAD_GRAYSCALE)
_, ca, _ = cv2.findContours(a, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_KCOS)
_, cb, _ = cv2.findContours(b, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_TC89_KCOS)
@ -21,3 +21,6 @@ class shape_test(NewOpenCVTests):
self.assertAlmostEqual(d1, 26.4196891785, 3, "HausdorffDistanceExtractor")
self.assertAlmostEqual(d2, 0.25804194808, 3, "ShapeContextDistanceExtractor")
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -30,8 +30,8 @@ def find_squares(img):
bin = cv2.Canny(gray, 0, 50, apertureSize=5)
bin = cv2.dilate(bin, None)
else:
retval, bin = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY)
bin, contours, hierarchy = cv2.findContours(bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
_retval, bin = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY)
bin, contours, _hierarchy = cv2.findContours(bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
cnt_len = cv2.arcLength(cnt, True)
cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True)
@ -44,7 +44,7 @@ def find_squares(img):
return squares
def intersectionRate(s1, s2):
area, intersection = cv2.intersectConvexConvex(np.array(s1), np.array(s2))
area, _intersection = cv2.intersectConvexConvex(np.array(s1), np.array(s2))
return 2 * area / (cv2.contourArea(np.array(s1)) + cv2.contourArea(np.array(s2)))
def filterSquares(squares, square):
@ -93,4 +93,7 @@ class squares_test(NewOpenCVTests):
matches_counter += 1
self.assertGreater(matches_counter / len(testSquares), 0.9)
self.assertLess( (len(squares) - matches_counter) / len(squares), 0.2)
self.assertLess( (len(squares) - matches_counter) / len(squares), 0.2)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -11,10 +11,13 @@ class stitching_test(NewOpenCVTests):
img2 = self.get_sample('stitching/a2.png')
stitcher = cv2.createStitcher(False)
(result, pano) = stitcher.stitch((img1, img2))
(_result, pano) = stitcher.stitch((img1, img2))
#cv2.imshow("pano", pano)
#cv2.waitKey()
self.assertAlmostEqual(pano.shape[0], 685, delta=100, msg="rows: %r" % list(pano.shape))
self.assertAlmostEqual(pano.shape[1], 1025, delta=100, msg="cols: %r" % list(pano.shape))
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -42,3 +42,6 @@ class texture_flow_test(NewOpenCVTests):
for i in range(len(textureVectors)):
self.assertTrue(cv2.norm(textureVectors[i], cv2.NORM_L2) < eps
or abs(cv2.norm(textureVectors[i], cv2.NORM_L2) - d) < eps)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -0,0 +1,86 @@
#!/usr/bin/env python
from __future__ import print_function
import numpy as np
import cv2
from tests_common import NewOpenCVTests
class UMat(NewOpenCVTests):
def test_umat_construct(self):
data = np.random.random([512, 512])
# UMat constructors
data_um = cv2.UMat(data) # from ndarray
data_sub_um = cv2.UMat(data_um, [128, 256], [128, 256]) # from UMat
data_dst_um = cv2.UMat(128, 128, cv2.CV_64F) # from size/type
# test continuous and submatrix flags
assert data_um.isContinuous() and not data_um.isSubmatrix()
assert not data_sub_um.isContinuous() and data_sub_um.isSubmatrix()
# test operation on submatrix
cv2.multiply(data_sub_um, 2., dst=data_dst_um)
assert np.allclose(2. * data[128:256, 128:256], data_dst_um.get())
def test_umat_handle(self):
a_um = cv2.UMat(256, 256, cv2.CV_32F)
_ctx_handle = cv2.UMat.context() # obtain context handle
_queue_handle = cv2.UMat.queue() # obtain queue handle
_a_handle = a_um.handle(cv2.ACCESS_READ) # obtain buffer handle
_offset = a_um.offset # obtain buffer offset
def test_umat_matching(self):
img1 = self.get_sample("samples/data/right01.jpg")
img2 = self.get_sample("samples/data/right02.jpg")
orb = cv2.ORB_create()
img1, img2 = cv2.UMat(img1), cv2.UMat(img2)
ps1, descs_umat1 = orb.detectAndCompute(img1, None)
ps2, descs_umat2 = orb.detectAndCompute(img2, None)
self.assertIsInstance(descs_umat1, cv2.UMat)
self.assertIsInstance(descs_umat2, cv2.UMat)
self.assertGreater(len(ps1), 0)
self.assertGreater(len(ps2), 0)
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
res_umats = bf.match(descs_umat1, descs_umat2)
res = bf.match(descs_umat1.get(), descs_umat2.get())
self.assertGreater(len(res), 0)
self.assertEqual(len(res_umats), len(res))
def test_umat_optical_flow(self):
img1 = self.get_sample("samples/data/right01.jpg", cv2.IMREAD_GRAYSCALE)
img2 = self.get_sample("samples/data/right02.jpg", cv2.IMREAD_GRAYSCALE)
# Note, that if you want to see performance boost by OCL implementation - you need enough data
# For example you can increase maxCorners param to 10000 and increase img1 and img2 in such way:
# img = np.hstack([np.vstack([img] * 6)] * 6)
feature_params = dict(maxCorners=239,
qualityLevel=0.3,
minDistance=7,
blockSize=7)
p0 = cv2.goodFeaturesToTrack(img1, mask=None, **feature_params)
p0_umat = cv2.goodFeaturesToTrack(cv2.UMat(img1), mask=None, **feature_params)
self.assertEqual(p0_umat.get().shape, p0.shape)
p0 = np.array(sorted(p0, key=lambda p: tuple(p[0])))
p0_umat = cv2.UMat(np.array(sorted(p0_umat.get(), key=lambda p: tuple(p[0]))))
self.assertTrue(np.allclose(p0_umat.get(), p0))
_p1_mask_err = cv2.calcOpticalFlowPyrLK(img1, img2, p0, None)
_p1_mask_err_umat0 = map(cv2.UMat.get, cv2.calcOpticalFlowPyrLK(img1, img2, p0_umat, None))
_p1_mask_err_umat1 = map(cv2.UMat.get, cv2.calcOpticalFlowPyrLK(cv2.UMat(img1), img2, p0_umat, None))
_p1_mask_err_umat2 = map(cv2.UMat.get, cv2.calcOpticalFlowPyrLK(img1, cv2.UMat(img2), p0_umat, None))
# # results of OCL optical flow differs from CPU implementation, so result can not be easily compared
# for p1_mask_err_umat in [p1_mask_err_umat0, p1_mask_err_umat1, p1_mask_err_umat2]:
# for data, data_umat in zip(p1_mask_err, p1_mask_err_umat):
# self.assertTrue(np.allclose(data, data_umat))
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -30,4 +30,7 @@ class watershed_test(NewOpenCVTests):
refSegments = segments.copy()
cv2.imwrite(self.extraTestDataPath + '/cv/watershed/wshed_segments.png', refSegments)
self.assertLess(cv2.norm(segments - refSegments, cv2.NORM_L1) / 255.0, 50)
self.assertLess(cv2.norm(segments - refSegments, cv2.NORM_L1) / 255.0, 50)
if __name__ == '__main__':
NewOpenCVTests.bootstrap()

@ -2,10 +2,13 @@
from __future__ import print_function
import unittest
import os
import sys
import unittest
import hashlib
import os
import random
import argparse
import numpy as np
import cv2
@ -62,6 +65,26 @@ class NewOpenCVTests(unittest.TestCase):
if not a > b:
self.fail('%s not greater than %s' % (repr(a), repr(b)))
@staticmethod
def bootstrap():
parser = argparse.ArgumentParser(description='run OpenCV python tests')
parser.add_argument('--repo', help='use sample image files from local git repository (path to folder), '
'if not set, samples will be downloaded from github.com')
parser.add_argument('--data', help='<not used> use data files from local folder (path to folder), '
'if not set, data files will be downloaded from docs.opencv.org')
args, other = parser.parse_known_args()
print("Testing OpenCV", cv2.__version__)
print("Local repo path:", args.repo)
NewOpenCVTests.repoPath = args.repo
try:
NewOpenCVTests.extraTestDataPath = os.environ['OPENCV_TEST_DATA_PATH']
except KeyError:
print('Missing opencv extra repository. Some of tests may fail.')
random.seed(0)
unit_argv = [sys.argv[0]] + other
unittest.main(argv=unit_argv)
def intersectionRate(s1, s2):
x1, y1, x2, y2 = s1
@ -70,7 +93,7 @@ def intersectionRate(s1, s2):
x1, y1, x2, y2 = s2
s2 = np.array([[x1, y1], [x2,y1], [x2, y2], [x1, y2]])
area, intersection = cv2.intersectConvexConvex(s1, s2)
area, _intersection = cv2.intersectConvexConvex(s1, s2)
return 2 * area / (cv2.contourArea(s1) + cv2.contourArea(s2))
def isPointInRect(p, rect):

Loading…
Cancel
Save