import hashlib
import os
import getopt
+import operator
+import functools
import cv
def setUp(self):
self.image_cache = {}
+ def snap(self, img):
+ self.snapL([img])
+
+ def snapL(self, L):
+ for i,img in enumerate(L):
+ cv.NamedWindow("snap-%d" % i, 1)
+ cv.ShowImage("snap-%d" % i, img)
+ cv.WaitKey()
+ cv.DestroyAllWindows()
+
+ def hashimg(self, im):
+ """ Compute a hash for an image, useful for image comparisons """
+ return hashlib.md5(im.tostring()).digest()
+
# Tests to run first; check the handful of basic operations that the later tests rely on
class PreliminaryTests(OpenCVTests):
vely = cv.CreateImage(vel_size, cv.IPL_DEPTH_32F, 1)
cv.CalcOpticalFlowBM(a, b, (8,8), (1,1), (8,8), 0, velx, vely)
+ def test_CartToPolar(self):
+ x = cv.CreateMat(5, 5, cv.CV_32F)
+ y = cv.CreateMat(5, 5, cv.CV_32F)
+ mag = cv.CreateMat(5, 5, cv.CV_32F)
+ angle = cv.CreateMat(5, 5, cv.CV_32F)
+ x2 = cv.CreateMat(5, 5, cv.CV_32F)
+ y2 = cv.CreateMat(5, 5, cv.CV_32F)
+
+ for i in range(5):
+ for j in range(5):
+ x[i, j] = i
+ y[i, j] = j
+
+ for in_degrees in [False, True]:
+ cv.CartToPolar(x, y, mag, angle, in_degrees)
+ cv.PolarToCart(mag, angle, x2, y2, in_degrees)
+ for i in range(5):
+ for j in range(5):
+ self.assertAlmostEqual(x[i, j], x2[i, j], 1)
+ self.assertAlmostEqual(y[i, j], y2[i, j], 1)
+
def test_Circle(self):
for w,h in [(2,77), (77,2), (256, 256), (640,480)]:
img = cv.CreateImage((w,h), cv.IPL_DEPTH_8U, 1)
self.assert_(a.depth == d)
self.assert_(cv.GetSize(a) == (w, h))
# self.assert_(cv.GetElemType(a) == d)
+ self.assertRaises(cv.error, lambda: cv.CreateImage((100, 100), 9, 1))
def test_CreateMat(self):
for rows in [1, 2, 4, 16, 64, 512, 640]:
m = cv.CreateMat(rows, cols, t)
self.assertEqual(cv.GetElemType(m), t)
self.assertEqual(m.type, t)
-
+ self.assertRaises(cv.error, lambda: cv.CreateMat(0, 100, cv.CV_8SC4))
+ self.assertRaises(cv.error, lambda: cv.CreateMat(100, 0, cv.CV_8SC4))
+ # Uncomment when ticket #100 is fixed
+ # self.assertRaises(cv.error, lambda: cv.CreateMat(100, 100, 666666))
def test_DrawChessboardCorners(self):
im = cv.CreateImage((512,512), cv.IPL_DEPTH_8U, 3)
random.seed(0)
storage = cv.CreateMemStorage()
+
+ # First run FindContours on a black image.
+ scratch = cv.CreateImage((800,800), 8, 1)
+ cv.SetZero(scratch)
+ seq = cv.FindContours(scratch, storage, cv.CV_RETR_TREE, cv.CV_CHAIN_APPROX_SIMPLE)
+
for trial in range(10):
scratch = cv.CreateImage((800,800), 8, 1)
cv.SetZero(scratch)
return sorted(r)
self.assert_(traverse(seq.v_next()) == actual)
+ if 1:
+ original = cv.CreateImage((800,800), 8, 1)
+ cv.SetZero(original)
+ cv.Circle(original, (400, 400), 200, 255, -1)
+ cv.Circle(original, (100, 100), 20, 255, -1)
+ else:
+ original = self.get_sample("samples/c/lena.jpg", 0)
+ cv.Threshold(original, original, 128, 255, cv.CV_THRESH_BINARY);
+
+ contours = cv.FindContours(original, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE)
+
+
+ def contour_iterator(contour):
+ while contour:
+ yield contour
+ contour = contour.h_next()
+
+ # Should be 2 contours from the two circles above
+ self.assertEqual(len(list(contour_iterator(contours))), 2)
+
+ # Smoke DrawContours
+ sketch = cv.CreateImage(cv.GetSize(original), 8, 3)
+ cv.SetZero(sketch)
+ red = cv.RGB(255, 0, 0)
+ green = cv.RGB(0, 255, 0)
+ for c in contour_iterator(contours):
+ cv.DrawContours(sketch, c, red, green, 0)
+ # self.snap(sketch)
+
def test_GetAffineTransform(self):
mapping = cv.CreateMat(2, 3, cv.CV_32FC1)
cv.GetAffineTransform([ (0,0), (1,0), (0,1) ], [ (0,0), (17,0), (0,17) ], mapping)
self.assert_(nd == 3)
self.assert_((nc * nr * nd) == elems)
+ # Now test ReshapeMatND
+ mat = cv.CreateMatND([24], cv.CV_32F)
+ cv.Set(mat, 1.0)
+ self.assertEqual(cv.GetDims(cv.ReshapeMatND(mat, 0, [])), (24, 1))
+ self.assertEqual(cv.GetDims(cv.ReshapeMatND(mat, 0, [1])), (6, 4))
+
def test_Save(self):
for o in [ cv.CreateImage((128,128), cv.IPL_DEPTH_8U, 1), cv.CreateMat(16, 16, cv.CV_32FC1) ]:
cv.Save("test.save", o)
# Should have produced the same answer every time, so results set should have size 1
self.assert_(len(results) == 1)
+ # ticket #71 repro attempt
+ image = self.get_sample("samples/c/lena.jpg", 0)
+ red = cv.CreateImage(cv.GetSize(image), 8, 1)
+ binary = cv.CreateImage(cv.GetSize(image), 8, 1)
+ cv.Split(image, red, None, None, None)
+ cv.Threshold(red, binary, 42, 255, cv.CV_THRESH_BINARY)
+
##############################################################################
def yield_line_image(self):
class AreaTests(OpenCVTests):
+ def test_numpy(self):
+ if 'fromarray' in dir(cv):
+ import numpy
+
+ def convert(numpydims):
+ """ Create a numpy array with specified dims, return the OpenCV CvMat """
+ a1 = numpy.array([1] * reduce(operator.__mul__, numpydims)).reshape(*numpydims)
+ return cv.fromarray(a1)
+ def row_col_chan(m):
+ col = m.cols
+ row = m.rows
+ chan = cv.CV_MAT_CN(cv.GetElemType(m))
+ return (row, col, chan)
+
+ self.assertEqual(row_col_chan(convert((2, 13))), (2, 13, 1))
+ self.assertEqual(row_col_chan(convert((2, 13, 4))), (2, 13, 4))
+ self.assertEqual(row_col_chan(convert((2, 13, cv.CV_CN_MAX))), (2, 13, cv.CV_CN_MAX))
+ self.assertRaises(TypeError, lambda: convert((2,)))
+ self.assertRaises(TypeError, lambda: convert((11, 17, cv.CV_CN_MAX + 1)))
+
+ for t in [cv.CV_16UC1, cv.CV_32SC1, cv.CV_32FC1]:
+ for d in [ (8,), (1,7), (2,3,4), (7,9,2,1,8), (1,2,3,4,5,6,7,8) ]:
+ total = reduce(operator.__mul__, d)
+ m = cv.CreateMatND(d, t)
+ for i in range(total):
+ cv.Set1D(m, i, i)
+ na = numpy.asarray(m).reshape((total,))
+ self.assertEqual(list(na), range(total))
+
+ # now do numpy -> cvmat, and verify
+ m2 = cv.fromarray(na, True)
+
+ # Check that new cvmat m2 contains same counting sequence
+ for i in range(total):
+ self.assertEqual(cv.Get1D(m, i)[0], i)
+
+ # Verify round-trip for 2D arrays
+ for rows in [2, 3, 7, 13]:
+ for cols in [2, 3, 7, 13]:
+ for allowND in [False, True]:
+ im = cv.CreateMatND([rows, cols], cv.CV_16UC1)
+ cv.SetZero(im)
+ a = numpy.asarray(im)
+ self.assertEqual(a.shape, (rows, cols))
+ cvmatnd = cv.fromarray(a, allowND)
+ self.assertEqual(cv.GetDims(cvmatnd), (rows, cols))
+
+ # im, a and cvmatnd all point to the same data, so...
+ for i,coord in enumerate([(0,0), (0,1), (1,0), (1,1)]):
+ v = 5 + i + 7
+ a[coord] = v
+ self.assertEqual(im[coord], v)
+ self.assertEqual(cvmatnd[coord], v)
+
+ # Cv -> Numpy 3 channel check
+ im = cv.CreateMatND([2, 13], cv.CV_16UC3)
+ self.assertEqual(numpy.asarray(im).shape, (2, 13, 3))
+
+ # multi-dimensional NumPy array
+ na = numpy.ones([7,9,2,1,8])
+ cm = cv.fromarray(na, True)
+ self.assertEqual(cv.GetDims(cm), (7,9,2,1,8))
+
+ # Using an array object for a CvArr parameter
+ ones = numpy.ones((640, 480))
+ r = numpy.ones((640, 480))
+ cv.AddS(ones, 7, r)
+ self.assert_(numpy.alltrue(r == (8 * ones)))
+
+ else:
+ print "SKIPPING test_numpy - numpy support not built"
+
+ def test_stereo(self):
+ bm = cv.CreateStereoBMState()
+ def illegal_delete():
+ bm = cv.CreateStereoBMState()
+ del bm.preFilterType
+ def illegal_assign():
+ bm = cv.CreateStereoBMState()
+ bm.preFilterType = "foo"
+
+ self.assertRaises(TypeError, illegal_delete)
+ self.assertRaises(TypeError, illegal_assign)
+
+ left = self.get_sample("samples/c/lena.jpg", 0)
+ right = self.get_sample("samples/c/lena.jpg", 0)
+ disparity = cv.CreateMat(512, 512, cv.CV_16SC1)
+ cv.FindStereoCorrespondenceBM(left, right, disparity, bm)
+
+ gc = cv.CreateStereoGCState(16, 2)
+ left_disparity = cv.CreateMat(512, 512, cv.CV_16SC1)
+ right_disparity = cv.CreateMat(512, 512, cv.CV_16SC1)
+ cv.FindStereoCorrespondenceGC(left, right, left_disparity, right_disparity, gc)
+
+ def test_kalman(self):
+ k = cv.CreateKalman(2, 1, 0)
+
def failing_test_exception(self):
- a = cv.CreateImage((640,480), cv.IPL_DEPTH_8U, 1)
- b = cv.CreateImage((640,480), cv.IPL_DEPTH_8U, 1)
+ a = cv.CreateImage((640, 480), cv.IPL_DEPTH_8U, 1)
+ b = cv.CreateImage((640, 480), cv.IPL_DEPTH_8U, 1)
self.assertRaises(cv.error, lambda: cv.Laplace(a, b))
def test_cvmat_accessors(self):
cv.Line(b, (x*16,0), (x*16,1024), 255)
#self.snapL([a,b])
- def snap(self, img):
- self.snapL([img])
-
- def snapL(self, L):
- for i,img in enumerate(L):
- cv.NamedWindow("snap-%d" % i, 1)
- cv.ShowImage("snap-%d" % i, img)
- cv.WaitKey()
- cv.DestroyAllWindows()
def local_test_Haar(self):
del im
self.assertEqual(sys.getrefcount(data), start_count - 1)
+ def test_morphological(self):
+ im = cv.CreateImage((128, 128), cv.IPL_DEPTH_8U, 1)
+ cv.Resize(cv.GetImage(self.get_sample("samples/c/lena.jpg", 0)), im)
+ dst = cv.CloneImage(im)
+
+ # Check defaults by asserting that all these operations produce the same image
+ funs = [
+ lambda: cv.Dilate(im, dst),
+ lambda: cv.Dilate(im, dst, None),
+ lambda: cv.Dilate(im, dst, iterations = 1),
+ lambda: cv.Dilate(im, dst, element = None),
+ lambda: cv.Dilate(im, dst, iterations = 1, element = None),
+ lambda: cv.Dilate(im, dst, element = None, iterations = 1),
+ ]
+ src_h = self.hashimg(im)
+ hashes = set()
+ for f in funs:
+ f()
+ hashes.add(self.hashimg(dst))
+ self.assertNotEqual(src_h, self.hashimg(dst))
+ # Source image should be untouched
+ self.assertEqual(self.hashimg(im), src_h)
+ # All results should be same
+ self.assertEqual(len(hashes), 1)
+
+ # self.snap(dst)
+ shapes = [eval("cv.CV_SHAPE_%s" % s) for s in ['RECT', 'CROSS', 'ELLIPSE']]
+ elements = [cv.CreateStructuringElementEx(sz, sz, sz / 2 + 1, sz / 2 + 1, shape) for sz in [3, 4, 7, 20] for shape in shapes]
+ elements += [cv.CreateStructuringElementEx(7, 7, 3, 3, cv.CV_SHAPE_CUSTOM, [1] * 49)]
+ for e in elements:
+ for iter in [1, 2]:
+ cv.Dilate(im, dst, e, iter)
+ cv.Erode(im, dst, e, iter)
+ temp = cv.CloneImage(im)
+ for op in ["OPEN", "CLOSE", "GRADIENT", "TOPHAT", "BLACKHAT"]:
+ cv.MorphologyEx(im, dst, temp, e, eval("cv.CV_MOP_%s" % op), iter)
+
+ def test_getmat_nd(self):
+ # 1D CvMatND should yield (N,1) CvMat
+ matnd = cv.CreateMatND([13], cv.CV_8UC1)
+ self.assertEqual(cv.GetDims(cv.GetMat(matnd, allowND = True)), (13, 1))
+
+ # 2D CvMatND should yield 2D CvMat
+ matnd = cv.CreateMatND([11, 12], cv.CV_8UC1)
+ self.assertEqual(cv.GetDims(cv.GetMat(matnd, allowND = True)), (11, 12))
+
+ # 3D CvMatND should yield (N,1) CvMat
+ matnd = cv.CreateMatND([7, 8, 9], cv.CV_8UC1)
+ self.assertEqual(cv.GetDims(cv.GetMat(matnd, allowND = True)), (7 * 8 * 9, 1))
+
def test_clipline(self):
self.assert_(cv.ClipLine((100,100), (-100,0), (500,0)) == ((0,0), (99,0)))
self.assert_(cv.ClipLine((100,100), (-100,0), (-200,0)) == None)
a = self.get_sample("samples/c/lena.jpg", 0)
eig_image = cv.CreateImage(cv.GetSize(a), cv.IPL_DEPTH_32F, 1)
temp_image = cv.CreateImage(cv.GetSize(a), cv.IPL_DEPTH_32F, 1)
- pts = cv.GoodFeaturesToTrack(a, eig_image, temp_image, 100, 0.04, 2, use_harris=1)
+ pts = cv.GoodFeaturesToTrack(a, eig_image, temp_image, 100, 0.04, 2, useHarris=1)
hull = cv.ConvexHull2(pts, cv.CreateMemStorage(), return_points = 1)
cv.FitLine(hull, cv.CV_DIST_L2, 0, 0.01, 0.01)
self.assertEqual(doreduce((1,3), lambda dst: cv.Reduce(srcmat, dst, op = cv.CV_REDUCE_MAX)), [3, 4, 5])
self.assertEqual(doreduce((1,3), lambda dst: cv.Reduce(srcmat, dst, op = cv.CV_REDUCE_MIN)), [0, 1, 2])
+ # exercise both dim and op
+ self.assertEqual(doreduce((1,3), lambda dst: cv.Reduce(srcmat, dst, 0, cv.CV_REDUCE_MAX)), [3, 4, 5])
+ self.assertEqual(doreduce((2,1), lambda dst: cv.Reduce(srcmat, dst, 1, cv.CV_REDUCE_MAX)), [2, 5])
+
def test_operations(self):
class Im:
if o == '-r':
shuffle = 1
+ cases = [PreliminaryTests, FunctionTests, AreaTests]
+ everything = [(tc, t) for tc in cases for t in unittest.TestLoader().getTestCaseNames(tc) ]
if len(args) == 0:
- cases = [PreliminaryTests, FunctionTests, AreaTests]
# cases = [NewTests]
- args = [(tc, t) for tc in cases for t in unittest.TestLoader().getTestCaseNames(tc) ]
+ args = everything
+ else:
+ args = [(tc, t) for (tc, t) in everything if t in args]
suite = unittest.TestSuite()
for l in range(loops):