Commit 25887e69 authored by Vadim Pisarevsky's avatar Vadim Pisarevsky

removed the obsolete tests from the trunk as well.

parent 832262e3
#ENABLE_TESTING()
#add_subdirectory(cv)
#add_subdirectory(cxcore)
#add_subdirectory(ml)
#add_subdirectory(cxts)
#add_subdirectory(gpu)
import sys
import math
import time
import random
import numpy
import transformations
import cv
def clamp(a, x, b):
return numpy.maximum(a, numpy.minimum(x, b))
def norm(v):
mag = numpy.sqrt(sum([e * e for e in v]))
return v / mag
class Vec3:
def __init__(self, x, y, z):
self.v = (x, y, z)
def x(self):
return self.v[0]
def y(self):
return self.v[1]
def z(self):
return self.v[2]
def __repr__(self):
return "<Vec3 (%s,%s,%s)>" % tuple([repr(c) for c in self.v])
def __add__(self, other):
return Vec3(*[self.v[i] + other.v[i] for i in range(3)])
def __sub__(self, other):
return Vec3(*[self.v[i] - other.v[i] for i in range(3)])
def __mul__(self, other):
if isinstance(other, Vec3):
return Vec3(*[self.v[i] * other.v[i] for i in range(3)])
else:
return Vec3(*[self.v[i] * other for i in range(3)])
def mag2(self):
return sum([e * e for e in self.v])
def __abs__(self):
return numpy.sqrt(sum([e * e for e in self.v]))
def norm(self):
return self * (1.0 / abs(self))
def dot(self, other):
return sum([self.v[i] * other.v[i] for i in range(3)])
def cross(self, other):
(ax, ay, az) = self.v
(bx, by, bz) = other.v
return Vec3(ay * bz - by * az, az * bx - bz * ax, ax * by - bx * ay)
class Ray:
def __init__(self, o, d):
self.o = o
self.d = d
def project(self, d):
return self.o + self.d * d
class Camera:
def __init__(self, F):
R = Vec3(1., 0., 0.)
U = Vec3(0, 1., 0)
self.center = Vec3(0, 0, 0)
self.pcenter = Vec3(0, 0, F)
self.up = U
self.right = R
def genray(self, x, y):
""" -1 <= y <= 1 """
r = numpy.sqrt(x * x + y * y)
if 0:
rprime = r + (0.17 * r**2)
else:
rprime = (10 * numpy.sqrt(17 * r + 25) - 50) / 17
print "scale", rprime / r
x *= rprime / r
y *= rprime / r
o = self.center
r = (self.pcenter + (self.right * x) + (self.up * y)) - o
return Ray(o, r.norm())
class Sphere:
def __init__(self, center, radius):
self.center = center
self.radius = radius
def hit(self, r):
# a = mag2(r.d)
a = 1.
v = r.o - self.center
b = 2 * r.d.dot(v)
c = self.center.mag2() + r.o.mag2() + -2 * self.center.dot(r.o) - (self.radius ** 2)
det = (b * b) - (4 * c)
pred = 0 < det
sq = numpy.sqrt(abs(det))
h0 = (-b - sq) / (2)
h1 = (-b + sq) / (2)
h = numpy.minimum(h0, h1)
pred = pred & (h > 0)
normal = (r.project(h) - self.center) * (1.0 / self.radius)
return (pred, numpy.where(pred, h, 999999.), normal)
def pt2plane(p, plane):
return p.dot(plane) * (1. / abs(plane))
class Plane:
def __init__(self, p, n, right):
self.D = -pt2plane(p, n)
self.Pn = n
self.right = right
self.rightD = -pt2plane(p, right)
self.up = n.cross(right)
self.upD = -pt2plane(p, self.up)
def hit(self, r):
Vd = self.Pn.dot(r.d)
V0 = -(self.Pn.dot(r.o) + self.D)
h = V0 / Vd
pred = (0 <= h)
return (pred, numpy.where(pred, h, 999999.), self.Pn)
def localxy(self, loc):
x = (loc.dot(self.right) + self.rightD)
y = (loc.dot(self.up) + self.upD)
return (x, y)
# lena = numpy.fromstring(cv.LoadImage("../samples/c/lena.jpg", 0).tostring(), numpy.uint8) / 255.0
def texture(xy):
x,y = xy
xa = numpy.floor(x * 512)
ya = numpy.floor(y * 512)
a = (512 * ya) + xa
safe = (0 <= x) & (0 <= y) & (x < 1) & (y < 1)
if 0:
a = numpy.where(safe, a, 0).astype(numpy.int)
return numpy.where(safe, numpy.take(lena, a), 0.0)
else:
xi = numpy.floor(x * 11).astype(numpy.int)
yi = numpy.floor(y * 11).astype(numpy.int)
inside = (1 <= xi) & (xi < 10) & (2 <= yi) & (yi < 9)
checker = (xi & 1) ^ (yi & 1)
final = numpy.where(inside, checker, 1.0)
return numpy.where(safe, final, 0.5)
def under(vv, m):
return Vec3(*(numpy.dot(m, vv.v + (1,))[:3]))
class Renderer:
def __init__(self, w, h, oversample):
self.w = w
self.h = h
random.seed(1)
x = numpy.arange(self.w*self.h) % self.w
y = numpy.floor(numpy.arange(self.w*self.h) / self.w)
h2 = h / 2.0
w2 = w / 2.0
self.r = [ None ] * oversample
for o in range(oversample):
stoch_x = numpy.random.rand(self.w * self.h)
stoch_y = numpy.random.rand(self.w * self.h)
nx = (x + stoch_x - 0.5 - w2) / h2
ny = (y + stoch_y - 0.5 - h2) / h2
self.r[o] = cam.genray(nx, ny)
self.rnds = [random.random() for i in range(10)]
def frame(self, i):
rnds = self.rnds
roll = math.sin(i * .01 * rnds[0] + rnds[1])
pitch = math.sin(i * .01 * rnds[2] + rnds[3])
yaw = math.pi * math.sin(i * .01 * rnds[4] + rnds[5])
x = math.sin(i * 0.01 * rnds[6])
y = math.sin(i * 0.01 * rnds[7])
x,y,z = -0.5,0.5,1
roll,pitch,yaw = (0,0,0)
z = 4 + 3 * math.sin(i * 0.1 * rnds[8])
print z
rz = transformations.euler_matrix(roll, pitch, yaw)
p = Plane(Vec3(x, y, z), under(Vec3(0,0,-1), rz), under(Vec3(1, 0, 0), rz))
acc = 0
for r in self.r:
(pred, h, norm) = p.hit(r)
l = numpy.where(pred, texture(p.localxy(r.project(h))), 0.0)
acc += l
acc *= (1.0 / len(self.r))
# print "took", time.time() - st
img = cv.CreateMat(self.h, self.w, cv.CV_8UC1)
cv.SetData(img, (clamp(0, acc, 1) * 255).astype(numpy.uint8).tostring(), self.w)
return img
#########################################################################
num_x_ints = 8
num_y_ints = 6
num_pts = num_x_ints * num_y_ints
def get_corners(mono, refine = False):
(ok, corners) = cv.FindChessboardCorners(mono, (num_x_ints, num_y_ints), cv.CV_CALIB_CB_ADAPTIVE_THRESH | cv.CV_CALIB_CB_NORMALIZE_IMAGE)
if refine and ok:
corners = cv.FindCornerSubPix(mono, corners, (5,5), (-1,-1), ( cv.CV_TERMCRIT_EPS+cv.CV_TERMCRIT_ITER, 30, 0.1 ))
return (ok, corners)
def mk_object_points(nimages, squaresize = 1):
opts = cv.CreateMat(nimages * num_pts, 3, cv.CV_32FC1)
for i in range(nimages):
for j in range(num_pts):
opts[i * num_pts + j, 0] = (j / num_x_ints) * squaresize
opts[i * num_pts + j, 1] = (j % num_x_ints) * squaresize
opts[i * num_pts + j, 2] = 0
return opts
def mk_image_points(goodcorners):
ipts = cv.CreateMat(len(goodcorners) * num_pts, 2, cv.CV_32FC1)
for (i, co) in enumerate(goodcorners):
for j in range(num_pts):
ipts[i * num_pts + j, 0] = co[j][0]
ipts[i * num_pts + j, 1] = co[j][1]
return ipts
def mk_point_counts(nimages):
npts = cv.CreateMat(nimages, 1, cv.CV_32SC1)
for i in range(nimages):
npts[i, 0] = num_pts
return npts
def cvmat_iterator(cvmat):
for i in range(cvmat.rows):
for j in range(cvmat.cols):
yield cvmat[i,j]
cam = Camera(3.0)
rend = Renderer(640, 480, 2)
cv.NamedWindow("snap")
#images = [rend.frame(i) for i in range(0, 2000, 400)]
images = [rend.frame(i) for i in [1200]]
if 0:
for i,img in enumerate(images):
cv.SaveImage("final/%06d.png" % i, img)
size = cv.GetSize(images[0])
corners = [get_corners(i) for i in images]
goodcorners = [co for (im, (ok, co)) in zip(images, corners) if ok]
def checkerboard_error(xformed):
def pt2line(a, b, c):
x0,y0 = a
x1,y1 = b
x2,y2 = c
return abs((x2 - x1) * (y1 - y0) - (x1 - x0) * (y2 - y1)) / math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
errorsum = 0.
for im in xformed:
for row in range(6):
l0 = im[8 * row]
l1 = im[8 * row + 7]
for col in range(1, 7):
e = pt2line(im[8 * row + col], l0, l1)
#print "row", row, "e", e
errorsum += e
return errorsum
if True:
from scipy.optimize import fmin
def xf(pt, poly):
x, y = pt
r = math.sqrt((x - 320) ** 2 + (y - 240) ** 2)
fr = poly(r) / r
return (320 + (x - 320) * fr, 240 + (y - 240) * fr)
def silly(p, goodcorners):
# print "eval", p
d = 1.0 # - sum(p)
poly = numpy.poly1d(list(p) + [d, 0.])
xformed = [[xf(pt, poly) for pt in co] for co in goodcorners]
return checkerboard_error(xformed)
x0 = [ 0. ]
#print silly(x0, goodcorners)
print "initial error", silly(x0, goodcorners)
xopt = fmin(silly, x0, args=(goodcorners,))
print "xopt", xopt
print "final error", silly(xopt, goodcorners)
d = 1.0 # - sum(xopt)
poly = numpy.poly1d(list(xopt) + [d, 0.])
print "final polynomial"
print poly
for co in goodcorners:
scrib = cv.CreateMat(480, 640, cv.CV_8UC3)
cv.SetZero(scrib)
cv.DrawChessboardCorners(scrib, (num_x_ints, num_y_ints), [xf(pt, poly) for pt in co], True)
cv.ShowImage("snap", scrib)
cv.WaitKey()
sys.exit(0)
for (i, (img, (ok, co))) in enumerate(zip(images, corners)):
scrib = cv.CreateMat(img.rows, img.cols, cv.CV_8UC3)
cv.CvtColor(img, scrib, cv.CV_GRAY2BGR)
if ok:
cv.DrawChessboardCorners(scrib, (num_x_ints, num_y_ints), co, True)
cv.ShowImage("snap", scrib)
cv.WaitKey()
print len(goodcorners)
ipts = mk_image_points(goodcorners)
opts = mk_object_points(len(goodcorners), .1)
npts = mk_point_counts(len(goodcorners))
intrinsics = cv.CreateMat(3, 3, cv.CV_64FC1)
distortion = cv.CreateMat(4, 1, cv.CV_64FC1)
cv.SetZero(intrinsics)
cv.SetZero(distortion)
# focal lengths have 1/1 ratio
intrinsics[0,0] = 1.0
intrinsics[1,1] = 1.0
cv.CalibrateCamera2(opts, ipts, npts,
cv.GetSize(images[0]),
intrinsics,
distortion,
cv.CreateMat(len(goodcorners), 3, cv.CV_32FC1),
cv.CreateMat(len(goodcorners), 3, cv.CV_32FC1),
flags = 0) # cv.CV_CALIB_ZERO_TANGENT_DIST)
print "D =", list(cvmat_iterator(distortion))
print "K =", list(cvmat_iterator(intrinsics))
mapx = cv.CreateImage((640, 480), cv.IPL_DEPTH_32F, 1)
mapy = cv.CreateImage((640, 480), cv.IPL_DEPTH_32F, 1)
cv.InitUndistortMap(intrinsics, distortion, mapx, mapy)
for img in images:
r = cv.CloneMat(img)
cv.Remap(img, r, mapx, mapy)
cv.ShowImage("snap", r)
cv.WaitKey()
import cv
import unittest
class TestGoodFeaturesToTrack(unittest.TestCase):
def test(self):
arr = cv.LoadImage("../samples/c/lena.jpg", 0)
original = cv.CloneImage(arr)
size = cv.GetSize(arr)
eig_image = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
temp_image = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
threshes = [ x / 100. for x in range(1,10) ]
results = dict([(t, cv.GoodFeaturesToTrack(arr, eig_image, temp_image, 20000, t, 2, use_harris = 1)) for t in threshes])
# Check that GoodFeaturesToTrack has not modified input image
self.assert_(arr.tostring() == original.tostring())
# Check for repeatability
for i in range(10):
results2 = dict([(t, cv.GoodFeaturesToTrack(arr, eig_image, temp_image, 20000, t, 2, use_harris = 1)) for t in threshes])
self.assert_(results == results2)
for t0,t1 in zip(threshes, threshes[1:]):
r0 = results[t0]
r1 = results[t1]
# Increasing thresh should make result list shorter
self.assert_(len(r0) > len(r1))
# Increasing thresh should monly truncate result list
self.assert_(r0[:len(r1)] == r1)
if __name__ == '__main__':
unittest.main()
import cv
import numpy as np
cv.NamedWindow('Leak')
while 1:
leak = np.random.random((480, 640)) * 255
cv.ShowImage('Leak', leak.astype(np.uint8))
cv.WaitKey(10)
import cv
import numpy as np
import time
while True:
for i in range(4000):
a = cv.CreateImage((1024,1024), cv.IPL_DEPTH_8U, 1)
b = cv.CreateMat(1024, 1024, cv.CV_8UC1)
c = cv.CreateMatND([1024,1024], cv.CV_8UC1)
print "pause..."
import cv
import math
import time
while True:
h = cv.CreateHist([40], cv.CV_HIST_ARRAY, [[0,255]], 1)
import cv
import math
import time
N=50000
print "leak4"
while True:
seq=list((i*1., i*1.) for i in range(N))
cv.Moments(seq)
import unittest
import random
import time
import math
import sys
import array
import urllib
import tarfile
import hashlib
import os
import getopt
import operator
import functools
import cv
class OpenCVTests(unittest.TestCase):
depths = [ cv.IPL_DEPTH_8U, cv.IPL_DEPTH_8S, cv.IPL_DEPTH_16U, cv.IPL_DEPTH_16S, cv.IPL_DEPTH_32S, cv.IPL_DEPTH_32F, cv.IPL_DEPTH_64F ]
mat_types = [
cv.CV_8UC1,
cv.CV_8UC2,
cv.CV_8UC3,
cv.CV_8UC4,
cv.CV_8SC1,
cv.CV_8SC2,
cv.CV_8SC3,
cv.CV_8SC4,
cv.CV_16UC1,
cv.CV_16UC2,
cv.CV_16UC3,
cv.CV_16UC4,
cv.CV_16SC1,
cv.CV_16SC2,
cv.CV_16SC3,
cv.CV_16SC4,
cv.CV_32SC1,
cv.CV_32SC2,
cv.CV_32SC3,
cv.CV_32SC4,
cv.CV_32FC1,
cv.CV_32FC2,
cv.CV_32FC3,
cv.CV_32FC4,
cv.CV_64FC1,
cv.CV_64FC2,
cv.CV_64FC3,
cv.CV_64FC4,
]
mat_types_single = [
cv.CV_8UC1,
cv.CV_8SC1,
cv.CV_16UC1,
cv.CV_16SC1,
cv.CV_32SC1,
cv.CV_32FC1,
cv.CV_64FC1,
]
def depthsize(self, d):
return { cv.IPL_DEPTH_8U : 1,
cv.IPL_DEPTH_8S : 1,
cv.IPL_DEPTH_16U : 2,
cv.IPL_DEPTH_16S : 2,
cv.IPL_DEPTH_32S : 4,
cv.IPL_DEPTH_32F : 4,
cv.IPL_DEPTH_64F : 8 }[d]
def get_sample(self, filename, iscolor = cv.CV_LOAD_IMAGE_COLOR):
if not filename in self.image_cache:
filedata = urllib.urlopen("https://code.ros.org/svn/opencv/trunk/opencv/" + filename).read()
imagefiledata = cv.CreateMatHeader(1, len(filedata), cv.CV_8UC1)
cv.SetData(imagefiledata, filedata, len(filedata))
self.image_cache[filename] = cv.DecodeImageM(imagefiledata, iscolor)
return self.image_cache[filename]
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):
def test_lena(self):
# Check that the lena jpg image has loaded correctly
# This test uses a 'golden' MD5 hash of the Lena image
# If the JPEG decompressor changes, it is possible that the MD5 hash will change,
# so the hash here will need to change.
im = self.get_sample("samples/c/lena.jpg")
# self.snap(im) # uncomment this line to view the image, when regilding
self.assertEqual(hashlib.md5(im.tostring()).hexdigest(), "9dcd9247f9811c6ce86675ba7b0297b6")
def test_LoadImage(self):
self.assertRaises(TypeError, lambda: cv.LoadImage())
self.assertRaises(TypeError, lambda: cv.LoadImage(4))
self.assertRaises(TypeError, lambda: cv.LoadImage('foo.jpg', 1, 1))
self.assertRaises(TypeError, lambda: cv.LoadImage('foo.jpg', xiscolor=cv.CV_LOAD_IMAGE_COLOR))
def test_types(self):
self.assert_(type(cv.CreateImage((7,5), cv.IPL_DEPTH_8U, 1)) == cv.iplimage)
self.assert_(type(cv.CreateMat(5, 7, cv.CV_32FC1)) == cv.cvmat)
for i,t in enumerate(self.mat_types):
basefunc = [
cv.CV_8UC,
cv.CV_8SC,
cv.CV_16UC,
cv.CV_16SC,
cv.CV_32SC,
cv.CV_32FC,
cv.CV_64FC,
][i / 4]
self.assertEqual(basefunc(1 + (i % 4)), t)
def test_tostring(self):
for w in [ 1, 4, 64, 512, 640]:
for h in [ 1, 4, 64, 480, 512]:
for c in [1, 2, 3, 4]:
for d in self.depths:
a = cv.CreateImage((w,h), d, c);
self.assert_(len(a.tostring()) == w * h * c * self.depthsize(d))
for w in [ 32, 96, 480 ]:
for h in [ 32, 96, 480 ]:
depth_size = {
cv.IPL_DEPTH_8U : 1,
cv.IPL_DEPTH_8S : 1,
cv.IPL_DEPTH_16U : 2,
cv.IPL_DEPTH_16S : 2,
cv.IPL_DEPTH_32S : 4,
cv.IPL_DEPTH_32F : 4,
cv.IPL_DEPTH_64F : 8
}
for f in self.depths:
for channels in (1,2,3,4):
img = cv.CreateImage((w, h), f, channels)
esize = (w * h * channels * depth_size[f])
self.assert_(len(img.tostring()) == esize)
cv.SetData(img, " " * esize, w * channels * depth_size[f])
self.assert_(len(img.tostring()) == esize)
mattype_size = {
cv.CV_8UC1 : 1,
cv.CV_8UC2 : 1,
cv.CV_8UC3 : 1,
cv.CV_8UC4 : 1,
cv.CV_8SC1 : 1,
cv.CV_8SC2 : 1,
cv.CV_8SC3 : 1,
cv.CV_8SC4 : 1,
cv.CV_16UC1 : 2,
cv.CV_16UC2 : 2,
cv.CV_16UC3 : 2,
cv.CV_16UC4 : 2,
cv.CV_16SC1 : 2,
cv.CV_16SC2 : 2,
cv.CV_16SC3 : 2,
cv.CV_16SC4 : 2,
cv.CV_32SC1 : 4,
cv.CV_32SC2 : 4,
cv.CV_32SC3 : 4,
cv.CV_32SC4 : 4,
cv.CV_32FC1 : 4,
cv.CV_32FC2 : 4,
cv.CV_32FC3 : 4,
cv.CV_32FC4 : 4,
cv.CV_64FC1 : 8,
cv.CV_64FC2 : 8,
cv.CV_64FC3 : 8,
cv.CV_64FC4 : 8
}
for t in self.mat_types:
for im in [cv.CreateMat(h, w, t), cv.CreateMatND([h, w], t)]:
elemsize = cv.CV_MAT_CN(cv.GetElemType(im)) * mattype_size[cv.GetElemType(im)]
cv.SetData(im, " " * (w * h * elemsize), (w * elemsize))
esize = (w * h * elemsize)
self.assert_(len(im.tostring()) == esize)
cv.SetData(im, " " * esize, w * elemsize)
self.assert_(len(im.tostring()) == esize)
# Tests for specific OpenCV functions
class FunctionTests(OpenCVTests):
def test_AvgSdv(self):
m = cv.CreateMat(1, 8, cv.CV_32FC1)
for i,v in enumerate([2, 4, 4, 4, 5, 5, 7, 9]):
m[0,i] = (v,)
self.assertAlmostEqual(cv.Avg(m)[0], 5.0, 3)
avg,sdv = cv.AvgSdv(m)
self.assertAlmostEqual(avg[0], 5.0, 3)
self.assertAlmostEqual(sdv[0], 2.0, 3)
def test_CalcEMD2(self):
cc = {}
for r in [ 5, 10, 37, 38 ]:
scratch = cv.CreateImage((100,100), 8, 1)
cv.SetZero(scratch)
cv.Circle(scratch, (50,50), r, 255, -1)
storage = cv.CreateMemStorage()
seq = cv.FindContours(scratch, storage, cv.CV_RETR_TREE, cv.CV_CHAIN_APPROX_SIMPLE)
arr = cv.CreateMat(len(seq), 3, cv.CV_32FC1)
for i,e in enumerate(seq):
arr[i,0] = 1
arr[i,1] = e[0]
arr[i,2] = e[1]
cc[r] = arr
def myL1(A, B, D):
return abs(A[0]-B[0]) + abs(A[1]-B[1])
def myL2(A, B, D):
return math.sqrt((A[0]-B[0])**2 + (A[1]-B[1])**2)
def myC(A, B, D):
return max(abs(A[0]-B[0]), abs(A[1]-B[1]))
contours = set(cc.values())
for c0 in contours:
for c1 in contours:
self.assert_(abs(cv.CalcEMD2(c0, c1, cv.CV_DIST_L1) - cv.CalcEMD2(c0, c1, cv.CV_DIST_USER, myL1)) < 1e-3)
self.assert_(abs(cv.CalcEMD2(c0, c1, cv.CV_DIST_L2) - cv.CalcEMD2(c0, c1, cv.CV_DIST_USER, myL2)) < 1e-3)
self.assert_(abs(cv.CalcEMD2(c0, c1, cv.CV_DIST_C) - cv.CalcEMD2(c0, c1, cv.CV_DIST_USER, myC)) < 1e-3)
def test_CalcOpticalFlowBM(self):
a = self.get_sample("samples/c/lena.jpg", 0)
b = self.get_sample("samples/c/lena.jpg", 0)
(w,h) = cv.GetSize(a)
vel_size = (w - 8, h - 8)
velx = cv.CreateImage(vel_size, cv.IPL_DEPTH_32F, 1)
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_CalcOpticalFlowPyrLK(self):
a = self.get_sample("samples/c/lena.jpg", 0)
map = cv.CreateMat(2, 3, cv.CV_32FC1)
cv.GetRotationMatrix2D((256, 256), 10, 1.0, map)
b = cv.CloneMat(a)
cv.WarpAffine(a, b, map)
eig_image = cv.CreateMat(a.rows, a.cols, cv.CV_32FC1)
temp_image = cv.CreateMat(a.rows, a.cols, cv.CV_32FC1)
prevPyr = cv.CreateMat(a.rows / 3, a.cols + 8, cv.CV_8UC1)
currPyr = cv.CreateMat(a.rows / 3, a.cols + 8, cv.CV_8UC1)
prevFeatures = cv.GoodFeaturesToTrack(a, eig_image, temp_image, 400, 0.01, 0.01)
(currFeatures, status, track_error) = cv.CalcOpticalFlowPyrLK(a,
b,
prevPyr,
currPyr,
prevFeatures,
(10, 10),
3,
(cv.CV_TERMCRIT_ITER|cv.CV_TERMCRIT_EPS,20, 0.03),
0)
if 0: # enable visualization
print
print sum(status), "Points found in curr image"
for prev,this in zip(prevFeatures, currFeatures):
iprev = tuple([int(c) for c in prev])
ithis = tuple([int(c) for c in this])
cv.Circle(a, iprev, 3, 255)
cv.Circle(a, ithis, 3, 0)
cv.Line(a, iprev, ithis, 128)
self.snapL([a, b])
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)
cv.SetZero(img)
tricky = [ -8000, -2, -1, 0, 1, h/2, h-1, h, h+1, w/2, w-1, w, w+1, 8000]
for x0 in tricky:
for y0 in tricky:
for r in [ 0, 1, 2, 3, 4, 5, w/2, w-1, w, w+1, h/2, h-1, h, h+1, 8000 ]:
for thick in [1, 2, 10]:
for t in [0, 8, 4, cv.CV_AA]:
cv.Circle(img, (x0,y0), r, 255, thick, t)
# just check that something was drawn
self.assert_(cv.Sum(img)[0] > 0)
def test_ConvertImage(self):
i1 = cv.GetImage(self.get_sample("samples/c/lena.jpg", 1))
i2 = cv.CloneImage(i1)
i3 = cv.CloneImage(i1)
cv.ConvertImage(i1, i2, cv.CV_CVTIMG_FLIP + cv.CV_CVTIMG_SWAP_RB)
self.assertNotEqual(self.hashimg(i1), self.hashimg(i2))
cv.ConvertImage(i2, i3, cv.CV_CVTIMG_FLIP + cv.CV_CVTIMG_SWAP_RB)
self.assertEqual(self.hashimg(i1), self.hashimg(i3))
def test_ConvexHull2(self):
# Draw a series of N-pointed stars, find contours, assert the contour is not convex,
# assert the hull has N segments, assert that there are N convexity defects.
def polar2xy(th, r):
return (int(400 + r * math.cos(th)), int(400 + r * math.sin(th)))
storage = cv.CreateMemStorage(0)
for way in ['CvSeq', 'CvMat', 'list']:
for points in range(3,20):
scratch = cv.CreateImage((800,800), 8, 1)
cv.SetZero(scratch)
sides = 2 * points
cv.FillPoly(scratch, [ [ polar2xy(i * 2 * math.pi / sides, [100,350][i&1]) for i in range(sides) ] ], 255)
seq = cv.FindContours(scratch, storage, cv.CV_RETR_TREE, cv.CV_CHAIN_APPROX_SIMPLE)
if way == 'CvSeq':
# pts is a CvSeq
pts = seq
elif way == 'CvMat':
# pts is a CvMat
arr = cv.CreateMat(len(seq), 1, cv.CV_32SC2)
for i,e in enumerate(seq):
arr[i,0] = e
pts = arr
elif way == 'list':
# pts is a list of 2-tuples
pts = list(seq)
else:
assert False
self.assert_(cv.CheckContourConvexity(pts) == 0)
hull = cv.ConvexHull2(pts, storage, return_points = 1)
self.assert_(cv.CheckContourConvexity(hull) == 1)
self.assert_(len(hull) == points)
if way in [ 'CvSeq', 'CvMat' ]:
defects = cv.ConvexityDefects(pts, cv.ConvexHull2(pts, storage), storage)
self.assert_(len([depth for (_,_,_,depth) in defects if (depth > 5)]) == points)
def test_CreateImage(self):
for w in [ 1, 4, 64, 512, 640]:
for h in [ 1, 4, 64, 480, 512]:
for c in [1, 2, 3, 4]:
for d in self.depths:
a = cv.CreateImage((w,h), d, c);
self.assert_(a.width == w)
self.assert_(a.height == h)
self.assert_(a.nChannels == c)
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]:
for cols in [1, 2, 4, 16, 64, 512, 640]:
for t in self.mat_types:
m = cv.CreateMat(rows, cols, t)
self.assertEqual(cv.GetElemType(m), t)
self.assertEqual(m.type, t)
self.assertRaises(cv.error, lambda: cv.CreateMat(-1, 100, cv.CV_8SC4))
self.assertRaises(cv.error, lambda: cv.CreateMat(100, -1, cv.CV_8SC4))
self.assertRaises(cv.error, lambda: cv.cvmat())
def test_DrawChessboardCorners(self):
im = cv.CreateImage((512,512), cv.IPL_DEPTH_8U, 3)
cv.SetZero(im)
cv.DrawChessboardCorners(im, (5, 5), [ (100,100) for i in range(5 * 5) ], 1)
self.assert_(cv.Sum(im)[0] > 0)
self.assertRaises(TypeError, lambda: cv.DrawChessboardCorners(im, (4, 5), [ (100,100) for i in range(5 * 5) ], 1))
def test_ExtractSURF(self):
img = self.get_sample("samples/c/lena.jpg", 0)
w,h = cv.GetSize(img)
for hessthresh in [ 300,400,500]:
for dsize in [0,1]:
for layers in [1,3,10]:
kp,desc = cv.ExtractSURF(img, None, cv.CreateMemStorage(), (dsize, hessthresh, 3, layers))
self.assert_(len(kp) == len(desc))
for d in desc:
self.assert_(len(d) == {0:64, 1:128}[dsize])
for pt,laplacian,size,dir,hessian in kp:
self.assert_((0 <= pt[0]) and (pt[0] <= w))
self.assert_((0 <= pt[1]) and (pt[1] <= h))
self.assert_(laplacian in [-1, 0, 1])
self.assert_((0 <= dir) and (dir <= 360))
self.assert_(hessian >= hessthresh)
def test_FillPoly(self):
scribble = cv.CreateImage((640,480), cv.IPL_DEPTH_8U, 1)
random.seed(0)
for i in range(50):
cv.SetZero(scribble)
self.assert_(cv.CountNonZero(scribble) == 0)
cv.FillPoly(scribble, [ [ (random.randrange(640), random.randrange(480)) for i in range(100) ] ], (255,))
self.assert_(cv.CountNonZero(scribble) != 0)
def test_FindChessboardCorners(self):
im = cv.CreateImage((512,512), cv.IPL_DEPTH_8U, 1)
cv.Set(im, 128)
# Empty image run
status,corners = cv.FindChessboardCorners( im, (7,7) )
# Perfect checkerboard
def xf(i,j, o):
return ((96 + o) + 40 * i, (96 + o) + 40 * j)
for i in range(8):
for j in range(8):
color = ((i ^ j) & 1) * 255
cv.Rectangle(im, xf(i,j, 0), xf(i,j, 39), color, cv.CV_FILLED)
status,corners = cv.FindChessboardCorners( im, (7,7) )
self.assert_(status)
self.assert_(len(corners) == (7 * 7))
# Exercise corner display
im3 = cv.CreateImage(cv.GetSize(im), cv.IPL_DEPTH_8U, 3)
cv.Merge(im, im, im, None, im3)
cv.DrawChessboardCorners(im3, (7,7), corners, status)
if 0:
self.snap(im3)
# Run it with too many corners
cv.Set(im, 128)
for i in range(40):
for j in range(40):
color = ((i ^ j) & 1) * 255
x = 30 + 6 * i
y = 30 + 4 * j
cv.Rectangle(im, (x, y), (x+4, y+4), color, cv.CV_FILLED)
status,corners = cv.FindChessboardCorners( im, (7,7) )
# XXX - this is very slow
if 0:
rng = cv.RNG(0)
cv.RandArr(rng, im, cv.CV_RAND_UNI, 0, 255.0)
self.snap(im)
status,corners = cv.FindChessboardCorners( im, (7,7) )
def test_FindContours(self):
random.seed(0)
storage = cv.CreateMemStorage()
# First run FindContours on a black image.
for mode in [cv.CV_RETR_EXTERNAL, cv.CV_RETR_LIST, cv.CV_RETR_CCOMP, cv.CV_RETR_TREE]:
for method in [cv.CV_CHAIN_CODE, cv.CV_CHAIN_APPROX_NONE, cv.CV_CHAIN_APPROX_SIMPLE, cv.CV_CHAIN_APPROX_TC89_L1, cv.CV_CHAIN_APPROX_TC89_KCOS, cv.CV_LINK_RUNS]:
scratch = cv.CreateImage((800,800), 8, 1)
cv.SetZero(scratch)
seq = cv.FindContours(scratch, storage, mode, method)
x = len(seq)
if seq:
pass
for s in seq:
pass
for trial in range(10):
scratch = cv.CreateImage((800,800), 8, 1)
cv.SetZero(scratch)
def plot(center, radius, mode):
cv.Circle(scratch, center, radius, mode, -1)
if radius < 20:
return 0
else:
newmode = 255 - mode
subs = random.choice([1,2,3])
if subs == 1:
return [ plot(center, radius - 5, newmode) ]
else:
newradius = int({ 2: radius / 2, 3: radius / 2.3 }[subs] - 5)
r = radius / 2
ret = []
for i in range(subs):
th = i * (2 * math.pi) / subs
ret.append(plot((int(center[0] + r * math.cos(th)), int(center[1] + r * math.sin(th))), newradius, newmode))
return sorted(ret)
actual = plot((400,400), 390, 255 )
seq = cv.FindContours(scratch, storage, cv.CV_RETR_TREE, cv.CV_CHAIN_APPROX_SIMPLE)
def traverse(s):
if s == None:
return 0
else:
self.assert_(abs(cv.ContourArea(s)) > 0.0)
((x,y),(w,h),th) = cv.MinAreaRect2(s, cv.CreateMemStorage())
self.assert_(((w / h) - 1.0) < 0.01)
self.assert_(abs(cv.ContourArea(s)) > 0.0)
r = []
while s:
r.append(traverse(s.v_next()))
s = s.h_next()
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.assertAlmostEqual(mapping[0,0], 17, 2)
self.assertAlmostEqual(mapping[1,1], 17, 2)
def test_GetRotationMatrix2D(self):
mapping = cv.CreateMat(2, 3, cv.CV_32FC1)
for scale in [0.0, 1.0, 2.0]:
for angle in [0.0, 360.0]:
cv.GetRotationMatrix2D((0,0), angle, scale, mapping)
for r in [0, 1]:
for c in [0, 1, 2]:
if r == c:
e = scale
else:
e = 0.0
self.assertAlmostEqual(mapping[r, c], e, 2)
def test_GetSize(self):
self.assert_(cv.GetSize(cv.CreateMat(5, 7, cv.CV_32FC1)) == (7,5))
self.assert_(cv.GetSize(cv.CreateImage((7,5), cv.IPL_DEPTH_8U, 1)) == (7,5))
def test_GetStarKeypoints(self):
src = self.get_sample("samples/c/lena.jpg", 0)
storage = cv.CreateMemStorage()
kp = cv.GetStarKeypoints(src, storage)
self.assert_(len(kp) > 0)
for (x,y),scale,r in kp:
self.assert_(0 <= x)
self.assert_(x <= cv.GetSize(src)[0])
self.assert_(0 <= y)
self.assert_(y <= cv.GetSize(src)[1])
return
scribble = cv.CreateImage(cv.GetSize(src), 8, 3)
cv.CvtColor(src, scribble, cv.CV_GRAY2BGR)
for (x,y),scale,r in kp:
print x,y,scale,r
cv.Circle(scribble, (x,y), scale, cv.RGB(255,0,0))
self.snap(scribble)
def test_GetSubRect(self):
src = cv.CreateImage((100,100), 8, 1)
data = "z" * (100 * 100)
cv.SetData(src, data, 100)
start_count = sys.getrefcount(data)
iter = 77
subs = []
for i in range(iter):
sub = cv.GetSubRect(src, (0, 0, 10, 10))
subs.append(sub)
self.assert_(sys.getrefcount(data) == (start_count + iter))
src = self.get_sample("samples/c/lena.jpg", 0)
made = cv.CreateImage(cv.GetSize(src), 8, 1)
sub = cv.CreateMat(32, 32, cv.CV_8UC1)
for x in range(0, 512, 32):
for y in range(0, 512, 32):
sub = cv.GetSubRect(src, (x, y, 32, 32))
cv.SetImageROI(made, (x, y, 32, 32))
cv.Copy(sub, made)
cv.ResetImageROI(made)
cv.AbsDiff(made, src, made)
self.assert_(cv.CountNonZero(made) == 0)
for m1 in [cv.CreateMat(1, 10, cv.CV_8UC1), cv.CreateImage((10, 1), 8, 1)]:
for i in range(10):
m1[0, i] = i
def aslist(cvmat): return list(array.array('B', cvmat.tostring()))
m2 = cv.GetSubRect(m1, (5, 0, 4, 1))
m3 = cv.GetSubRect(m2, (1, 0, 2, 1))
self.assertEqual(aslist(m1), range(10))
self.assertEqual(aslist(m2), range(5, 9))
self.assertEqual(aslist(m3), range(6, 8))
def xtest_grabCut(self):
image = self.get_sample("samples/c/lena.jpg", cv.CV_LOAD_IMAGE_COLOR)
tmp1 = cv.CreateMat(1, 13 * 5, cv.CV_32FC1)
tmp2 = cv.CreateMat(1, 13 * 5, cv.CV_32FC1)
mask = cv.CreateMat(image.rows, image.cols, cv.CV_8UC1)
cv.GrabCut(image, mask, (10,10,200,200), tmp1, tmp2, 10, cv.GC_INIT_WITH_RECT)
def test_HoughLines2_PROBABILISTIC(self):
li = cv.HoughLines2(self.yield_line_image(),
cv.CreateMemStorage(),
cv.CV_HOUGH_PROBABILISTIC,
1,
math.pi/180,
50,
50,
10)
self.assert_(len(li) > 0)
self.assert_(li[0] != None)
def test_HoughLines2_STANDARD(self):
li = cv.HoughLines2(self.yield_line_image(),
cv.CreateMemStorage(),
cv.CV_HOUGH_STANDARD,
1,
math.pi/180,
100,
0,
0)
self.assert_(len(li) > 0)
self.assert_(li[0] != None)
def test_InPaint(self):
src = self.get_sample("doc/pics/building.jpg")
msk = cv.CreateImage(cv.GetSize(src), cv.IPL_DEPTH_8U, 1)
damaged = cv.CloneMat(src)
repaired = cv.CreateImage(cv.GetSize(src), cv.IPL_DEPTH_8U, 3)
difference = cv.CloneImage(repaired)
cv.SetZero(msk)
for method in [ cv.CV_INPAINT_NS, cv.CV_INPAINT_TELEA ]:
for (p0,p1) in [ ((10,10), (400,400)) ]:
cv.Line(damaged, p0, p1, cv.RGB(255, 0, 255), 2)
cv.Line(msk, p0, p1, 255, 2)
cv.Inpaint(damaged, msk, repaired, 10., cv.CV_INPAINT_NS)
cv.AbsDiff(src, repaired, difference)
#self.snapL([src, damaged, repaired, difference])
def test_InitLineIterator(self):
scribble = cv.CreateImage((640,480), cv.IPL_DEPTH_8U, 1)
self.assert_(len(list(cv.InitLineIterator(scribble, (20,10), (30,10)))) == 11)
def test_InRange(self):
sz = (256,256)
Igray1 = cv.CreateImage(sz,cv.IPL_DEPTH_32F,1)
Ilow1 = cv.CreateImage(sz,cv.IPL_DEPTH_32F,1)
Ihi1 = cv.CreateImage(sz,cv.IPL_DEPTH_32F,1)
Igray2 = cv.CreateImage(sz,cv.IPL_DEPTH_32F,1)
Ilow2 = cv.CreateImage(sz,cv.IPL_DEPTH_32F,1)
Ihi2 = cv.CreateImage(sz,cv.IPL_DEPTH_32F,1)
Imask = cv.CreateImage(sz, cv.IPL_DEPTH_8U,1)
Imaskt = cv.CreateImage(sz,cv.IPL_DEPTH_8U,1)
cv.InRange(Igray1, Ilow1, Ihi1, Imask);
cv.InRange(Igray2, Ilow2, Ihi2, Imaskt);
cv.Or(Imask, Imaskt, Imask);
def test_Line(self):
w,h = 640,480
img = cv.CreateImage((w,h), cv.IPL_DEPTH_8U, 1)
cv.SetZero(img)
tricky = [ -8000, -2, -1, 0, 1, h/2, h-1, h, h+1, w/2, w-1, w, w+1, 8000]
for x0 in tricky:
for y0 in tricky:
for x1 in tricky:
for y1 in tricky:
for thickness in [ 0, 1, 8 ]:
for line_type in [0, 4, 8, cv.CV_AA ]:
cv.Line(img, (x0,y0), (x1,y1), 255, thickness, line_type)
# just check that something was drawn
self.assert_(cv.Sum(img)[0] > 0)
def test_MinMaxLoc(self):
scribble = cv.CreateImage((640,480), cv.IPL_DEPTH_8U, 1)
los = [ (random.randrange(480), random.randrange(640)) for i in range(100) ]
his = [ (random.randrange(480), random.randrange(640)) for i in range(100) ]
for (lo,hi) in zip(los,his):
cv.Set(scribble, 128)
scribble[lo] = 0
scribble[hi] = 255
r = cv.MinMaxLoc(scribble)
self.assert_(r == (0, 255, tuple(reversed(lo)), tuple(reversed(hi))))
def xxx_test_PyrMeanShiftFiltering(self): # XXX - ticket #306
if 0:
src = self.get_sample("samples/c/lena.jpg", cv.CV_LOAD_IMAGE_COLOR)
dst = cv.CloneMat(src)
cv.PyrMeanShiftFiltering(src, dst, 5, 5)
print src, dst
self.snap(src)
else:
r = cv.temp_test()
print r
print len(r.tostring())
self.snap(r)
def test_Reshape(self):
# 97 rows
# 12 cols
rows = 97
cols = 12
im = cv.CreateMat( rows, cols, cv.CV_32FC1 )
elems = rows * cols * 1
def crd(im):
return cv.GetSize(im) + (cv.CV_MAT_CN(cv.GetElemType(im)),)
for c in (1, 2, 3, 4):
nc,nr,nd = crd(cv.Reshape(im, c))
self.assert_(nd == c)
self.assert_((nc * nr * nd) == elems)
nc,nr,nd = crd(cv.Reshape(im, 0, 97*2))
self.assert_(nr == 97*2)
self.assert_((nc * nr * nd) == elems)
nc,nr,nd = crd(cv.Reshape(im, 3, 97*2))
self.assert_(nr == 97*2)
self.assert_(nd == 3)
self.assert_((nc * nr * nd) == elems)
# Now test ReshapeMatND
mat = cv.CreateMatND([24], cv.CV_32FC1)
cv.Set(mat, 1.0)
self.assertEqual(cv.GetDims(cv.ReshapeMatND(mat, 0, [24, 1])), (24, 1))
self.assertEqual(cv.GetDims(cv.ReshapeMatND(mat, 0, [6, 4])), (6, 4))
self.assertEqual(cv.GetDims(cv.ReshapeMatND(mat, 24, [1])), (1,))
self.assertRaises(TypeError, lambda: cv.ReshapeMatND(mat, 12, [1]))
def test_Save(self):
for o in [ cv.CreateImage((128,128), cv.IPL_DEPTH_8U, 1), cv.CreateMat(16, 16, cv.CV_32FC1), cv.CreateMatND([7,9,4], cv.CV_32FC1) ]:
cv.Save("test.save", o)
loaded = cv.Load("test.save", cv.CreateMemStorage())
self.assert_(type(o) == type(loaded))
def test_SetIdentity(self):
for r in range(1,16):
for c in range(1, 16):
for t in self.mat_types_single:
M = cv.CreateMat(r, c, t)
cv.SetIdentity(M)
for rj in range(r):
for cj in range(c):
if rj == cj:
expected = 1.0
else:
expected = 0.0
self.assertEqual(M[rj,cj], expected)
def test_SnakeImage(self):
src = self.get_sample("samples/c/lena.jpg", 0)
pts = [ (512-i,i) for i in range(0, 512, 8) ]
# Make sure that weight arguments get validated
self.assertRaises(TypeError, lambda: cv.SnakeImage(cv.GetImage(src), pts, [1,2], .01, .01, (7,7), (cv.CV_TERMCRIT_ITER, 100, 0.1)))
# Smoke by making sure that points are changed by call
r = cv.SnakeImage(cv.GetImage(src), pts, .01, .01, .01, (7,7), (cv.CV_TERMCRIT_ITER, 100, 0.1))
if 0:
cv.PolyLine(src, [ r ], 0, 255)
self.snap(src)
self.assertEqual(len(r), len(pts))
self.assertNotEqual(r, pts)
# Ensure that list of weights is same as scalar weight
w = [.01] * len(pts)
r2 = cv.SnakeImage(cv.GetImage(src), pts, w, w, w, (7,7), (cv.CV_TERMCRIT_ITER, 100, 0.1))
self.assertEqual(r, r2)
def test_KMeans2(self):
size = 500
samples = cv.CreateMat(size, 1, cv.CV_32FC3)
labels = cv.CreateMat(size, 1, cv.CV_32SC1)
centers = cv.CreateMat(2, 3, cv.CV_32FC1)
cv.Zero(samples)
cv.Zero(labels)
cv.Zero(centers)
cv.Set(cv.GetSubRect(samples, (0, 0, 1, size/2)), (255, 255, 255))
compact = cv.KMeans2(samples, 2, labels, (cv.CV_TERMCRIT_ITER, 100, 0.1), 1, 0, centers)
self.assertEqual(int(compact), 0)
random.seed(0)
for i in range(50):
index = random.randrange(size)
if index < size/2:
self.assertEqual(samples[index, 0], (255, 255, 255))
self.assertEqual(labels[index, 0], 1)
else:
self.assertEqual(samples[index, 0], (0, 0, 0))
self.assertEqual(labels[index, 0], 0)
for cluster in (0, 1):
for channel in (0, 1, 2):
self.assertEqual(int(centers[cluster, channel]), cluster*255)
def test_Sum(self):
for r in range(1,11):
for c in range(1, 11):
for t in self.mat_types_single:
M = cv.CreateMat(r, c, t)
cv.Set(M, 1)
self.assertEqual(cv.Sum(M)[0], r * c)
def test_Threshold(self):
#""" directed test for bug 2790622 """
src = self.get_sample("samples/c/lena.jpg", 0)
results = set()
for i in range(10):
dst = cv.CreateImage(cv.GetSize(src), cv.IPL_DEPTH_8U, 1)
cv.Threshold(src, dst, 128, 128, cv.CV_THRESH_BINARY)
results.add(dst.tostring())
# 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):
""" Needed by HoughLines tests """
src = self.get_sample("doc/pics/building.jpg", 0)
dst = cv.CreateImage(cv.GetSize(src), 8, 1)
cv.Canny(src, dst, 50, 200, 3)
return dst
# Tests for functional areas
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).astype(numpy.float32)
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)))
# create arrays, use them in OpenCV and replace the the array
# looking for leaks
def randdim():
return [random.randrange(1,6) for i in range(random.randrange(1, 6))]
arrays = [numpy.ones(randdim()).astype(numpy.uint8) for i in range(10)]
cs = [cv.fromarray(a, True) for a in arrays]
for i in range(1000):
arrays[random.randrange(10)] = numpy.ones(randdim()).astype(numpy.uint8)
cs[random.randrange(10)] = cv.fromarray(arrays[random.randrange(10)], True)
for j in range(10):
self.assert_(all([c == chr(1) for c in cs[j].tostring()]))
#
m = numpy.identity(4, dtype = numpy.float32)
rvec = cv.CreateMat(3, 1, cv.CV_32FC1)
rvec[0,0] = 1
rvec[1,0] = 1
rvec[2,0] = 1
cv.Rodrigues2(rvec, m[:3,:3])
#print m
else:
print "SKIPPING test_numpy - numpy support not built"
def test_boundscatch(self):
l2 = cv.CreateMat(256, 1, cv.CV_8U)
l2[0,0] # should be OK
self.assertRaises(cv.error, lambda: l2[1,1])
l2[0] # should be OK
self.assertRaises(cv.error, lambda: l2[299])
for n in range(1, 8):
l = cv.CreateMatND([2] * n, cv.CV_8U)
l[0] # should be OK
self.assertRaises(cv.error, lambda: l[999])
tup0 = (0,) * n
l[tup0] # should be OK
tup2 = (2,) * n
self.assertRaises(cv.error, lambda: l[tup2])
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)
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)
self.assertRaises(cv.error, lambda: cv.Laplace(a, b))
def test_cvmat_accessors(self):
cvm = cv.CreateMat(20, 10, cv.CV_32FC1)
def test_depths(self):
#""" Make sure that the depth enums are unique """
self.assert_(len(self.depths) == len(set(self.depths)))
def test_leak(self):
#""" If CreateImage is not releasing image storage, then the loop below should use ~4GB of memory. """
for i in range(64000):
a = cv.CreateImage((1024,1024), cv.IPL_DEPTH_8U, 1)
for i in range(64000):
a = cv.CreateMat(1024, 1024, cv.CV_8UC1)
def test_histograms(self):
def split(im):
nchans = cv.CV_MAT_CN(cv.GetElemType(im))
c = [ cv.CreateImage(cv.GetSize(im), cv.IPL_DEPTH_8U, 1) for i in range(nchans) ] + [None] * (4 - nchans)
cv.Split(im, c[0], c[1], c[2], c[3])
return c[:nchans]
def imh(im):
s = split(im)
hist = cv.CreateHist([256] * len(s), cv.CV_HIST_ARRAY, [ (0,255) ] * len(s), 1)
cv.CalcHist(s, hist, 0)
return hist
dims = [180]
ranges = [(0,180)]
a = cv.CreateHist(dims, cv.CV_HIST_ARRAY , ranges, 1)
src = self.get_sample("samples/c/lena.jpg", 0)
h = imh(src)
(minv, maxv, minl, maxl) = cv.GetMinMaxHistValue(h)
self.assert_(cv.QueryHistValue_nD(h, minl) == minv)
self.assert_(cv.QueryHistValue_nD(h, maxl) == maxv)
bp = cv.CreateImage(cv.GetSize(src), cv.IPL_DEPTH_8U, 1)
cv.CalcBackProject(split(src), bp, h)
bp = cv.CreateImage((cv.GetSize(src)[0]-2, cv.GetSize(src)[1]-2), cv.IPL_DEPTH_32F, 1)
cv.CalcBackProjectPatch(split(src), bp, (3,3), h, cv.CV_COMP_INTERSECT, 1)
for meth,expected in [(cv.CV_COMP_CORREL, 1.0), (cv.CV_COMP_CHISQR, 0.0), (cv.CV_COMP_INTERSECT, 1.0), (cv.CV_COMP_BHATTACHARYYA, 0.0)]:
self.assertEqual(cv.CompareHist(h, h, meth), expected)
def test_arithmetic(self):
a = cv.CreateMat(4, 4, cv.CV_8UC1)
a[0,0] = 50.0
b = cv.CreateMat(4, 4, cv.CV_8UC1)
b[0,0] = 4.0
d = cv.CreateMat(4, 4, cv.CV_8UC1)
cv.Add(a, b, d)
self.assertEqual(d[0,0], 54.0)
cv.Mul(a, b, d)
self.assertEqual(d[0,0], 200.0)
def failing_test_cvtcolor(self):
src3 = self.get_sample("samples/c/lena.jpg")
src1 = self.get_sample("samples/c/lena.jpg", 0)
dst8u = dict([(c,cv.CreateImage(cv.GetSize(src1), cv.IPL_DEPTH_8U, c)) for c in (1,2,3,4)])
dst16u = dict([(c,cv.CreateImage(cv.GetSize(src1), cv.IPL_DEPTH_16U, c)) for c in (1,2,3,4)])
dst32f = dict([(c,cv.CreateImage(cv.GetSize(src1), cv.IPL_DEPTH_32F, c)) for c in (1,2,3,4)])
for srcf in ["BGR", "RGB"]:
for dstf in ["Luv"]:
cv.CvtColor(src3, dst8u[3], eval("cv.CV_%s2%s" % (srcf, dstf)))
cv.CvtColor(src3, dst32f[3], eval("cv.CV_%s2%s" % (srcf, dstf)))
cv.CvtColor(src3, dst8u[3], eval("cv.CV_%s2%s" % (dstf, srcf)))
for srcf in ["BayerBG", "BayerGB", "BayerGR"]:
for dstf in ["RGB", "BGR"]:
cv.CvtColor(src1, dst8u[3], eval("cv.CV_%s2%s" % (srcf, dstf)))
def test_voronoi(self):
w,h = 500,500
storage = cv.CreateMemStorage(0)
def facet_edges(e0):
e = e0
while True:
e = cv.Subdiv2DGetEdge(e, cv.CV_NEXT_AROUND_LEFT)
yield e
if e == e0:
break
def areas(edges):
seen = []
seensorted = []
for edge in edges:
pts = [ cv.Subdiv2DEdgeOrg(e) for e in facet_edges(edge) ]
if not (None in pts):
l = [p.pt for p in pts]
ls = sorted(l)
if not(ls in seensorted):
seen.append(l)
seensorted.append(ls)
return seen
for npoints in range(1, 200):
points = [ (random.randrange(w), random.randrange(h)) for i in range(npoints) ]
subdiv = cv.CreateSubdivDelaunay2D( (0,0,w,h), storage )
for p in points:
cv.SubdivDelaunay2DInsert( subdiv, p)
cv.CalcSubdivVoronoi2D(subdiv)
ars = areas([ cv.Subdiv2DRotateEdge(e, 1) for e in subdiv.edges ] + [ cv.Subdiv2DRotateEdge(e, 3) for e in subdiv.edges ])
self.assert_(len(ars) == len(set(points)))
if False:
img = cv.CreateImage((w,h), cv.IPL_DEPTH_8U, 3)
cv.SetZero(img)
def T(x): return int(x) # int(300+x/16)
for pts in ars:
cv.FillConvexPoly( img, [(T(x),T(y)) for (x,y) in pts], cv.RGB(100+random.randrange(156),random.randrange(256),random.randrange(256)), cv.CV_AA, 0 );
for x,y in points:
cv.Circle(img, (T(x), T(y)), 3, cv.RGB(0,0,0), -1)
cv.ShowImage("snap", img)
if cv.WaitKey(10) > 0:
break
def perf_test_pow(self):
mt = cv.CreateMat(1000, 1000, cv.CV_32FC1)
dst = cv.CreateMat(1000, 1000, cv.CV_32FC1)
rng = cv.RNG(0)
cv.RandArr(rng, mt, cv.CV_RAND_UNI, 0, 1000.0)
mt[0,0] = 10
print
for a in [0.5, 2.0, 2.3, 2.4, 3.0, 37.1786] + [2.4]*10:
started = time.time()
for i in range(10):
cv.Pow(mt, dst, a)
took = (time.time() - started) / 1e7
print "%4.1f took %f ns" % (a, took * 1e9)
print dst[0,0], 10 ** 2.4
def test_access_row_col(self):
src = cv.CreateImage((8,3), 8, 1)
# Put these words
# Achilles
# Benedict
# Congreve
# in an array (3 rows, 8 columns).
# Then extract the array in various ways.
for r,w in enumerate(("Achilles", "Benedict", "Congreve")):
for c,v in enumerate(w):
src[r,c] = ord(v)
self.assertEqual(src.tostring(), "AchillesBenedictCongreve")
self.assertEqual(src[:,:].tostring(), "AchillesBenedictCongreve")
self.assertEqual(src[:,:4].tostring(), "AchiBeneCong")
self.assertEqual(src[:,0].tostring(), "ABC")
self.assertEqual(src[:,4:].tostring(), "llesdictreve")
self.assertEqual(src[::2,:].tostring(), "AchillesCongreve")
self.assertEqual(src[1:,:].tostring(), "BenedictCongreve")
self.assertEqual(src[1:2,:].tostring(), "Benedict")
self.assertEqual(src[::2,:4].tostring(), "AchiCong")
# The mats share the same storage, so updating one should update them all
lastword = src[2]
self.assertEqual(lastword.tostring(), "Congreve")
src[2,0] = ord('K')
self.assertEqual(lastword.tostring(), "Kongreve")
src[2,0] = ord('C')
# ABCD
# EFGH
# IJKL
#
# MNOP
# QRST
# UVWX
mt = cv.CreateMatND([2,3,4], cv.CV_8UC1)
for i in range(2):
for j in range(3):
for k in range(4):
mt[i,j,k] = ord('A') + k + 4 * (j + 3 * i)
self.assertEqual(mt[:,:,:1].tostring(), "AEIMQU")
self.assertEqual(mt[:,:1,:].tostring(), "ABCDMNOP")
self.assertEqual(mt[:1,:,:].tostring(), "ABCDEFGHIJKL")
self.assertEqual(mt[1,1].tostring(), "QRST")
self.assertEqual(mt[:,::2,:].tostring(), "ABCDIJKLMNOPUVWX")
# Exercise explicit GetRows
self.assertEqual(cv.GetRows(src, 0, 3).tostring(), "AchillesBenedictCongreve")
self.assertEqual(cv.GetRows(src, 0, 3, 1).tostring(), "AchillesBenedictCongreve")
self.assertEqual(cv.GetRows(src, 0, 3, 2).tostring(), "AchillesCongreve")
self.assertEqual(cv.GetRow(src, 0).tostring(), "Achilles")
self.assertEqual(cv.GetCols(src, 0, 4).tostring(), "AchiBeneCong")
self.assertEqual(cv.GetCol(src, 0).tostring(), "ABC")
self.assertEqual(cv.GetCol(src, 1).tostring(), "ceo")
self.assertEqual(cv.GetDiag(src, 0).tostring(), "Aen")
# Check that matrix type is preserved by the various operators
for mt in self.mat_types:
m = cv.CreateMat(5, 3, mt)
self.assertEqual(mt, cv.GetElemType(cv.GetRows(m, 0, 2)))
self.assertEqual(mt, cv.GetElemType(cv.GetRow(m, 0)))
self.assertEqual(mt, cv.GetElemType(cv.GetCols(m, 0, 2)))
self.assertEqual(mt, cv.GetElemType(cv.GetCol(m, 0)))
self.assertEqual(mt, cv.GetElemType(cv.GetDiag(m, 0)))
self.assertEqual(mt, cv.GetElemType(m[0]))
self.assertEqual(mt, cv.GetElemType(m[::2]))
self.assertEqual(mt, cv.GetElemType(m[:,0]))
self.assertEqual(mt, cv.GetElemType(m[:,:]))
self.assertEqual(mt, cv.GetElemType(m[::2,:]))
def test_addS_3D(self):
for dim in [ [1,1,4], [2,2,3], [7,4,3] ]:
for ty,ac in [ (cv.CV_32FC1, 'f'), (cv.CV_64FC1, 'd')]:
mat = cv.CreateMatND(dim, ty)
mat2 = cv.CreateMatND(dim, ty)
for increment in [ 0, 3, -1 ]:
cv.SetData(mat, array.array(ac, range(dim[0] * dim[1] * dim[2])), 0)
cv.AddS(mat, increment, mat2)
for i in range(dim[0]):
for j in range(dim[1]):
for k in range(dim[2]):
self.assert_(mat2[i,j,k] == mat[i,j,k] + increment)
def test_buffers(self):
ar = array.array('f', [7] * (360*640))
m = cv.CreateMat(360, 640, cv.CV_32FC1)
cv.SetData(m, ar, 4 * 640)
self.assert_(m[0,0] == 7.0)
m = cv.CreateMatND((360, 640), cv.CV_32FC1)
cv.SetData(m, ar, 4 * 640)
self.assert_(m[0,0] == 7.0)
m = cv.CreateImage((640, 360), cv.IPL_DEPTH_32F, 1)
cv.SetData(m, ar, 4 * 640)
self.assert_(m[0,0] == 7.0)
def xxtest_Filters(self):
print
m = cv.CreateMat(360, 640, cv.CV_32FC1)
d = cv.CreateMat(360, 640, cv.CV_32FC1)
for k in range(3, 21, 2):
started = time.time()
for i in range(1000):
cv.Smooth(m, m, param1=k)
print k, "took", time.time() - started
def assertSame(self, a, b):
w,h = cv.GetSize(a)
d = cv.CreateMat(h, w, cv.CV_8UC1)
cv.AbsDiff(a, b, d)
self.assert_(cv.CountNonZero(d) == 0)
def test_text(self):
img = cv.CreateImage((640,40), cv.IPL_DEPTH_8U, 1)
cv.SetZero(img)
font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1)
message = "XgfooX"
cv.PutText(img, message, (320,30), font, 255)
((w,h),bl) = cv.GetTextSize(message, font)
# Find nonzero in X and Y
Xs = []
for x in range(640):
cv.SetImageROI(img, (x, 0, 1, 40))
Xs.append(cv.Sum(img)[0] > 0)
def firstlast(l):
return (l.index(True), len(l) - list(reversed(l)).index(True))
Ys = []
for y in range(40):
cv.SetImageROI(img, (0, y, 640, 1))
Ys.append(cv.Sum(img)[0] > 0)
x0,x1 = firstlast(Xs)
y0,y1 = firstlast(Ys)
actual_width = x1 - x0
actual_height = y1 - y0
# actual_width can be up to 8 pixels smaller than GetTextSize says
self.assert_(actual_width <= w)
self.assert_((w - actual_width) <= 8)
# actual_height can be up to 4 pixels smaller than GetTextSize says
self.assert_(actual_height <= (h + bl))
self.assert_(((h + bl) - actual_height) <= 4)
cv.ResetImageROI(img)
self.assert_(w != 0)
self.assert_(h != 0)
def test_sizes(self):
sizes = [ 1, 2, 3, 97, 255, 256, 257, 947 ]
for w in sizes:
for h in sizes:
# Create an IplImage
im = cv.CreateImage((w,h), cv.IPL_DEPTH_8U, 1)
cv.Set(im, 1)
self.assert_(cv.Sum(im)[0] == (w * h))
del im
# Create a CvMat
mt = cv.CreateMat(h, w, cv.CV_8UC1)
cv.Set(mt, 1)
self.assert_(cv.Sum(mt)[0] == (w * h))
random.seed(7)
for dim in range(1, cv.CV_MAX_DIM + 1):
for attempt in range(10):
dims = [ random.choice([1,1,1,1,2,3]) for i in range(dim) ]
mt = cv.CreateMatND(dims, cv.CV_8UC1)
cv.SetZero(mt)
self.assert_(cv.Sum(mt)[0] == 0)
# Set to all-ones, verify the sum
cv.Set(mt, 1)
expected = 1
for d in dims:
expected *= d
self.assert_(cv.Sum(mt)[0] == expected)
def test_random(self):
seeds = [ 0, 1, 2**48, 2**48 + 1 ]
sequences = set()
for s in seeds:
rng = cv.RNG(s)
sequences.add(str([cv.RandInt(rng) for i in range(10)]))
self.assert_(len(seeds) == len(sequences))
rng = cv.RNG(0)
im = cv.CreateImage((1024,1024), cv.IPL_DEPTH_8U, 1)
cv.RandArr(rng, im, cv.CV_RAND_UNI, 0, 256)
cv.RandArr(rng, im, cv.CV_RAND_NORMAL, 128, 30)
if 1:
hist = cv.CreateHist([ 256 ], cv.CV_HIST_ARRAY, [ (0,255) ], 1)
cv.CalcHist([im], hist)
rng = cv.RNG()
for i in range(1000):
v = cv.RandReal(rng)
self.assert_(0 <= v)
self.assert_(v < 1)
for mode in [ cv.CV_RAND_UNI, cv.CV_RAND_NORMAL ]:
for fmt in self.mat_types:
mat = cv.CreateMat(64, 64, fmt)
cv.RandArr(cv.RNG(), mat, mode, (0,0,0,0), (1,1,1,1))
def test_MixChannels(self):
# First part - test the single case described in the documentation
rgba = cv.CreateMat(100, 100, cv.CV_8UC4)
bgr = cv.CreateMat(100, 100, cv.CV_8UC3)
alpha = cv.CreateMat(100, 100, cv.CV_8UC1)
cv.Set(rgba, (1,2,3,4))
cv.MixChannels([rgba], [bgr, alpha], [
(0, 2), # rgba[0] -> bgr[2]
(1, 1), # rgba[1] -> bgr[1]
(2, 0), # rgba[2] -> bgr[0]
(3, 3) # rgba[3] -> alpha[0]
])
self.assert_(bgr[0,0] == (3,2,1))
self.assert_(alpha[0,0] == 4)
# Second part. Choose random sets of sources and destinations,
# fill them with known values, choose random channel assignments,
# run cvMixChannels and check that the result is as expected.
random.seed(1)
for rows in [1,2,4,13,64,1000]:
for cols in [1,2,4,13,64,1000]:
for loop in range(5):
sources = [random.choice([1, 2, 3, 4]) for i in range(8)]
dests = [random.choice([1, 2, 3, 4]) for i in range(8)]
# make sure that fromTo does not have duplicates in dests, otherwise the result is not determined
while 1:
fromTo = [(random.randrange(-1, sum(sources)), random.randrange(sum(dests))) for i in range(random.randrange(1, 30))]
dests_set = list(set([j for (i, j) in fromTo]))
if len(dests_set) == len(dests):
break
# print sources
# print dests
# print fromTo
def CV_8UC(n):
return [cv.CV_8UC1, cv.CV_8UC2, cv.CV_8UC3, cv.CV_8UC4][n-1]
source_m = [cv.CreateMat(rows, cols, CV_8UC(c)) for c in sources]
dest_m = [cv.CreateMat(rows, cols, CV_8UC(c)) for c in dests]
def m00(m):
# return the contents of the N channel mat m[0,0] as a N-length list
chans = cv.CV_MAT_CN(cv.GetElemType(m))
if chans == 1:
return [m[0,0]]
else:
return list(m[0,0])[:chans]
# Sources numbered from 50, destinations numbered from 100
for i in range(len(sources)):
s = sum(sources[:i]) + 50
cv.Set(source_m[i], (s, s+1, s+2, s+3))
self.assertEqual(m00(source_m[i]), [s, s+1, s+2, s+3][:sources[i]])
for i in range(len(dests)):
s = sum(dests[:i]) + 100
cv.Set(dest_m[i], (s, s+1, s+2, s+3))
self.assertEqual(m00(dest_m[i]), [s, s+1, s+2, s+3][:dests[i]])
# now run the sanity check
for i in range(len(sources)):
s = sum(sources[:i]) + 50
self.assertEqual(m00(source_m[i]), [s, s+1, s+2, s+3][:sources[i]])
for i in range(len(dests)):
s = sum(dests[:i]) + 100
self.assertEqual(m00(dest_m[i]), [s, s+1, s+2, s+3][:dests[i]])
cv.MixChannels(source_m, dest_m, fromTo)
expected = range(100, 100 + sum(dests))
for (i, j) in fromTo:
if i == -1:
expected[j] = 0.0
else:
expected[j] = 50 + i
actual = sum([m00(m) for m in dest_m], [])
self.assertEqual(sum([m00(m) for m in dest_m], []), expected)
def test_allocs(self):
mats = [ 0 for i in range(20) ]
for i in range(1000):
m = cv.CreateMat(random.randrange(10, 512), random.randrange(10, 512), cv.CV_8UC1)
j = random.randrange(len(mats))
mats[j] = m
cv.SetZero(m)
def test_access(self):
cnames = { 1:cv.CV_32FC1, 2:cv.CV_32FC2, 3:cv.CV_32FC3, 4:cv.CV_32FC4 }
for w in range(1,11):
for h in range(2,11):
for c in [1,2]:
for o in [ cv.CreateMat(h, w, cnames[c]), cv.CreateImage((w,h), cv.IPL_DEPTH_32F, c) ][1:]:
pattern = [ (i,j) for i in range(w) for j in range(h) ]
random.shuffle(pattern)
for k,(i,j) in enumerate(pattern):
if c == 1:
o[j,i] = k
else:
o[j,i] = (k,) * c
for k,(i,j) in enumerate(pattern):
if c == 1:
self.assert_(o[j,i] == k)
else:
self.assert_(o[j,i] == (k,)*c)
test_mat = cv.CreateMat(2, 3, cv.CV_32FC1)
cv.SetData(test_mat, array.array('f', range(6)), 12)
self.assertEqual(cv.GetDims(test_mat[0]), (1, 3))
self.assertEqual(cv.GetDims(test_mat[1]), (1, 3))
self.assertEqual(cv.GetDims(test_mat[0:1]), (1, 3))
self.assertEqual(cv.GetDims(test_mat[1:2]), (1, 3))
self.assertEqual(cv.GetDims(test_mat[-1:]), (1, 3))
self.assertEqual(cv.GetDims(test_mat[-1]), (1, 3))
def xxxtest_corners(self):
a = cv.LoadImage("foo-mono.png", 0)
cv.AdaptiveThreshold(a, a, 255, param1=5)
scribble = cv.CreateImage(cv.GetSize(a), 8, 3)
cv.CvtColor(a, scribble, cv.CV_GRAY2BGR)
if 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)
for p in pts:
cv.Circle( scribble, p, 1, cv.RGB(255,0,0), -1 )
self.snap(scribble)
canny = cv.CreateImage(cv.GetSize(a), 8, 1)
cv.SubRS(a, 255, canny)
self.snap(canny)
li = cv.HoughLines2(canny,
cv.CreateMemStorage(),
cv.CV_HOUGH_STANDARD,
1,
math.pi/180,
60,
0,
0)
for (rho,theta) in li:
print rho,theta
c = math.cos(theta)
s = math.sin(theta)
x0 = c*rho
y0 = s*rho
cv.Line(scribble,
(x0 + 1000*(-s), y0 + 1000*c),
(x0 + -1000*(-s), y0 - 1000*c),
(0,255,0))
self.snap(scribble)
def test_calibration(self):
def get_corners(mono, refine = False):
(ok, corners) = cv.FindChessboardCorners(mono, (num_x_ints, num_y_ints), cv.CV_CALIB_CB_ADAPTIVE_THRESH | cv.CV_CALIB_CB_NORMALIZE_IMAGE)
if refine and ok:
corners = cv.FindCornerSubPix(mono, corners, (5,5), (-1,-1), ( cv.CV_TERMCRIT_EPS+cv.CV_TERMCRIT_ITER, 30, 0.1 ))
return (ok, corners)
def mk_object_points(nimages, squaresize = 1):
opts = cv.CreateMat(nimages * num_pts, 3, cv.CV_32FC1)
for i in range(nimages):
for j in range(num_pts):
opts[i * num_pts + j, 0] = (j / num_x_ints) * squaresize
opts[i * num_pts + j, 1] = (j % num_x_ints) * squaresize
opts[i * num_pts + j, 2] = 0
return opts
def mk_image_points(goodcorners):
ipts = cv.CreateMat(len(goodcorners) * num_pts, 2, cv.CV_32FC1)
for (i, co) in enumerate(goodcorners):
for j in range(num_pts):
ipts[i * num_pts + j, 0] = co[j][0]
ipts[i * num_pts + j, 1] = co[j][1]
return ipts
def mk_point_counts(nimages):
npts = cv.CreateMat(nimages, 1, cv.CV_32SC1)
for i in range(nimages):
npts[i, 0] = num_pts
return npts
def cvmat_iterator(cvmat):
for i in range(cvmat.rows):
for j in range(cvmat.cols):
yield cvmat[i,j]
def image_from_archive(tar, name):
member = tar.getmember(name)
filedata = tar.extractfile(member).read()
imagefiledata = cv.CreateMat(1, len(filedata), cv.CV_8UC1)
cv.SetData(imagefiledata, filedata, len(filedata))
return cv.DecodeImageM(imagefiledata)
urllib.urlretrieve("http://pr.willowgarage.com/data/camera_calibration/camera_calibration.tar.gz", "camera_calibration.tar.gz")
tf = tarfile.open("camera_calibration.tar.gz")
num_x_ints = 8
num_y_ints = 6
num_pts = num_x_ints * num_y_ints
leftimages = [image_from_archive(tf, "wide/left%04d.pgm" % i) for i in range(3, 15)]
size = cv.GetSize(leftimages[0])
# Monocular test
if True:
corners = [get_corners(i) for i in leftimages]
goodcorners = [co for (im, (ok, co)) in zip(leftimages, corners) if ok]
ipts = mk_image_points(goodcorners)
opts = mk_object_points(len(goodcorners), .1)
npts = mk_point_counts(len(goodcorners))
intrinsics = cv.CreateMat(3, 3, cv.CV_64FC1)
distortion = cv.CreateMat(4, 1, cv.CV_64FC1)
cv.SetZero(intrinsics)
cv.SetZero(distortion)
# focal lengths have 1/1 ratio
intrinsics[0,0] = 1.0
intrinsics[1,1] = 1.0
cv.CalibrateCamera2(opts, ipts, npts,
cv.GetSize(leftimages[0]),
intrinsics,
distortion,
cv.CreateMat(len(goodcorners), 3, cv.CV_32FC1),
cv.CreateMat(len(goodcorners), 3, cv.CV_32FC1),
flags = 0) # cv.CV_CALIB_ZERO_TANGENT_DIST)
# print "D =", list(cvmat_iterator(distortion))
# print "K =", list(cvmat_iterator(intrinsics))
newK = cv.CreateMat(3, 3, cv.CV_64FC1)
cv.GetOptimalNewCameraMatrix(intrinsics, distortion, size, 1.0, newK)
# print "newK =", list(cvmat_iterator(newK))
mapx = cv.CreateImage((640, 480), cv.IPL_DEPTH_32F, 1)
mapy = cv.CreateImage((640, 480), cv.IPL_DEPTH_32F, 1)
for K in [ intrinsics, newK ]:
cv.InitUndistortMap(K, distortion, mapx, mapy)
for img in leftimages[:1]:
r = cv.CloneMat(img)
cv.Remap(img, r, mapx, mapy)
# cv.ShowImage("snap", r)
# cv.WaitKey()
rightimages = [image_from_archive(tf, "wide/right%04d.pgm" % i) for i in range(3, 15)]
# Stereo test
if True:
lcorners = [get_corners(i) for i in leftimages]
rcorners = [get_corners(i) for i in rightimages]
good = [(lco, rco) for ((lok, lco), (rok, rco)) in zip(lcorners, rcorners) if (lok and rok)]
lipts = mk_image_points([l for (l, r) in good])
ripts = mk_image_points([r for (l, r) in good])
opts = mk_object_points(len(good), .108)
npts = mk_point_counts(len(good))
flags = cv.CV_CALIB_FIX_ASPECT_RATIO | cv.CV_CALIB_FIX_INTRINSIC
flags = cv.CV_CALIB_SAME_FOCAL_LENGTH + cv.CV_CALIB_FIX_PRINCIPAL_POINT + cv.CV_CALIB_ZERO_TANGENT_DIST
flags = 0
T = cv.CreateMat(3, 1, cv.CV_64FC1)
R = cv.CreateMat(3, 3, cv.CV_64FC1)
lintrinsics = cv.CreateMat(3, 3, cv.CV_64FC1)
ldistortion = cv.CreateMat(4, 1, cv.CV_64FC1)
rintrinsics = cv.CreateMat(3, 3, cv.CV_64FC1)
rdistortion = cv.CreateMat(4, 1, cv.CV_64FC1)
lR = cv.CreateMat(3, 3, cv.CV_64FC1)
rR = cv.CreateMat(3, 3, cv.CV_64FC1)
lP = cv.CreateMat(3, 4, cv.CV_64FC1)
rP = cv.CreateMat(3, 4, cv.CV_64FC1)
lmapx = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
lmapy = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
rmapx = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
rmapy = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
cv.SetIdentity(lintrinsics)
cv.SetIdentity(rintrinsics)
lintrinsics[0,2] = size[0] * 0.5
lintrinsics[1,2] = size[1] * 0.5
rintrinsics[0,2] = size[0] * 0.5
rintrinsics[1,2] = size[1] * 0.5
cv.SetZero(ldistortion)
cv.SetZero(rdistortion)
cv.StereoCalibrate(opts, lipts, ripts, npts,
lintrinsics, ldistortion,
rintrinsics, rdistortion,
size,
R, # R
T, # T
cv.CreateMat(3, 3, cv.CV_32FC1), # E
cv.CreateMat(3, 3, cv.CV_32FC1), # F
(cv.CV_TERMCRIT_ITER + cv.CV_TERMCRIT_EPS, 30, 1e-5),
flags)
for a in [-1, 0, 1]:
cv.StereoRectify(lintrinsics,
rintrinsics,
ldistortion,
rdistortion,
size,
R,
T,
lR, rR, lP, rP,
alpha = a)
cv.InitUndistortRectifyMap(lintrinsics, ldistortion, lR, lP, lmapx, lmapy)
cv.InitUndistortRectifyMap(rintrinsics, rdistortion, rR, rP, rmapx, rmapy)
for l,r in zip(leftimages, rightimages)[:1]:
l_ = cv.CloneMat(l)
r_ = cv.CloneMat(r)
cv.Remap(l, l_, lmapx, lmapy)
cv.Remap(r, r_, rmapx, rmapy)
# cv.ShowImage("snap", l_)
# cv.WaitKey()
def xxx_test_Disparity(self):
print
for t in ["8U", "8S", "16U", "16S", "32S", "32F", "64F" ]:
for c in [1,2,3,4]:
nm = "%sC%d" % (t, c)
print "int32 CV_%s=%d" % (nm, eval("cv.CV_%s" % nm))
return
integral = cv.CreateImage((641,481), cv.IPL_DEPTH_32S, 1)
L = cv.LoadImage("f0-left.png", 0)
R = cv.LoadImage("f0-right.png", 0)
d = cv.CreateImage(cv.GetSize(L), cv.IPL_DEPTH_8U, 1)
Rn = cv.CreateImage(cv.GetSize(L), cv.IPL_DEPTH_8U, 1)
started = time.time()
for i in range(100):
cv.AbsDiff(L, R, d)
cv.Integral(d, integral)
cv.SetImageROI(R, (1, 1, 639, 479))
cv.SetImageROI(Rn, (0, 0, 639, 479))
cv.Copy(R, Rn)
R = Rn
cv.ResetImageROI(R)
print 1e3 * (time.time() - started) / 100, "ms"
# self.snap(d)
def local_test_lk(self):
seq = [cv.LoadImage("track/%06d.png" % i, 0) for i in range(40)]
crit = (cv.CV_TERMCRIT_ITER, 100, 0.1)
crit = (cv.CV_TERMCRIT_EPS, 0, 0.001)
for i in range(1,40):
r = cv.CalcOpticalFlowPyrLK(seq[0], seq[i], None, None, [(32,32)], (7,7), 0, crit, 0)
pos = r[0][0]
#print pos, r[2]
a = cv.CreateImage((1024,1024), 8, 1)
b = cv.CreateImage((1024,1024), 8, 1)
cv.Resize(seq[0], a, cv.CV_INTER_NN)
cv.Resize(seq[i], b, cv.CV_INTER_NN)
cv.Line(a, (0, 512), (1024, 512), 255)
cv.Line(a, (512,0), (512,1024), 255)
x,y = [int(c) for c in pos]
cv.Line(b, (0, y*16), (1024, y*16), 255)
cv.Line(b, (x*16,0), (x*16,1024), 255)
#self.snapL([a,b])
def local_test_Haar(self):
import os
hcfile = os.environ['OPENCV_ROOT'] + '/share/opencv/haarcascades/haarcascade_frontalface_default.xml'
hc = cv.Load(hcfile)
img = cv.LoadImage('Stu.jpg', 0)
faces = cv.HaarDetectObjects(img, hc, cv.CreateMemStorage())
self.assert_(len(faces) > 0)
for (x,y,w,h),n in faces:
cv.Rectangle(img, (x,y), (x+w,y+h), 255)
#self.snap(img)
def test_create(self):
#""" CvCreateImage, CvCreateMat and the header-only form """
for (w,h) in [ (320,400), (640,480), (1024, 768) ]:
data = "z" * (w * h)
im = cv.CreateImage((w,h), 8, 1)
cv.SetData(im, data, w)
im2 = cv.CreateImageHeader((w,h), 8, 1)
cv.SetData(im2, data, w)
self.assertSame(im, im2)
m = cv.CreateMat(h, w, cv.CV_8UC1)
cv.SetData(m, data, w)
m2 = cv.CreateMatHeader(h, w, cv.CV_8UC1)
cv.SetData(m2, data, w)
self.assertSame(m, m2)
self.assertSame(im, m)
self.assertSame(im2, m2)
def test_casts(self):
im = cv.GetImage(self.get_sample("samples/c/lena.jpg", 0))
data = im.tostring()
cv.SetData(im, data, cv.GetSize(im)[0])
start_count = sys.getrefcount(data)
# Conversions should produce same data
self.assertSame(im, cv.GetImage(im))
m = cv.GetMat(im)
self.assertSame(im, m)
self.assertSame(m, cv.GetImage(m))
im2 = cv.GetImage(m)
self.assertSame(im, im2)
self.assertEqual(sys.getrefcount(data), start_count + 2)
del im2
self.assertEqual(sys.getrefcount(data), start_count + 1)
del m
self.assertEqual(sys.getrefcount(data), start_count)
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))
if 0: # XXX - ticket #149
# 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)
def test_smoke_image_processing(self):
src = self.get_sample("samples/c/lena.jpg", cv.CV_LOAD_IMAGE_GRAYSCALE)
#dst = cv.CloneImage(src)
for aperture_size in [1, 3, 5, 7]:
dst_16s = cv.CreateImage(cv.GetSize(src), cv.IPL_DEPTH_16S, 1)
dst_32f = cv.CreateImage(cv.GetSize(src), cv.IPL_DEPTH_32F, 1)
cv.Sobel(src, dst_16s, 1, 1, aperture_size)
cv.Laplace(src, dst_16s, aperture_size)
cv.PreCornerDetect(src, dst_32f)
eigendst = cv.CreateImage((6*cv.GetSize(src)[0], cv.GetSize(src)[1]), cv.IPL_DEPTH_32F, 1)
cv.CornerEigenValsAndVecs(src, eigendst, 8, aperture_size)
cv.CornerMinEigenVal(src, dst_32f, 8, aperture_size)
cv.CornerHarris(src, dst_32f, 8, aperture_size)
cv.CornerHarris(src, dst_32f, 8, aperture_size, 0.1)
#self.snap(dst)
def test_fitline(self):
cv.FitLine([ (1,1), (10,10) ], cv.CV_DIST_L2, 0, 0.01, 0.01)
cv.FitLine([ (1,1,1), (10,10,10) ], cv.CV_DIST_L2, 0, 0.01, 0.01)
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, useHarris=1)
hull = cv.ConvexHull2(pts, cv.CreateMemStorage(), return_points = 1)
cv.FitLine(hull, cv.CV_DIST_L2, 0, 0.01, 0.01)
def test_moments(self):
im = self.get_sample("samples/c/lena.jpg", 0)
mo = cv.Moments(im)
for fld in ["m00", "m10", "m01", "m20", "m11", "m02", "m30", "m21", "m12", "m03", "mu20", "mu11", "mu02", "mu30", "mu21", "mu12", "mu03", "inv_sqrt_m00"]:
self.assert_(isinstance(getattr(mo, fld), float))
x = getattr(mo, fld)
self.assert_(isinstance(x, float))
orders = []
for x_order in range(4):
for y_order in range(4 - x_order):
orders.append((x_order, y_order))
# Just a smoke test for these three functions
[ cv.GetSpatialMoment(mo, xo, yo) for (xo,yo) in orders ]
[ cv.GetCentralMoment(mo, xo, yo) for (xo,yo) in orders ]
[ cv.GetNormalizedCentralMoment(mo, xo, yo) for (xo,yo) in orders ]
# Hu Moments we can do slightly better. Check that the first
# six are invariant wrt image reflection, and that the 7th
# is negated.
hu0 = cv.GetHuMoments(cv.Moments(im))
cv.Flip(im, im, 1)
hu1 = cv.GetHuMoments(cv.Moments(im))
self.assert_(len(hu0) == 7)
self.assert_(len(hu1) == 7)
for i in range(5):
self.assert_(abs(hu0[i] - hu1[i]) < 1e-6)
self.assert_(abs(hu0[i] + hu1[i]) < 1e-6)
def test_encode(self):
im = self.get_sample("samples/c/lena.jpg", 1)
jpeg = cv.EncodeImage(".jpeg", im)
# Smoke jpeg compression at various qualities
sizes = dict([(qual, cv.EncodeImage(".jpeg", im, [cv.CV_IMWRITE_JPEG_QUALITY, qual]).cols) for qual in range(5, 100, 5)])
# Check that the default QUALITY is 95
self.assertEqual(cv.EncodeImage(".jpeg", im).cols, sizes[95])
# Check that the 'round-trip' gives an image of the same size
round_trip = cv.DecodeImage(cv.EncodeImage(".jpeg", im, [cv.CV_IMWRITE_JPEG_QUALITY, 10]))
self.assert_(cv.GetSize(round_trip) == cv.GetSize(im))
def test_reduce(self):
srcmat = cv.CreateMat(2, 3, cv.CV_32FC1)
# 0 1 2
# 3 4 5
srcmat[0,0] = 0
srcmat[0,1] = 1
srcmat[0,2] = 2
srcmat[1,0] = 3
srcmat[1,1] = 4
srcmat[1,2] = 5
def doreduce(siz, rfunc):
dst = cv.CreateMat(siz[0], siz[1], cv.CV_32FC1)
rfunc(dst)
if siz[0] != 1:
return [dst[i,0] for i in range(siz[0])]
else:
return [dst[0,i] for i in range(siz[1])]
# exercise dim
self.assertEqual(doreduce((1,3), lambda dst: cv.Reduce(srcmat, dst)), [3, 5, 7])
self.assertEqual(doreduce((1,3), lambda dst: cv.Reduce(srcmat, dst, -1)), [3, 5, 7])
self.assertEqual(doreduce((1,3), lambda dst: cv.Reduce(srcmat, dst, 0)), [3, 5, 7])
self.assertEqual(doreduce((2,1), lambda dst: cv.Reduce(srcmat, dst, 1)), [3, 12])
# exercise op
self.assertEqual(doreduce((1,3), lambda dst: cv.Reduce(srcmat, dst, op = cv.CV_REDUCE_SUM)), [3, 5, 7])
self.assertEqual(doreduce((1,3), lambda dst: cv.Reduce(srcmat, dst, op = cv.CV_REDUCE_AVG)), [1.5, 2.5, 3.5])
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:
def __init__(self, data = None):
self.m = cv.CreateMat(1, 32, cv.CV_32FC1)
if data:
cv.SetData(self.m, array.array('f', data), 128)
def __add__(self, other):
r = Im()
if isinstance(other, Im):
cv.Add(self.m, other.m, r.m)
else:
cv.AddS(self.m, (other,), r.m)
return r
def __sub__(self, other):
r = Im()
if isinstance(other, Im):
cv.Sub(self.m, other.m, r.m)
else:
cv.SubS(self.m, (other,), r.m)
return r
def __rsub__(self, other):
r = Im()
cv.SubRS(self.m, (other,), r.m)
return r
def __mul__(self, other):
r = Im()
if isinstance(other, Im):
cv.Mul(self.m, other.m, r.m)
else:
cv.ConvertScale(self.m, r.m, other)
return r
def __rmul__(self, other):
r = Im()
cv.ConvertScale(self.m, r.m, other)
return r
def __div__(self, other):
r = Im()
if isinstance(other, Im):
cv.Div(self.m, other.m, r.m)
else:
cv.ConvertScale(self.m, r.m, 1.0 / other)
return r
def __pow__(self, other):
r = Im()
cv.Pow(self.m, r.m, other)
return r
def __abs__(self):
r = Im()
cv.Abs(self.m, r.m)
return r
def __getitem__(self, i):
return self.m[0,i]
def verify(op):
r = op(a, b)
for i in range(32):
expected = op(a[i], b[i])
self.assertAlmostEqual(expected, r[i], 4)
a = Im([random.randrange(1, 256) for i in range(32)])
b = Im([random.randrange(1, 256) for i in range(32)])
# simple operations first
verify(lambda x, y: x + y)
verify(lambda x, y: x + 3)
verify(lambda x, y: x + 0)
verify(lambda x, y: x + -8)
verify(lambda x, y: x - y)
verify(lambda x, y: x - 1)
verify(lambda x, y: 1 - x)
verify(lambda x, y: abs(x))
verify(lambda x, y: x * y)
verify(lambda x, y: x * 3)
verify(lambda x, y: x / y)
verify(lambda x, y: x / 2)
for p in [-2, -1, -0.5, -0.1, 0, 0.1, 0.5, 1, 2 ]:
verify(lambda x, y: (x ** p) + (y ** p))
# Combinations...
verify(lambda x, y: x - 4 * abs(y))
verify(lambda x, y: abs(y) / x)
# a polynomial
verify(lambda x, y: 2 * x + 3 * (y ** 0.5))
def temp_test(self):
cv.temp_test()
def failing_test_rand_GetStarKeypoints(self):
# GetStarKeypoints [<cvmat(type=4242400d rows=64 cols=64 step=512 )>, <cv.cvmemstorage object at 0xb7cc40d0>, (45, 0.73705234376883488, 0.64282591451367344, 0.1567738743689836, 3)]
print cv.CV_MAT_CN(0x4242400d)
mat = cv.CreateMat( 64, 64, cv.CV_32FC2)
cv.GetStarKeypoints(mat, cv.CreateMemStorage(), (45, 0.73705234376883488, 0.64282591451367344, 0.1567738743689836, 3))
print mat
def test_rand_PutText(self):
#""" Test for bug 2829336 """
mat = cv.CreateMat( 64, 64, cv.CV_8UC1)
font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1)
cv.PutText(mat, chr(127), (20, 20), font, 255)
def failing_test_rand_FindNearestPoint2D(self):
subdiv = cv.CreateSubdivDelaunay2D((0,0,100,100), cv.CreateMemStorage())
cv.SubdivDelaunay2DInsert( subdiv, (50, 50))
cv.CalcSubdivVoronoi2D(subdiv)
print
for e in subdiv.edges:
print e,
print " ", cv.Subdiv2DEdgeOrg(e)
print " ", cv.Subdiv2DEdgeOrg(cv.Subdiv2DRotateEdge(e, 1)), cv.Subdiv2DEdgeDst(cv.Subdiv2DRotateEdge(e, 1))
print "nearest", cv.FindNearestPoint2D(subdiv, (1.0, 1.0))
class DocumentFragmentTests(OpenCVTests):
""" Test the fragments of code that are included in the documentation """
def setUp(self):
OpenCVTests.setUp(self)
sys.path.append("../doc/python_fragments")
def test_precornerdetect(self):
from test_functions import precornerdetect
im = self.get_sample("samples/cpp/right01.jpg", 0)
imf = cv.CreateMat(im.rows, im.cols, cv.CV_32FC1)
cv.ConvertScale(im, imf)
(r0,r1) = precornerdetect(imf)
for r in (r0, r1):
self.assertEqual(im.cols, r.cols)
self.assertEqual(im.rows, r.rows)
def test_findstereocorrespondence(self):
from test_functions import findstereocorrespondence
(l,r) = [self.get_sample("doc/pics/tsukuba_%s.png" % c, cv.CV_LOAD_IMAGE_GRAYSCALE) for c in "lr"]
(disparity_left, disparity_right) = findstereocorrespondence(l, r)
disparity_left_visual = cv.CreateMat(l.rows, l.cols, cv.CV_8U)
cv.ConvertScale(disparity_left, disparity_left_visual, -16)
# self.snap(disparity_left_visual)
def test_calchist(self):
from test_functions import hs_histogram
i1 = self.get_sample("samples/c/lena.jpg")
i2 = self.get_sample("doc/pics/building.jpg")
i3 = cv.CloneMat(i1)
cv.Flip(i3, i3, 1)
h1 = hs_histogram(i1)
h2 = hs_histogram(i2)
h3 = hs_histogram(i3)
self.assertEqual(self.hashimg(h1), self.hashimg(h3))
self.assertNotEqual(self.hashimg(h1), self.hashimg(h2))
class NewTests(OpenCVTests):
pass
if __name__ == '__main__':
print "testing", cv.__version__
random.seed(0)
unittest.main()
# optlist, args = getopt.getopt(sys.argv[1:], 'l:rd')
# loops = 1
# shuffle = 0
# doc_frags = False
# for o,a in optlist:
# if o == '-l':
# loops = int(a)
# if o == '-r':
# shuffle = 1
# if o == '-d':
# doc_frags = True
#
# cases = [PreliminaryTests, FunctionTests, AreaTests]
# if doc_frags:
# cases += [DocumentFragmentTests]
# everything = [(tc, t) for tc in cases for t in unittest.TestLoader().getTestCaseNames(tc) ]
# if len(args) == 0:
# # cases = [NewTests]
# args = everything
# else:
# args = [(tc, t) for (tc, t) in everything if t in args]
#
# suite = unittest.TestSuite()
# for l in range(loops):
# if shuffle:
# random.shuffle(args)
# for tc,t in args:
# suite.addTest(tc(t))
# unittest.TextTestRunner(verbosity=2).run(suite)
import sys
import cv
def hs_histogram(src):
# Convert to HSV
hsv = cv.CreateImage(cv.GetSize(src), 8, 3)
cv.CvtColor(src, hsv, cv.CV_BGR2HSV)
# Extract the H and S planes
h_plane = cv.CreateMat(src.rows, src.cols, cv.CV_8UC1)
s_plane = cv.CreateMat(src.rows, src.cols, cv.CV_8UC1)
cv.Split(hsv, h_plane, s_plane, None, None)
planes = [h_plane, s_plane]
h_bins = 30
s_bins = 32
hist_size = [h_bins, s_bins]
# hue varies from 0 (~0 deg red) to 180 (~360 deg red again */
h_ranges = [0, 180]
# saturation varies from 0 (black-gray-white) to
# 255 (pure spectrum color)
s_ranges = [0, 255]
ranges = [h_ranges, s_ranges]
scale = 10
hist = cv.CreateHist([h_bins, s_bins], cv.CV_HIST_ARRAY, ranges, 1)
cv.CalcHist([cv.GetImage(i) for i in planes], hist)
(_, max_value, _, _) = cv.GetMinMaxHistValue(hist)
hist_img = cv.CreateImage((h_bins*scale, s_bins*scale), 8, 3)
for h in range(h_bins):
for s in range(s_bins):
bin_val = cv.QueryHistValue_2D(hist, h, s)
intensity = cv.Round(bin_val * 255 / max_value)
cv.Rectangle(hist_img,
(h*scale, s*scale),
((h+1)*scale - 1, (s+1)*scale - 1),
cv.RGB(intensity, intensity, intensity),
cv.CV_FILLED)
return hist_img
def precornerdetect(image):
# assume that the image is floating-point
corners = cv.CloneMat(image)
cv.PreCornerDetect(image, corners, 3)
dilated_corners = cv.CloneMat(image)
cv.Dilate(corners, dilated_corners, None, 1)
corner_mask = cv.CreateMat(image.rows, image.cols, cv.CV_8UC1)
cv.Sub(corners, dilated_corners, corners)
cv.CmpS(corners, 0, corner_mask, cv.CV_CMP_GE)
return (corners, corner_mask)
def findstereocorrespondence(image_left, image_right):
# image_left and image_right are the input 8-bit single-channel images
# from the left and the right cameras, respectively
(r, c) = (image_left.rows, image_left.cols)
disparity_left = cv.CreateMat(r, c, cv.CV_16S)
disparity_right = cv.CreateMat(r, c, cv.CV_16S)
state = cv.CreateStereoGCState(16, 2)
cv.FindStereoCorrespondenceGC(image_left, image_right, disparity_left, disparity_right, state, 0)
return (disparity_left, disparity_right)
import urllib
import cv
import Image
import unittest
class TestLoadImage(unittest.TestCase):
def setUp(self):
open("large.jpg", "w").write(urllib.urlopen("http://www.cs.ubc.ca/labs/lci/curious_george/img/ROS_bug_imgs/IMG_3560.jpg").read())
def test_load(self):
pilim = Image.open("large.jpg")
cvim = cv.LoadImage("large.jpg")
self.assert_(len(pilim.tostring()) == len(cvim.tostring()))
if __name__ == '__main__':
unittest.main()
import unittest
import random
import time
import math
import sys
import array
import os
import cv
def find_sample(s):
for d in ["../samples/c/", "../doc/pics/"]:
path = os.path.join(d, s)
if os.access(path, os.R_OK):
return path
return s
class TestTickets(unittest.TestCase):
def test_2542670(self):
xys = [(94, 121), (94, 122), (93, 123), (92, 123), (91, 124), (91, 125), (91, 126), (92, 127), (92, 128), (92, 129), (92, 130), (92, 131), (91, 132), (90, 131), (90, 130), (90, 131), (91, 132), (92, 133), (92, 134), (93, 135), (94, 136), (94, 137), (94, 138), (95, 139), (96, 140), (96, 141), (96, 142), (96, 143), (97, 144), (97, 145), (98, 146), (99, 146), (100, 146), (101, 146), (102, 146), (103, 146), (104, 146), (105, 146), (106, 146), (107, 146), (108, 146), (109, 146), (110, 146), (111, 146), (112, 146), (113, 146), (114, 146), (115, 146), (116, 146), (117, 146), (118, 146), (119, 146), (120, 146), (121, 146), (122, 146), (123, 146), (124, 146), (125, 146), (126, 146), (126, 145), (126, 144), (126, 143), (126, 142), (126, 141), (126, 140), (127, 139), (127, 138), (127, 137), (127, 136), (127, 135), (127, 134), (127, 133), (128, 132), (129, 132), (130, 131), (131, 130), (131, 129), (131, 128), (132, 127), (133, 126), (134, 125), (134, 124), (135, 123), (136, 122), (136, 121), (135, 121), (134, 121), (133, 121), (132, 121), (131, 121), (130, 121), (129, 121), (128, 121), (127, 121), (126, 121), (125, 121), (124, 121), (123, 121), (122, 121), (121, 121), (120, 121), (119, 121), (118, 121), (117, 121), (116, 121), (115, 121), (114, 121), (113, 121), (112, 121), (111, 121), (110, 121), (109, 121), (108, 121), (107, 121), (106, 121), (105, 121), (104, 121), (103, 121), (102, 121), (101, 121), (100, 121), (99, 121), (98, 121), (97, 121), (96, 121), (95, 121)]
#xys = xys[:12] + xys[16:]
pts = cv.CreateMat(len(xys), 1, cv.CV_32SC2)
for i,(x,y) in enumerate(xys):
pts[i,0] = (x, y)
storage = cv.CreateMemStorage()
hull = cv.ConvexHull2(pts, storage)
hullp = cv.ConvexHull2(pts, storage, return_points = 1)
defects = cv.ConvexityDefects(pts, hull, storage)
vis = cv.CreateImage((1000,1000), 8, 3)
x0 = min([x for (x,y) in xys]) - 10
x1 = max([x for (x,y) in xys]) + 10
y0 = min([y for (y,y) in xys]) - 10
y1 = max([y for (y,y) in xys]) + 10
def xform(pt):
x,y = pt
return (1000 * (x - x0) / (x1 - x0),
1000 * (y - y0) / (y1 - y0))
for d in defects[:2]:
cv.Zero(vis)
# First draw the defect as a red triangle
cv.FillConvexPoly(vis, [xform(p) for p in d[:3]], cv.RGB(255,0,0))
# Draw the convex hull as a thick green line
for a,b in zip(hullp, hullp[1:]):
cv.Line(vis, xform(a), xform(b), cv.RGB(0,128,0), 3)
# Draw the original contour as a white line
for a,b in zip(xys, xys[1:]):
cv.Line(vis, xform(a), xform(b), (255,255,255))
self.snap(vis)
def test_2686307(self):
lena = cv.LoadImage(find_sample("lena.jpg"), 1)
dst = cv.CreateImage((512,512), 8, 3)
cv.Set(dst, (128,192,255))
mask = cv.CreateImage((512,512), 8, 1)
cv.Zero(mask)
cv.Rectangle(mask, (10,10), (300,100), 255, -1)
cv.Copy(lena, dst, mask)
self.snapL([lena, dst, mask])
m = cv.CreateMat(480, 640, cv.CV_8UC1)
print "ji", m
print m.rows, m.cols, m.type, m.step
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()
if __name__ == '__main__':
random.seed(0)
if len(sys.argv) == 1:
suite = unittest.TestLoader().loadTestsFromTestCase(TestTickets)
unittest.TextTestRunner(verbosity=2).run(suite)
else:
suite = unittest.TestSuite()
suite.addTest(TestTickets(sys.argv[1]))
unittest.TextTestRunner(verbosity=2).run(suite)
# -*- coding: utf-8 -*-
# transformations.py
# Copyright (c) 2006, Christoph Gohlke
# Copyright (c) 2006-2009, The Regents of the University of California
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holders nor the names of any
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Homogeneous Transformation Matrices and Quaternions.
A library for calculating 4x4 matrices for translating, rotating, reflecting,
scaling, shearing, projecting, orthogonalizing, and superimposing arrays of
3D homogeneous coordinates as well as for converting between rotation matrices,
Euler angles, and quaternions. Also includes an Arcball control object and
functions to decompose transformation matrices.
:Authors:
`Christoph Gohlke <http://www.lfd.uci.edu/~gohlke/>`__,
Laboratory for Fluorescence Dynamics, University of California, Irvine
:Version: 20090418
Requirements
------------
* `Python 2.6 <http://www.python.org>`__
* `Numpy 1.3 <http://numpy.scipy.org>`__
* `transformations.c 20090418 <http://www.lfd.uci.edu/~gohlke/>`__
(optional implementation of some functions in C)
Notes
-----
Matrices (M) can be inverted using numpy.linalg.inv(M), concatenated using
numpy.dot(M0, M1), or used to transform homogeneous coordinates (v) using
numpy.dot(M, v) for shape (4, \*) "point of arrays", respectively
numpy.dot(v, M.T) for shape (\*, 4) "array of points".
Calculations are carried out with numpy.float64 precision.
This Python implementation is not optimized for speed.
Vector, point, quaternion, and matrix function arguments are expected to be
"array like", i.e. tuple, list, or numpy arrays.
Return types are numpy arrays unless specified otherwise.
Angles are in radians unless specified otherwise.
Quaternions ix+jy+kz+w are represented as [x, y, z, w].
Use the transpose of transformation matrices for OpenGL glMultMatrixd().
A triple of Euler angles can be applied/interpreted in 24 ways, which can
be specified using a 4 character string or encoded 4-tuple:
*Axes 4-string*: e.g. 'sxyz' or 'ryxy'
- first character : rotations are applied to 's'tatic or 'r'otating frame
- remaining characters : successive rotation axis 'x', 'y', or 'z'
*Axes 4-tuple*: e.g. (0, 0, 0, 0) or (1, 1, 1, 1)
- inner axis: code of axis ('x':0, 'y':1, 'z':2) of rightmost matrix.
- parity : even (0) if inner axis 'x' is followed by 'y', 'y' is followed
by 'z', or 'z' is followed by 'x'. Otherwise odd (1).
- repetition : first and last axis are same (1) or different (0).
- frame : rotations are applied to static (0) or rotating (1) frame.
References
----------
(1) Matrices and transformations. Ronald Goldman.
In "Graphics Gems I", pp 472-475. Morgan Kaufmann, 1990.
(2) More matrices and transformations: shear and pseudo-perspective.
Ronald Goldman. In "Graphics Gems II", pp 320-323. Morgan Kaufmann, 1991.
(3) Decomposing a matrix into simple transformations. Spencer Thomas.
In "Graphics Gems II", pp 320-323. Morgan Kaufmann, 1991.
(4) Recovering the data from the transformation matrix. Ronald Goldman.
In "Graphics Gems II", pp 324-331. Morgan Kaufmann, 1991.
(5) Euler angle conversion. Ken Shoemake.
In "Graphics Gems IV", pp 222-229. Morgan Kaufmann, 1994.
(6) Arcball rotation control. Ken Shoemake.
In "Graphics Gems IV", pp 175-192. Morgan Kaufmann, 1994.
(7) Representing attitude: Euler angles, unit quaternions, and rotation
vectors. James Diebel. 2006.
(8) A discussion of the solution for the best rotation to relate two sets
of vectors. W Kabsch. Acta Cryst. 1978. A34, 827-828.
(9) Closed-form solution of absolute orientation using unit quaternions.
BKP Horn. J Opt Soc Am A. 1987. 4(4), 629-642.
(10) Quaternions. Ken Shoemake.
http://www.sfu.ca/~jwa3/cmpt461/files/quatut.pdf
(11) From quaternion to matrix and back. JMP van Waveren. 2005.
http://www.intel.com/cd/ids/developer/asmo-na/eng/293748.htm
(12) Uniform random rotations. Ken Shoemake.
In "Graphics Gems III", pp 124-132. Morgan Kaufmann, 1992.
Examples
--------
>>> alpha, beta, gamma = 0.123, -1.234, 2.345
>>> origin, xaxis, yaxis, zaxis = (0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)
>>> I = identity_matrix()
>>> Rx = rotation_matrix(alpha, xaxis)
>>> Ry = rotation_matrix(beta, yaxis)
>>> Rz = rotation_matrix(gamma, zaxis)
>>> R = concatenate_matrices(Rx, Ry, Rz)
>>> euler = euler_from_matrix(R, 'rxyz')
>>> numpy.allclose([alpha, beta, gamma], euler)
True
>>> Re = euler_matrix(alpha, beta, gamma, 'rxyz')
>>> is_same_transform(R, Re)
True
>>> al, be, ga = euler_from_matrix(Re, 'rxyz')
>>> is_same_transform(Re, euler_matrix(al, be, ga, 'rxyz'))
True
>>> qx = quaternion_about_axis(alpha, xaxis)
>>> qy = quaternion_about_axis(beta, yaxis)
>>> qz = quaternion_about_axis(gamma, zaxis)
>>> q = quaternion_multiply(qx, qy)
>>> q = quaternion_multiply(q, qz)
>>> Rq = quaternion_matrix(q)
>>> is_same_transform(R, Rq)
True
>>> S = scale_matrix(1.23, origin)
>>> T = translation_matrix((1, 2, 3))
>>> Z = shear_matrix(beta, xaxis, origin, zaxis)
>>> R = random_rotation_matrix(numpy.random.rand(3))
>>> M = concatenate_matrices(T, R, Z, S)
>>> scale, shear, angles, trans, persp = decompose_matrix(M)
>>> numpy.allclose(scale, 1.23)
True
>>> numpy.allclose(trans, (1, 2, 3))
True
>>> numpy.allclose(shear, (0, math.tan(beta), 0))
True
>>> is_same_transform(R, euler_matrix(axes='sxyz', *angles))
True
>>> M1 = compose_matrix(scale, shear, angles, trans, persp)
>>> is_same_transform(M, M1)
True
"""
from __future__ import division
import warnings
import math
import numpy
# Documentation in HTML format can be generated with Epydoc
__docformat__ = "restructuredtext en"
def identity_matrix():
"""Return 4x4 identity/unit matrix.
>>> I = identity_matrix()
>>> numpy.allclose(I, numpy.dot(I, I))
True
>>> numpy.sum(I), numpy.trace(I)
(4.0, 4.0)
>>> numpy.allclose(I, numpy.identity(4, dtype=numpy.float64))
True
"""
return numpy.identity(4, dtype=numpy.float64)
def translation_matrix(direction):
"""Return matrix to translate by direction vector.
>>> v = numpy.random.random(3) - 0.5
>>> numpy.allclose(v, translation_matrix(v)[:3, 3])
True
"""
M = numpy.identity(4)
M[:3, 3] = direction[:3]
return M
def translation_from_matrix(matrix):
"""Return translation vector from translation matrix.
>>> v0 = numpy.random.random(3) - 0.5
>>> v1 = translation_from_matrix(translation_matrix(v0))
>>> numpy.allclose(v0, v1)
True
"""
return numpy.array(matrix, copy=False)[:3, 3].copy()
def reflection_matrix(point, normal):
"""Return matrix to mirror at plane defined by point and normal vector.
>>> v0 = numpy.random.random(4) - 0.5
>>> v0[3] = 1.0
>>> v1 = numpy.random.random(3) - 0.5
>>> R = reflection_matrix(v0, v1)
>>> numpy.allclose(2., numpy.trace(R))
True
>>> numpy.allclose(v0, numpy.dot(R, v0))
True
>>> v2 = v0.copy()
>>> v2[:3] += v1
>>> v3 = v0.copy()
>>> v2[:3] -= v1
>>> numpy.allclose(v2, numpy.dot(R, v3))
True
"""
normal = unit_vector(normal[:3])
M = numpy.identity(4)
M[:3, :3] -= 2.0 * numpy.outer(normal, normal)
M[:3, 3] = (2.0 * numpy.dot(point[:3], normal)) * normal
return M
def reflection_from_matrix(matrix):
"""Return mirror plane point and normal vector from reflection matrix.
>>> v0 = numpy.random.random(3) - 0.5
>>> v1 = numpy.random.random(3) - 0.5
>>> M0 = reflection_matrix(v0, v1)
>>> point, normal = reflection_from_matrix(M0)
>>> M1 = reflection_matrix(point, normal)
>>> is_same_transform(M0, M1)
True
"""
M = numpy.array(matrix, dtype=numpy.float64, copy=False)
# normal: unit eigenvector corresponding to eigenvalue -1
l, V = numpy.linalg.eig(M[:3, :3])
i = numpy.where(abs(numpy.real(l) + 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue -1")
normal = numpy.real(V[:, i[0]]).squeeze()
# point: any unit eigenvector corresponding to eigenvalue 1
l, V = numpy.linalg.eig(M)
i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
point = numpy.real(V[:, i[-1]]).squeeze()
point /= point[3]
return point, normal
def rotation_matrix(angle, direction, point=None):
"""Return matrix to rotate about axis defined by point and direction.
>>> angle = (random.random() - 0.5) * (2*math.pi)
>>> direc = numpy.random.random(3) - 0.5
>>> point = numpy.random.random(3) - 0.5
>>> R0 = rotation_matrix(angle, direc, point)
>>> R1 = rotation_matrix(angle-2*math.pi, direc, point)
>>> is_same_transform(R0, R1)
True
>>> R0 = rotation_matrix(angle, direc, point)
>>> R1 = rotation_matrix(-angle, -direc, point)
>>> is_same_transform(R0, R1)
True
>>> I = numpy.identity(4, numpy.float64)
>>> numpy.allclose(I, rotation_matrix(math.pi*2, direc))
True
>>> numpy.allclose(2., numpy.trace(rotation_matrix(math.pi/2,
... direc, point)))
True
"""
sina = math.sin(angle)
cosa = math.cos(angle)
direction = unit_vector(direction[:3])
# rotation matrix around unit vector
R = numpy.array(((cosa, 0.0, 0.0),
(0.0, cosa, 0.0),
(0.0, 0.0, cosa)), dtype=numpy.float64)
R += numpy.outer(direction, direction) * (1.0 - cosa)
direction *= sina
R += numpy.array((( 0.0, -direction[2], direction[1]),
( direction[2], 0.0, -direction[0]),
(-direction[1], direction[0], 0.0)),
dtype=numpy.float64)
M = numpy.identity(4)
M[:3, :3] = R
if point is not None:
# rotation not around origin
point = numpy.array(point[:3], dtype=numpy.float64, copy=False)
M[:3, 3] = point - numpy.dot(R, point)
return M
def rotation_from_matrix(matrix):
"""Return rotation angle and axis from rotation matrix.
>>> angle = (random.random() - 0.5) * (2*math.pi)
>>> direc = numpy.random.random(3) - 0.5
>>> point = numpy.random.random(3) - 0.5
>>> R0 = rotation_matrix(angle, direc, point)
>>> angle, direc, point = rotation_from_matrix(R0)
>>> R1 = rotation_matrix(angle, direc, point)
>>> is_same_transform(R0, R1)
True
"""
R = numpy.array(matrix, dtype=numpy.float64, copy=False)
R33 = R[:3, :3]
# direction: unit eigenvector of R33 corresponding to eigenvalue of 1
l, W = numpy.linalg.eig(R33.T)
i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
direction = numpy.real(W[:, i[-1]]).squeeze()
# point: unit eigenvector of R33 corresponding to eigenvalue of 1
l, Q = numpy.linalg.eig(R)
i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
point = numpy.real(Q[:, i[-1]]).squeeze()
point /= point[3]
# rotation angle depending on direction
cosa = (numpy.trace(R33) - 1.0) / 2.0
if abs(direction[2]) > 1e-8:
sina = (R[1, 0] + (cosa-1.0)*direction[0]*direction[1]) / direction[2]
elif abs(direction[1]) > 1e-8:
sina = (R[0, 2] + (cosa-1.0)*direction[0]*direction[2]) / direction[1]
else:
sina = (R[2, 1] + (cosa-1.0)*direction[1]*direction[2]) / direction[0]
angle = math.atan2(sina, cosa)
return angle, direction, point
def scale_matrix(factor, origin=None, direction=None):
"""Return matrix to scale by factor around origin in direction.
Use factor -1 for point symmetry.
>>> v = (numpy.random.rand(4, 5) - 0.5) * 20.0
>>> v[3] = 1.0
>>> S = scale_matrix(-1.234)
>>> numpy.allclose(numpy.dot(S, v)[:3], -1.234*v[:3])
True
>>> factor = random.random() * 10 - 5
>>> origin = numpy.random.random(3) - 0.5
>>> direct = numpy.random.random(3) - 0.5
>>> S = scale_matrix(factor, origin)
>>> S = scale_matrix(factor, origin, direct)
"""
if direction is None:
# uniform scaling
M = numpy.array(((factor, 0.0, 0.0, 0.0),
(0.0, factor, 0.0, 0.0),
(0.0, 0.0, factor, 0.0),
(0.0, 0.0, 0.0, 1.0)), dtype=numpy.float64)
if origin is not None:
M[:3, 3] = origin[:3]
M[:3, 3] *= 1.0 - factor
else:
# nonuniform scaling
direction = unit_vector(direction[:3])
factor = 1.0 - factor
M = numpy.identity(4)
M[:3, :3] -= factor * numpy.outer(direction, direction)
if origin is not None:
M[:3, 3] = (factor * numpy.dot(origin[:3], direction)) * direction
return M
def scale_from_matrix(matrix):
"""Return scaling factor, origin and direction from scaling matrix.
>>> factor = random.random() * 10 - 5
>>> origin = numpy.random.random(3) - 0.5
>>> direct = numpy.random.random(3) - 0.5
>>> S0 = scale_matrix(factor, origin)
>>> factor, origin, direction = scale_from_matrix(S0)
>>> S1 = scale_matrix(factor, origin, direction)
>>> is_same_transform(S0, S1)
True
>>> S0 = scale_matrix(factor, origin, direct)
>>> factor, origin, direction = scale_from_matrix(S0)
>>> S1 = scale_matrix(factor, origin, direction)
>>> is_same_transform(S0, S1)
True
"""
M = numpy.array(matrix, dtype=numpy.float64, copy=False)
M33 = M[:3, :3]
factor = numpy.trace(M33) - 2.0
try:
# direction: unit eigenvector corresponding to eigenvalue factor
l, V = numpy.linalg.eig(M33)
i = numpy.where(abs(numpy.real(l) - factor) < 1e-8)[0][0]
direction = numpy.real(V[:, i]).squeeze()
direction /= vector_norm(direction)
except IndexError:
# uniform scaling
factor = (factor + 2.0) / 3.0
direction = None
# origin: any eigenvector corresponding to eigenvalue 1
l, V = numpy.linalg.eig(M)
i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no eigenvector corresponding to eigenvalue 1")
origin = numpy.real(V[:, i[-1]]).squeeze()
origin /= origin[3]
return factor, origin, direction
def projection_matrix(point, normal, direction=None,
perspective=None, pseudo=False):
"""Return matrix to project onto plane defined by point and normal.
Using either perspective point, projection direction, or none of both.
If pseudo is True, perspective projections will preserve relative depth
such that Perspective = dot(Orthogonal, PseudoPerspective).
>>> P = projection_matrix((0, 0, 0), (1, 0, 0))
>>> numpy.allclose(P[1:, 1:], numpy.identity(4)[1:, 1:])
True
>>> point = numpy.random.random(3) - 0.5
>>> normal = numpy.random.random(3) - 0.5
>>> direct = numpy.random.random(3) - 0.5
>>> persp = numpy.random.random(3) - 0.5
>>> P0 = projection_matrix(point, normal)
>>> P1 = projection_matrix(point, normal, direction=direct)
>>> P2 = projection_matrix(point, normal, perspective=persp)
>>> P3 = projection_matrix(point, normal, perspective=persp, pseudo=True)
>>> is_same_transform(P2, numpy.dot(P0, P3))
True
>>> P = projection_matrix((3, 0, 0), (1, 1, 0), (1, 0, 0))
>>> v0 = (numpy.random.rand(4, 5) - 0.5) * 20.0
>>> v0[3] = 1.0
>>> v1 = numpy.dot(P, v0)
>>> numpy.allclose(v1[1], v0[1])
True
>>> numpy.allclose(v1[0], 3.0-v1[1])
True
"""
M = numpy.identity(4)
point = numpy.array(point[:3], dtype=numpy.float64, copy=False)
normal = unit_vector(normal[:3])
if perspective is not None:
# perspective projection
perspective = numpy.array(perspective[:3], dtype=numpy.float64,
copy=False)
M[0, 0] = M[1, 1] = M[2, 2] = numpy.dot(perspective-point, normal)
M[:3, :3] -= numpy.outer(perspective, normal)
if pseudo:
# preserve relative depth
M[:3, :3] -= numpy.outer(normal, normal)
M[:3, 3] = numpy.dot(point, normal) * (perspective+normal)
else:
M[:3, 3] = numpy.dot(point, normal) * perspective
M[3, :3] = -normal
M[3, 3] = numpy.dot(perspective, normal)
elif direction is not None:
# parallel projection
direction = numpy.array(direction[:3], dtype=numpy.float64, copy=False)
scale = numpy.dot(direction, normal)
M[:3, :3] -= numpy.outer(direction, normal) / scale
M[:3, 3] = direction * (numpy.dot(point, normal) / scale)
else:
# orthogonal projection
M[:3, :3] -= numpy.outer(normal, normal)
M[:3, 3] = numpy.dot(point, normal) * normal
return M
def projection_from_matrix(matrix, pseudo=False):
"""Return projection plane and perspective point from projection matrix.
Return values are same as arguments for projection_matrix function:
point, normal, direction, perspective, and pseudo.
>>> point = numpy.random.random(3) - 0.5
>>> normal = numpy.random.random(3) - 0.5
>>> direct = numpy.random.random(3) - 0.5
>>> persp = numpy.random.random(3) - 0.5
>>> P0 = projection_matrix(point, normal)
>>> result = projection_from_matrix(P0)
>>> P1 = projection_matrix(*result)
>>> is_same_transform(P0, P1)
True
>>> P0 = projection_matrix(point, normal, direct)
>>> result = projection_from_matrix(P0)
>>> P1 = projection_matrix(*result)
>>> is_same_transform(P0, P1)
True
>>> P0 = projection_matrix(point, normal, perspective=persp, pseudo=False)
>>> result = projection_from_matrix(P0, pseudo=False)
>>> P1 = projection_matrix(*result)
>>> is_same_transform(P0, P1)
True
>>> P0 = projection_matrix(point, normal, perspective=persp, pseudo=True)
>>> result = projection_from_matrix(P0, pseudo=True)
>>> P1 = projection_matrix(*result)
>>> is_same_transform(P0, P1)
True
"""
M = numpy.array(matrix, dtype=numpy.float64, copy=False)
M33 = M[:3, :3]
l, V = numpy.linalg.eig(M)
i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-8)[0]
if not pseudo and len(i):
# point: any eigenvector corresponding to eigenvalue 1
point = numpy.real(V[:, i[-1]]).squeeze()
point /= point[3]
# direction: unit eigenvector corresponding to eigenvalue 0
l, V = numpy.linalg.eig(M33)
i = numpy.where(abs(numpy.real(l)) < 1e-8)[0]
if not len(i):
raise ValueError("no eigenvector corresponding to eigenvalue 0")
direction = numpy.real(V[:, i[0]]).squeeze()
direction /= vector_norm(direction)
# normal: unit eigenvector of M33.T corresponding to eigenvalue 0
l, V = numpy.linalg.eig(M33.T)
i = numpy.where(abs(numpy.real(l)) < 1e-8)[0]
if len(i):
# parallel projection
normal = numpy.real(V[:, i[0]]).squeeze()
normal /= vector_norm(normal)
return point, normal, direction, None, False
else:
# orthogonal projection, where normal equals direction vector
return point, direction, None, None, False
else:
# perspective projection
i = numpy.where(abs(numpy.real(l)) > 1e-8)[0]
if not len(i):
raise ValueError(
"no eigenvector not corresponding to eigenvalue 0")
point = numpy.real(V[:, i[-1]]).squeeze()
point /= point[3]
normal = - M[3, :3]
perspective = M[:3, 3] / numpy.dot(point[:3], normal)
if pseudo:
perspective -= normal
return point, normal, None, perspective, pseudo
def clip_matrix(left, right, bottom, top, near, far, perspective=False):
"""Return matrix to obtain normalized device coordinates from frustrum.
The frustrum bounds are axis-aligned along x (left, right),
y (bottom, top) and z (near, far).
Normalized device coordinates are in range [-1, 1] if coordinates are
inside the frustrum.
If perspective is True the frustrum is a truncated pyramid with the
perspective point at origin and direction along z axis, otherwise an
orthographic canonical view volume (a box).
Homogeneous coordinates transformed by the perspective clip matrix
need to be dehomogenized (devided by w coordinate).
>>> frustrum = numpy.random.rand(6)
>>> frustrum[1] += frustrum[0]
>>> frustrum[3] += frustrum[2]
>>> frustrum[5] += frustrum[4]
>>> M = clip_matrix(*frustrum, perspective=False)
>>> numpy.dot(M, [frustrum[0], frustrum[2], frustrum[4], 1.0])
array([-1., -1., -1., 1.])
>>> numpy.dot(M, [frustrum[1], frustrum[3], frustrum[5], 1.0])
array([ 1., 1., 1., 1.])
>>> M = clip_matrix(*frustrum, perspective=True)
>>> v = numpy.dot(M, [frustrum[0], frustrum[2], frustrum[4], 1.0])
>>> v / v[3]
array([-1., -1., -1., 1.])
>>> v = numpy.dot(M, [frustrum[1], frustrum[3], frustrum[4], 1.0])
>>> v / v[3]
array([ 1., 1., -1., 1.])
"""
if left >= right or bottom >= top or near >= far:
raise ValueError("invalid frustrum")
if perspective:
if near <= _EPS:
raise ValueError("invalid frustrum: near <= 0")
t = 2.0 * near
M = ((-t/(right-left), 0.0, (right+left)/(right-left), 0.0),
(0.0, -t/(top-bottom), (top+bottom)/(top-bottom), 0.0),
(0.0, 0.0, -(far+near)/(far-near), t*far/(far-near)),
(0.0, 0.0, -1.0, 0.0))
else:
M = ((2.0/(right-left), 0.0, 0.0, (right+left)/(left-right)),
(0.0, 2.0/(top-bottom), 0.0, (top+bottom)/(bottom-top)),
(0.0, 0.0, 2.0/(far-near), (far+near)/(near-far)),
(0.0, 0.0, 0.0, 1.0))
return numpy.array(M, dtype=numpy.float64)
def shear_matrix(angle, direction, point, normal):
"""Return matrix to shear by angle along direction vector on shear plane.
The shear plane is defined by a point and normal vector. The direction
vector must be orthogonal to the plane's normal vector.
A point P is transformed by the shear matrix into P" such that
the vector P-P" is parallel to the direction vector and its extent is
given by the angle of P-P'-P", where P' is the orthogonal projection
of P onto the shear plane.
>>> angle = (random.random() - 0.5) * 4*math.pi
>>> direct = numpy.random.random(3) - 0.5
>>> point = numpy.random.random(3) - 0.5
>>> normal = numpy.cross(direct, numpy.random.random(3))
>>> S = shear_matrix(angle, direct, point, normal)
>>> numpy.allclose(1.0, numpy.linalg.det(S))
True
"""
normal = unit_vector(normal[:3])
direction = unit_vector(direction[:3])
if abs(numpy.dot(normal, direction)) > 1e-6:
raise ValueError("direction and normal vectors are not orthogonal")
angle = math.tan(angle)
M = numpy.identity(4)
M[:3, :3] += angle * numpy.outer(direction, normal)
M[:3, 3] = -angle * numpy.dot(point[:3], normal) * direction
return M
def shear_from_matrix(matrix):
"""Return shear angle, direction and plane from shear matrix.
>>> angle = (random.random() - 0.5) * 4*math.pi
>>> direct = numpy.random.random(3) - 0.5
>>> point = numpy.random.random(3) - 0.5
>>> normal = numpy.cross(direct, numpy.random.random(3))
>>> S0 = shear_matrix(angle, direct, point, normal)
>>> angle, direct, point, normal = shear_from_matrix(S0)
>>> S1 = shear_matrix(angle, direct, point, normal)
>>> is_same_transform(S0, S1)
True
"""
M = numpy.array(matrix, dtype=numpy.float64, copy=False)
M33 = M[:3, :3]
# normal: cross independent eigenvectors corresponding to the eigenvalue 1
l, V = numpy.linalg.eig(M33)
i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-4)[0]
if len(i) < 2:
raise ValueError("No two linear independent eigenvectors found %s" % l)
V = numpy.real(V[:, i]).squeeze().T
lenorm = -1.0
for i0, i1 in ((0, 1), (0, 2), (1, 2)):
n = numpy.cross(V[i0], V[i1])
l = vector_norm(n)
if l > lenorm:
lenorm = l
normal = n
normal /= lenorm
# direction and angle
direction = numpy.dot(M33 - numpy.identity(3), normal)
angle = vector_norm(direction)
direction /= angle
angle = math.atan(angle)
# point: eigenvector corresponding to eigenvalue 1
l, V = numpy.linalg.eig(M)
i = numpy.where(abs(numpy.real(l) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no eigenvector corresponding to eigenvalue 1")
point = numpy.real(V[:, i[-1]]).squeeze()
point /= point[3]
return angle, direction, point, normal
def decompose_matrix(matrix):
"""Return sequence of transformations from transformation matrix.
matrix : array_like
Non-degenerative homogeneous transformation matrix
Return tuple of:
scale : vector of 3 scaling factors
shear : list of shear factors for x-y, x-z, y-z axes
angles : list of Euler angles about static x, y, z axes
translate : translation vector along x, y, z axes
perspective : perspective partition of matrix
Raise ValueError if matrix is of wrong type or degenerative.
>>> T0 = translation_matrix((1, 2, 3))
>>> scale, shear, angles, trans, persp = decompose_matrix(T0)
>>> T1 = translation_matrix(trans)
>>> numpy.allclose(T0, T1)
True
>>> S = scale_matrix(0.123)
>>> scale, shear, angles, trans, persp = decompose_matrix(S)
>>> scale[0]
0.123
>>> R0 = euler_matrix(1, 2, 3)
>>> scale, shear, angles, trans, persp = decompose_matrix(R0)
>>> R1 = euler_matrix(*angles)
>>> numpy.allclose(R0, R1)
True
"""
M = numpy.array(matrix, dtype=numpy.float64, copy=True).T
if abs(M[3, 3]) < _EPS:
raise ValueError("M[3, 3] is zero")
M /= M[3, 3]
P = M.copy()
P[:, 3] = 0, 0, 0, 1
if not numpy.linalg.det(P):
raise ValueError("Matrix is singular")
scale = numpy.zeros((3, ), dtype=numpy.float64)
shear = [0, 0, 0]
angles = [0, 0, 0]
if any(abs(M[:3, 3]) > _EPS):
perspective = numpy.dot(M[:, 3], numpy.linalg.inv(P.T))
M[:, 3] = 0, 0, 0, 1
else:
perspective = numpy.array((0, 0, 0, 1), dtype=numpy.float64)
translate = M[3, :3].copy()
M[3, :3] = 0
row = M[:3, :3].copy()
scale[0] = vector_norm(row[0])
row[0] /= scale[0]
shear[0] = numpy.dot(row[0], row[1])
row[1] -= row[0] * shear[0]
scale[1] = vector_norm(row[1])
row[1] /= scale[1]
shear[0] /= scale[1]
shear[1] = numpy.dot(row[0], row[2])
row[2] -= row[0] * shear[1]
shear[2] = numpy.dot(row[1], row[2])
row[2] -= row[1] * shear[2]
scale[2] = vector_norm(row[2])
row[2] /= scale[2]
shear[1:] /= scale[2]
if numpy.dot(row[0], numpy.cross(row[1], row[2])) < 0:
scale *= -1
row *= -1
angles[1] = math.asin(-row[0, 2])
if math.cos(angles[1]):
angles[0] = math.atan2(row[1, 2], row[2, 2])
angles[2] = math.atan2(row[0, 1], row[0, 0])
else:
#angles[0] = math.atan2(row[1, 0], row[1, 1])
angles[0] = math.atan2(-row[2, 1], row[1, 1])
angles[2] = 0.0
return scale, shear, angles, translate, perspective
def compose_matrix(scale=None, shear=None, angles=None, translate=None,
perspective=None):
"""Return transformation matrix from sequence of transformations.
This is the inverse of the decompose_matrix function.
Sequence of transformations:
scale : vector of 3 scaling factors
shear : list of shear factors for x-y, x-z, y-z axes
angles : list of Euler angles about static x, y, z axes
translate : translation vector along x, y, z axes
perspective : perspective partition of matrix
>>> scale = numpy.random.random(3) - 0.5
>>> shear = numpy.random.random(3) - 0.5
>>> angles = (numpy.random.random(3) - 0.5) * (2*math.pi)
>>> trans = numpy.random.random(3) - 0.5
>>> persp = numpy.random.random(4) - 0.5
>>> M0 = compose_matrix(scale, shear, angles, trans, persp)
>>> result = decompose_matrix(M0)
>>> M1 = compose_matrix(*result)
>>> is_same_transform(M0, M1)
True
"""
M = numpy.identity(4)
if perspective is not None:
P = numpy.identity(4)
P[3, :] = perspective[:4]
M = numpy.dot(M, P)
if translate is not None:
T = numpy.identity(4)
T[:3, 3] = translate[:3]
M = numpy.dot(M, T)
if angles is not None:
R = euler_matrix(angles[0], angles[1], angles[2], 'sxyz')
M = numpy.dot(M, R)
if shear is not None:
Z = numpy.identity(4)
Z[1, 2] = shear[2]
Z[0, 2] = shear[1]
Z[0, 1] = shear[0]
M = numpy.dot(M, Z)
if scale is not None:
S = numpy.identity(4)
S[0, 0] = scale[0]
S[1, 1] = scale[1]
S[2, 2] = scale[2]
M = numpy.dot(M, S)
M /= M[3, 3]
return M
def orthogonalization_matrix(lengths, angles):
"""Return orthogonalization matrix for crystallographic cell coordinates.
Angles are expected in degrees.
The de-orthogonalization matrix is the inverse.
>>> O = orthogonalization_matrix((10., 10., 10.), (90., 90., 90.))
>>> numpy.allclose(O[:3, :3], numpy.identity(3, float) * 10)
True
>>> O = orthogonalization_matrix([9.8, 12.0, 15.5], [87.2, 80.7, 69.7])
>>> numpy.allclose(numpy.sum(O), 43.063229)
True
"""
a, b, c = lengths
angles = numpy.radians(angles)
sina, sinb, _ = numpy.sin(angles)
cosa, cosb, cosg = numpy.cos(angles)
co = (cosa * cosb - cosg) / (sina * sinb)
return numpy.array((
( a*sinb*math.sqrt(1.0-co*co), 0.0, 0.0, 0.0),
(-a*sinb*co, b*sina, 0.0, 0.0),
( a*cosb, b*cosa, c, 0.0),
( 0.0, 0.0, 0.0, 1.0)),
dtype=numpy.float64)
def superimposition_matrix(v0, v1, scaling=False, usesvd=True):
"""Return matrix to transform given vector set into second vector set.
v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 vectors.
If usesvd is True, the weighted sum of squared deviations (RMSD) is
minimized according to the algorithm by W. Kabsch [8]. Otherwise the
quaternion based algorithm by B. Horn [9] is used (slower when using
this Python implementation).
The returned matrix performs rotation, translation and uniform scaling
(if specified).
>>> v0 = numpy.random.rand(3, 10)
>>> M = superimposition_matrix(v0, v0)
>>> numpy.allclose(M, numpy.identity(4))
True
>>> R = random_rotation_matrix(numpy.random.random(3))
>>> v0 = ((1,0,0), (0,1,0), (0,0,1), (1,1,1))
>>> v1 = numpy.dot(R, v0)
>>> M = superimposition_matrix(v0, v1)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20.0
>>> v0[3] = 1.0
>>> v1 = numpy.dot(R, v0)
>>> M = superimposition_matrix(v0, v1)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> S = scale_matrix(random.random())
>>> T = translation_matrix(numpy.random.random(3)-0.5)
>>> M = concatenate_matrices(T, R, S)
>>> v1 = numpy.dot(M, v0)
>>> v0[:3] += numpy.random.normal(0.0, 1e-9, 300).reshape(3, -1)
>>> M = superimposition_matrix(v0, v1, scaling=True)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> M = superimposition_matrix(v0, v1, scaling=True, usesvd=False)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> v = numpy.empty((4, 100, 3), dtype=numpy.float64)
>>> v[:, :, 0] = v0
>>> M = superimposition_matrix(v0, v1, scaling=True, usesvd=False)
>>> numpy.allclose(v1, numpy.dot(M, v[:, :, 0]))
True
"""
v0 = numpy.array(v0, dtype=numpy.float64, copy=False)[:3]
v1 = numpy.array(v1, dtype=numpy.float64, copy=False)[:3]
if v0.shape != v1.shape or v0.shape[1] < 3:
raise ValueError("Vector sets are of wrong shape or type.")
# move centroids to origin
t0 = numpy.mean(v0, axis=1)
t1 = numpy.mean(v1, axis=1)
v0 = v0 - t0.reshape(3, 1)
v1 = v1 - t1.reshape(3, 1)
if usesvd:
# Singular Value Decomposition of covariance matrix
u, s, vh = numpy.linalg.svd(numpy.dot(v1, v0.T))
# rotation matrix from SVD orthonormal bases
R = numpy.dot(u, vh)
if numpy.linalg.det(R) < 0.0:
# R does not constitute right handed system
R -= numpy.outer(u[:, 2], vh[2, :]*2.0)
s[-1] *= -1.0
# homogeneous transformation matrix
M = numpy.identity(4)
M[:3, :3] = R
else:
# compute symmetric matrix N
xx, yy, zz = numpy.sum(v0 * v1, axis=1)
xy, yz, zx = numpy.sum(v0 * numpy.roll(v1, -1, axis=0), axis=1)
xz, yx, zy = numpy.sum(v0 * numpy.roll(v1, -2, axis=0), axis=1)
N = ((xx+yy+zz, yz-zy, zx-xz, xy-yx),
(yz-zy, xx-yy-zz, xy+yx, zx+xz),
(zx-xz, xy+yx, -xx+yy-zz, yz+zy),
(xy-yx, zx+xz, yz+zy, -xx-yy+zz))
# quaternion: eigenvector corresponding to most positive eigenvalue
l, V = numpy.linalg.eig(N)
q = V[:, numpy.argmax(l)]
q /= vector_norm(q) # unit quaternion
q = numpy.roll(q, -1) # move w component to end
# homogeneous transformation matrix
M = quaternion_matrix(q)
# scale: ratio of rms deviations from centroid
if scaling:
v0 *= v0
v1 *= v1
M[:3, :3] *= math.sqrt(numpy.sum(v1) / numpy.sum(v0))
# translation
M[:3, 3] = t1
T = numpy.identity(4)
T[:3, 3] = -t0
M = numpy.dot(M, T)
return M
def euler_matrix(ai, aj, ak, axes='sxyz'):
"""Return homogeneous rotation matrix from Euler angles and axis sequence.
ai, aj, ak : Euler's roll, pitch and yaw angles
axes : One of 24 axis sequences as string or encoded tuple
>>> R = euler_matrix(1, 2, 3, 'syxz')
>>> numpy.allclose(numpy.sum(R[0]), -1.34786452)
True
>>> R = euler_matrix(1, 2, 3, (0, 1, 0, 1))
>>> numpy.allclose(numpy.sum(R[0]), -0.383436184)
True
>>> ai, aj, ak = (4.0*math.pi) * (numpy.random.random(3) - 0.5)
>>> for axes in _AXES2TUPLE.keys():
... R = euler_matrix(ai, aj, ak, axes)
>>> for axes in _TUPLE2AXES.keys():
... R = euler_matrix(ai, aj, ak, axes)
"""
try:
firstaxis, parity, repetition, frame = _AXES2TUPLE[axes]
except (AttributeError, KeyError):
_ = _TUPLE2AXES[axes]
firstaxis, parity, repetition, frame = axes
i = firstaxis
j = _NEXT_AXIS[i+parity]
k = _NEXT_AXIS[i-parity+1]
if frame:
ai, ak = ak, ai
if parity:
ai, aj, ak = -ai, -aj, -ak
si, sj, sk = math.sin(ai), math.sin(aj), math.sin(ak)
ci, cj, ck = math.cos(ai), math.cos(aj), math.cos(ak)
cc, cs = ci*ck, ci*sk
sc, ss = si*ck, si*sk
M = numpy.identity(4)
if repetition:
M[i, i] = cj
M[i, j] = sj*si
M[i, k] = sj*ci
M[j, i] = sj*sk
M[j, j] = -cj*ss+cc
M[j, k] = -cj*cs-sc
M[k, i] = -sj*ck
M[k, j] = cj*sc+cs
M[k, k] = cj*cc-ss
else:
M[i, i] = cj*ck
M[i, j] = sj*sc-cs
M[i, k] = sj*cc+ss
M[j, i] = cj*sk
M[j, j] = sj*ss+cc
M[j, k] = sj*cs-sc
M[k, i] = -sj
M[k, j] = cj*si
M[k, k] = cj*ci
return M
def euler_from_matrix(matrix, axes='sxyz'):
"""Return Euler angles from rotation matrix for specified axis sequence.
axes : One of 24 axis sequences as string or encoded tuple
Note that many Euler angle triplets can describe one matrix.
>>> R0 = euler_matrix(1, 2, 3, 'syxz')
>>> al, be, ga = euler_from_matrix(R0, 'syxz')
>>> R1 = euler_matrix(al, be, ga, 'syxz')
>>> numpy.allclose(R0, R1)
True
>>> angles = (4.0*math.pi) * (numpy.random.random(3) - 0.5)
>>> for axes in _AXES2TUPLE.keys():
... R0 = euler_matrix(axes=axes, *angles)
... R1 = euler_matrix(axes=axes, *euler_from_matrix(R0, axes))
... if not numpy.allclose(R0, R1): print axes, "failed"
"""
try:
firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]
except (AttributeError, KeyError):
_ = _TUPLE2AXES[axes]
firstaxis, parity, repetition, frame = axes
i = firstaxis
j = _NEXT_AXIS[i+parity]
k = _NEXT_AXIS[i-parity+1]
M = numpy.array(matrix, dtype=numpy.float64, copy=False)[:3, :3]
if repetition:
sy = math.sqrt(M[i, j]*M[i, j] + M[i, k]*M[i, k])
if sy > _EPS:
ax = math.atan2( M[i, j], M[i, k])
ay = math.atan2( sy, M[i, i])
az = math.atan2( M[j, i], -M[k, i])
else:
ax = math.atan2(-M[j, k], M[j, j])
ay = math.atan2( sy, M[i, i])
az = 0.0
else:
cy = math.sqrt(M[i, i]*M[i, i] + M[j, i]*M[j, i])
if cy > _EPS:
ax = math.atan2( M[k, j], M[k, k])
ay = math.atan2(-M[k, i], cy)
az = math.atan2( M[j, i], M[i, i])
else:
ax = math.atan2(-M[j, k], M[j, j])
ay = math.atan2(-M[k, i], cy)
az = 0.0
if parity:
ax, ay, az = -ax, -ay, -az
if frame:
ax, az = az, ax
return ax, ay, az
def euler_from_quaternion(quaternion, axes='sxyz'):
"""Return Euler angles from quaternion for specified axis sequence.
>>> angles = euler_from_quaternion([0.06146124, 0, 0, 0.99810947])
>>> numpy.allclose(angles, [0.123, 0, 0])
True
"""
return euler_from_matrix(quaternion_matrix(quaternion), axes)
def quaternion_from_euler(ai, aj, ak, axes='sxyz'):
"""Return quaternion from Euler angles and axis sequence.
ai, aj, ak : Euler's roll, pitch and yaw angles
axes : One of 24 axis sequences as string or encoded tuple
>>> q = quaternion_from_euler(1, 2, 3, 'ryxz')
>>> numpy.allclose(q, [0.310622, -0.718287, 0.444435, 0.435953])
True
"""
try:
firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]
except (AttributeError, KeyError):
_ = _TUPLE2AXES[axes]
firstaxis, parity, repetition, frame = axes
i = firstaxis
j = _NEXT_AXIS[i+parity]
k = _NEXT_AXIS[i-parity+1]
if frame:
ai, ak = ak, ai
if parity:
aj = -aj
ai /= 2.0
aj /= 2.0
ak /= 2.0
ci = math.cos(ai)
si = math.sin(ai)
cj = math.cos(aj)
sj = math.sin(aj)
ck = math.cos(ak)
sk = math.sin(ak)
cc = ci*ck
cs = ci*sk
sc = si*ck
ss = si*sk
quaternion = numpy.empty((4, ), dtype=numpy.float64)
if repetition:
quaternion[i] = cj*(cs + sc)
quaternion[j] = sj*(cc + ss)
quaternion[k] = sj*(cs - sc)
quaternion[3] = cj*(cc - ss)
else:
quaternion[i] = cj*sc - sj*cs
quaternion[j] = cj*ss + sj*cc
quaternion[k] = cj*cs - sj*sc
quaternion[3] = cj*cc + sj*ss
if parity:
quaternion[j] *= -1
return quaternion
def quaternion_about_axis(angle, axis):
"""Return quaternion for rotation about axis.
>>> q = quaternion_about_axis(0.123, (1, 0, 0))
>>> numpy.allclose(q, [0.06146124, 0, 0, 0.99810947])
True
"""
quaternion = numpy.zeros((4, ), dtype=numpy.float64)
quaternion[:3] = axis[:3]
qlen = vector_norm(quaternion)
if qlen > _EPS:
quaternion *= math.sin(angle/2.0) / qlen
quaternion[3] = math.cos(angle/2.0)
return quaternion
def quaternion_matrix(quaternion):
"""Return homogeneous rotation matrix from quaternion.
>>> R = quaternion_matrix([0.06146124, 0, 0, 0.99810947])
>>> numpy.allclose(R, rotation_matrix(0.123, (1, 0, 0)))
True
"""
q = numpy.array(quaternion[:4], dtype=numpy.float64, copy=True)
nq = numpy.dot(q, q)
if nq < _EPS:
return numpy.identity(4)
q *= math.sqrt(2.0 / nq)
q = numpy.outer(q, q)
return numpy.array((
(1.0-q[1, 1]-q[2, 2], q[0, 1]-q[2, 3], q[0, 2]+q[1, 3], 0.0),
( q[0, 1]+q[2, 3], 1.0-q[0, 0]-q[2, 2], q[1, 2]-q[0, 3], 0.0),
( q[0, 2]-q[1, 3], q[1, 2]+q[0, 3], 1.0-q[0, 0]-q[1, 1], 0.0),
( 0.0, 0.0, 0.0, 1.0)
), dtype=numpy.float64)
def quaternion_from_matrix(matrix):
"""Return quaternion from rotation matrix.
>>> R = rotation_matrix(0.123, (1, 2, 3))
>>> q = quaternion_from_matrix(R)
>>> numpy.allclose(q, [0.0164262, 0.0328524, 0.0492786, 0.9981095])
True
"""
q = numpy.empty((4, ), dtype=numpy.float64)
M = numpy.array(matrix, dtype=numpy.float64, copy=False)[:4, :4]
t = numpy.trace(M)
if t > M[3, 3]:
q[3] = t
q[2] = M[1, 0] - M[0, 1]
q[1] = M[0, 2] - M[2, 0]
q[0] = M[2, 1] - M[1, 2]
else:
i, j, k = 0, 1, 2
if M[1, 1] > M[0, 0]:
i, j, k = 1, 2, 0
if M[2, 2] > M[i, i]:
i, j, k = 2, 0, 1
t = M[i, i] - (M[j, j] + M[k, k]) + M[3, 3]
q[i] = t
q[j] = M[i, j] + M[j, i]
q[k] = M[k, i] + M[i, k]
q[3] = M[k, j] - M[j, k]
q *= 0.5 / math.sqrt(t * M[3, 3])
return q
def quaternion_multiply(quaternion1, quaternion0):
"""Return multiplication of two quaternions.
>>> q = quaternion_multiply([1, -2, 3, 4], [-5, 6, 7, 8])
>>> numpy.allclose(q, [-44, -14, 48, 28])
True
"""
x0, y0, z0, w0 = quaternion0
x1, y1, z1, w1 = quaternion1
return numpy.array((
x1*w0 + y1*z0 - z1*y0 + w1*x0,
-x1*z0 + y1*w0 + z1*x0 + w1*y0,
x1*y0 - y1*x0 + z1*w0 + w1*z0,
-x1*x0 - y1*y0 - z1*z0 + w1*w0), dtype=numpy.float64)
def quaternion_conjugate(quaternion):
"""Return conjugate of quaternion.
>>> q0 = random_quaternion()
>>> q1 = quaternion_conjugate(q0)
>>> q1[3] == q0[3] and all(q1[:3] == -q0[:3])
True
"""
return numpy.array((-quaternion[0], -quaternion[1],
-quaternion[2], quaternion[3]), dtype=numpy.float64)
def quaternion_inverse(quaternion):
"""Return inverse of quaternion.
>>> q0 = random_quaternion()
>>> q1 = quaternion_inverse(q0)
>>> numpy.allclose(quaternion_multiply(q0, q1), [0, 0, 0, 1])
True
"""
return quaternion_conjugate(quaternion) / numpy.dot(quaternion, quaternion)
def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True):
"""Return spherical linear interpolation between two quaternions.
>>> q0 = random_quaternion()
>>> q1 = random_quaternion()
>>> q = quaternion_slerp(q0, q1, 0.0)
>>> numpy.allclose(q, q0)
True
>>> q = quaternion_slerp(q0, q1, 1.0, 1)
>>> numpy.allclose(q, q1)
True
>>> q = quaternion_slerp(q0, q1, 0.5)
>>> angle = math.acos(numpy.dot(q0, q))
>>> numpy.allclose(2.0, math.acos(numpy.dot(q0, q1)) / angle) or \
numpy.allclose(2.0, math.acos(-numpy.dot(q0, q1)) / angle)
True
"""
q0 = unit_vector(quat0[:4])
q1 = unit_vector(quat1[:4])
if fraction == 0.0:
return q0
elif fraction == 1.0:
return q1
d = numpy.dot(q0, q1)
if abs(abs(d) - 1.0) < _EPS:
return q0
if shortestpath and d < 0.0:
# invert rotation
d = -d
q1 *= -1.0
angle = math.acos(d) + spin * math.pi
if abs(angle) < _EPS:
return q0
isin = 1.0 / math.sin(angle)
q0 *= math.sin((1.0 - fraction) * angle) * isin
q1 *= math.sin(fraction * angle) * isin
q0 += q1
return q0
def random_quaternion(rand=None):
"""Return uniform random unit quaternion.
rand: array like or None
Three independent random variables that are uniformly distributed
between 0 and 1.
>>> q = random_quaternion()
>>> numpy.allclose(1.0, vector_norm(q))
True
>>> q = random_quaternion(numpy.random.random(3))
>>> q.shape
(4,)
"""
if rand is None:
rand = numpy.random.rand(3)
else:
assert len(rand) == 3
r1 = numpy.sqrt(1.0 - rand[0])
r2 = numpy.sqrt(rand[0])
pi2 = math.pi * 2.0
t1 = pi2 * rand[1]
t2 = pi2 * rand[2]
return numpy.array((numpy.sin(t1)*r1,
numpy.cos(t1)*r1,
numpy.sin(t2)*r2,
numpy.cos(t2)*r2), dtype=numpy.float64)
def random_rotation_matrix(rand=None):
"""Return uniform random rotation matrix.
rnd: array like
Three independent random variables that are uniformly distributed
between 0 and 1 for each returned quaternion.
>>> R = random_rotation_matrix()
>>> numpy.allclose(numpy.dot(R.T, R), numpy.identity(4))
True
"""
return quaternion_matrix(random_quaternion(rand))
class Arcball(object):
"""Virtual Trackball Control.
>>> ball = Arcball()
>>> ball = Arcball(initial=numpy.identity(4))
>>> ball.place([320, 320], 320)
>>> ball.down([500, 250])
>>> ball.drag([475, 275])
>>> R = ball.matrix()
>>> numpy.allclose(numpy.sum(R), 3.90583455)
True
>>> ball = Arcball(initial=[0, 0, 0, 1])
>>> ball.place([320, 320], 320)
>>> ball.setaxes([1,1,0], [-1, 1, 0])
>>> ball.setconstrain(True)
>>> ball.down([400, 200])
>>> ball.drag([200, 400])
>>> R = ball.matrix()
>>> numpy.allclose(numpy.sum(R), 0.2055924)
True
>>> ball.next()
"""
def __init__(self, initial=None):
"""Initialize virtual trackball control.
initial : quaternion or rotation matrix
"""
self._axis = None
self._axes = None
self._radius = 1.0
self._center = [0.0, 0.0]
self._vdown = numpy.array([0, 0, 1], dtype=numpy.float64)
self._constrain = False
if initial is None:
self._qdown = numpy.array([0, 0, 0, 1], dtype=numpy.float64)
else:
initial = numpy.array(initial, dtype=numpy.float64)
if initial.shape == (4, 4):
self._qdown = quaternion_from_matrix(initial)
elif initial.shape == (4, ):
initial /= vector_norm(initial)
self._qdown = initial
else:
raise ValueError("initial not a quaternion or matrix.")
self._qnow = self._qpre = self._qdown
def place(self, center, radius):
"""Place Arcball, e.g. when window size changes.
center : sequence[2]
Window coordinates of trackball center.
radius : float
Radius of trackball in window coordinates.
"""
self._radius = float(radius)
self._center[0] = center[0]
self._center[1] = center[1]
def setaxes(self, *axes):
"""Set axes to constrain rotations."""
if axes is None:
self._axes = None
else:
self._axes = [unit_vector(axis) for axis in axes]
def setconstrain(self, constrain):
"""Set state of constrain to axis mode."""
self._constrain = constrain == True
def getconstrain(self):
"""Return state of constrain to axis mode."""
return self._constrain
def down(self, point):
"""Set initial cursor window coordinates and pick constrain-axis."""
self._vdown = arcball_map_to_sphere(point, self._center, self._radius)
self._qdown = self._qpre = self._qnow
if self._constrain and self._axes is not None:
self._axis = arcball_nearest_axis(self._vdown, self._axes)
self._vdown = arcball_constrain_to_axis(self._vdown, self._axis)
else:
self._axis = None
def drag(self, point):
"""Update current cursor window coordinates."""
vnow = arcball_map_to_sphere(point, self._center, self._radius)
if self._axis is not None:
vnow = arcball_constrain_to_axis(vnow, self._axis)
self._qpre = self._qnow
t = numpy.cross(self._vdown, vnow)
if numpy.dot(t, t) < _EPS:
self._qnow = self._qdown
else:
q = [t[0], t[1], t[2], numpy.dot(self._vdown, vnow)]
self._qnow = quaternion_multiply(q, self._qdown)
def next(self, acceleration=0.0):
"""Continue rotation in direction of last drag."""
q = quaternion_slerp(self._qpre, self._qnow, 2.0+acceleration, False)
self._qpre, self._qnow = self._qnow, q
def matrix(self):
"""Return homogeneous rotation matrix."""
return quaternion_matrix(self._qnow)
def arcball_map_to_sphere(point, center, radius):
"""Return unit sphere coordinates from window coordinates."""
v = numpy.array(((point[0] - center[0]) / radius,
(center[1] - point[1]) / radius,
0.0), dtype=numpy.float64)
n = v[0]*v[0] + v[1]*v[1]
if n > 1.0:
v /= math.sqrt(n) # position outside of sphere
else:
v[2] = math.sqrt(1.0 - n)
return v
def arcball_constrain_to_axis(point, axis):
"""Return sphere point perpendicular to axis."""
v = numpy.array(point, dtype=numpy.float64, copy=True)
a = numpy.array(axis, dtype=numpy.float64, copy=True)
v -= a * numpy.dot(a, v) # on plane
n = vector_norm(v)
if n > _EPS:
if v[2] < 0.0:
v *= -1.0
v /= n
return v
if a[2] == 1.0:
return numpy.array([1, 0, 0], dtype=numpy.float64)
return unit_vector([-a[1], a[0], 0])
def arcball_nearest_axis(point, axes):
"""Return axis, which arc is nearest to point."""
point = numpy.array(point, dtype=numpy.float64, copy=False)
nearest = None
mx = -1.0
for axis in axes:
t = numpy.dot(arcball_constrain_to_axis(point, axis), point)
if t > mx:
nearest = axis
mx = t
return nearest
# epsilon for testing whether a number is close to zero
_EPS = numpy.finfo(float).eps * 4.0
# axis sequences for Euler angles
_NEXT_AXIS = [1, 2, 0, 1]
# map axes strings to/from tuples of inner axis, parity, repetition, frame
_AXES2TUPLE = {
'sxyz': (0, 0, 0, 0), 'sxyx': (0, 0, 1, 0), 'sxzy': (0, 1, 0, 0),
'sxzx': (0, 1, 1, 0), 'syzx': (1, 0, 0, 0), 'syzy': (1, 0, 1, 0),
'syxz': (1, 1, 0, 0), 'syxy': (1, 1, 1, 0), 'szxy': (2, 0, 0, 0),
'szxz': (2, 0, 1, 0), 'szyx': (2, 1, 0, 0), 'szyz': (2, 1, 1, 0),
'rzyx': (0, 0, 0, 1), 'rxyx': (0, 0, 1, 1), 'ryzx': (0, 1, 0, 1),
'rxzx': (0, 1, 1, 1), 'rxzy': (1, 0, 0, 1), 'ryzy': (1, 0, 1, 1),
'rzxy': (1, 1, 0, 1), 'ryxy': (1, 1, 1, 1), 'ryxz': (2, 0, 0, 1),
'rzxz': (2, 0, 1, 1), 'rxyz': (2, 1, 0, 1), 'rzyz': (2, 1, 1, 1)}
_TUPLE2AXES = dict((v, k) for k, v in _AXES2TUPLE.items())
# helper functions
def vector_norm(data, axis=None, out=None):
"""Return length, i.e. eucledian norm, of ndarray along axis.
>>> v = numpy.random.random(3)
>>> n = vector_norm(v)
>>> numpy.allclose(n, numpy.linalg.norm(v))
True
>>> v = numpy.random.rand(6, 5, 3)
>>> n = vector_norm(v, axis=-1)
>>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=2)))
True
>>> n = vector_norm(v, axis=1)
>>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=1)))
True
>>> v = numpy.random.rand(5, 4, 3)
>>> n = numpy.empty((5, 3), dtype=numpy.float64)
>>> vector_norm(v, axis=1, out=n)
>>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=1)))
True
>>> vector_norm([])
0.0
>>> vector_norm([1.0])
1.0
"""
data = numpy.array(data, dtype=numpy.float64, copy=True)
if out is None:
if data.ndim == 1:
return math.sqrt(numpy.dot(data, data))
data *= data
out = numpy.atleast_1d(numpy.sum(data, axis=axis))
numpy.sqrt(out, out)
return out
else:
data *= data
numpy.sum(data, axis=axis, out=out)
numpy.sqrt(out, out)
def unit_vector(data, axis=None, out=None):
"""Return ndarray normalized by length, i.e. eucledian norm, along axis.
>>> v0 = numpy.random.random(3)
>>> v1 = unit_vector(v0)
>>> numpy.allclose(v1, v0 / numpy.linalg.norm(v0))
True
>>> v0 = numpy.random.rand(5, 4, 3)
>>> v1 = unit_vector(v0, axis=-1)
>>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=2)), 2)
>>> numpy.allclose(v1, v2)
True
>>> v1 = unit_vector(v0, axis=1)
>>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=1)), 1)
>>> numpy.allclose(v1, v2)
True
>>> v1 = numpy.empty((5, 4, 3), dtype=numpy.float64)
>>> unit_vector(v0, axis=1, out=v1)
>>> numpy.allclose(v1, v2)
True
>>> list(unit_vector([]))
[]
>>> list(unit_vector([1.0]))
[1.0]
"""
if out is None:
data = numpy.array(data, dtype=numpy.float64, copy=True)
if data.ndim == 1:
data /= math.sqrt(numpy.dot(data, data))
return data
else:
if out is not data:
out[:] = numpy.array(data, copy=False)
data = out
length = numpy.atleast_1d(numpy.sum(data*data, axis))
numpy.sqrt(length, length)
if axis is not None:
length = numpy.expand_dims(length, axis)
data /= length
if out is None:
return data
def random_vector(size):
"""Return array of random doubles in the half-open interval [0.0, 1.0).
>>> v = random_vector(10000)
>>> numpy.all(v >= 0.0) and numpy.all(v < 1.0)
True
>>> v0 = random_vector(10)
>>> v1 = random_vector(10)
>>> numpy.any(v0 == v1)
False
"""
return numpy.random.random(size)
def inverse_matrix(matrix):
"""Return inverse of square transformation matrix.
>>> M0 = random_rotation_matrix()
>>> M1 = inverse_matrix(M0.T)
>>> numpy.allclose(M1, numpy.linalg.inv(M0.T))
True
>>> for size in range(1, 7):
... M0 = numpy.random.rand(size, size)
... M1 = inverse_matrix(M0)
... if not numpy.allclose(M1, numpy.linalg.inv(M0)): print size
"""
return numpy.linalg.inv(matrix)
def concatenate_matrices(*matrices):
"""Return concatenation of series of transformation matrices.
>>> M = numpy.random.rand(16).reshape((4, 4)) - 0.5
>>> numpy.allclose(M, concatenate_matrices(M))
True
>>> numpy.allclose(numpy.dot(M, M.T), concatenate_matrices(M, M.T))
True
"""
M = numpy.identity(4)
for i in matrices:
M = numpy.dot(M, i)
return M
def is_same_transform(matrix0, matrix1):
"""Return True if two matrices perform same transformation.
>>> is_same_transform(numpy.identity(4), numpy.identity(4))
True
>>> is_same_transform(numpy.identity(4), random_rotation_matrix())
False
"""
matrix0 = numpy.array(matrix0, dtype=numpy.float64, copy=True)
matrix0 /= matrix0[3, 3]
matrix1 = numpy.array(matrix1, dtype=numpy.float64, copy=True)
matrix1 /= matrix1[3, 3]
return numpy.allclose(matrix0, matrix1)
def _import_module(module_name, warn=True, prefix='_py_', ignore='_'):
"""Try import all public attributes from module into global namespace.
Existing attributes with name clashes are renamed with prefix.
Attributes starting with underscore are ignored by default.
Return True on successful import.
"""
try:
module = __import__(module_name)
except ImportError:
if warn:
warnings.warn("Failed to import module " + module_name)
else:
for attr in dir(module):
if ignore and attr.startswith(ignore):
continue
if prefix:
if attr in globals():
globals()[prefix + attr] = globals()[attr]
elif warn:
warnings.warn("No Python implementation of " + attr)
globals()[attr] = getattr(module, attr)
return True
#!/usr/bin/env python
import unittest
import cvtestutils
from cv import *
class cmp_test(unittest.TestCase):
def setUp(self):
self.w=17
self.h=17
self.x0 = cvCreateMat(self.w,self.h,CV_32F)
self.x1 = cvCreateMat(self.w,self.h,CV_32F)
cvSet(self.x0, cvScalarAll(0.0))
cvSet(self.x1, cvScalarAll(1.0))
def check_format(self, y):
assert( y.rows == self.h )
assert( y.cols == self.w )
assert( CV_MAT_DEPTH(y.type)==CV_8U )
def check_allzero(self, y):
assert( cvCountNonZero(y)==0 )
def check_all255(self, y):
nonzero=cvCountNonZero(y)
assert( nonzero==self.w*self.h )
sum = cvSum(y)[0]
assert( sum == self.w*self.h*255 )
def test_CvMat_gt(self):
y=self.x1>0
self.check_format( y )
self.check_all255( y )
y=self.x0>0
self.check_format( y )
self.check_allzero( y )
def test_CvMat_gte(self):
y=self.x1>=0
self.check_format( y )
self.check_all255( y )
y=self.x0>=0
self.check_format( y )
self.check_all255( y )
def test_CvMat_lt(self):
y=self.x1<1
self.check_format( y )
self.check_allzero( y )
y=self.x0<1
self.check_format( y )
self.check_all255( y )
def test_CvMat_lte(self):
y=self.x1<=1
self.check_format( y )
self.check_all255( y )
y=self.x0<=1
self.check_format( y )
def suite():
return unittest.TestLoader().loadTestsFromTestCase(cmp_test)
if __name__ == '__main__':
unittest.TextTestRunner(verbosity=2).run(suite())
# cvtestutils.py
#
# This module is meant to aid writing and running Python-based tests
# within the OpenCV tree.
#
# 2009-01-23, Roman Stanchak <rstanchak@gmail.com>
#
#
# Upon importing, this module adds the following python module
# directories from the dev tree to sys.path (i.e. PYTHON_PATH):
# opencv/interfaces/swig/python and opencv/lib
#
# Using it in a test case is simple, just be sure to import
# cvtestutils before cv, highgui, etc
#
# Usage:
# import cvtestutils
# import cv
import os
import imp
import sys
def top_srcdir():
"""
Return a string containing the top-level source directory in the OpenCV tree
"""
dir = os.path.dirname(os.path.realpath(__file__))
# top level dir should be two levels up from this file
return os.path.realpath( os.path.join( dir, '..', '..' ) )
def top_builddir():
"""
Return a string containing the top-level build directory in the OpenCV tree.
Either returns realpath(argv[1]) or top_srcdir();
"""
if len(sys.argv)>1: return os.path.realpath( sys.argv[1] );
else: return top_srcdir();
def initpath():
"""
Prepend the python module directories from the dev tree to sys.path
(i.e. PYTHON_PATH)
"""
# add path for OpenCV source directory (for adapters.py)
moduledir = os.path.join(top_srcdir(), 'interfaces','swig','python')
moduledir = os.path.realpath(moduledir)
sys.path.insert(0, moduledir)
# add path for OpenCV build directory
moduledir = os.path.join(top_builddir(), 'interfaces','swig','python')
moduledir = os.path.realpath(moduledir)
sys.path.insert(0, moduledir)
libdir = os.path.join(top_builddir(), 'lib' )
libdir = os.path.realpath(libdir)
sys.path.insert(0, libdir)
def which():
"""
Print the directory containing cv.py
"""
import cv
print "Using OpenCV Python in: " + os.path.dirname(cv.__file__)
def datadir():
"""
Return a string containing the full path to the python testdata directory
"""
return os.path.sep.join([top_srcdir(), '..', 'opencv_extra', 'testdata', 'python'])
### Module Initialization
try:
if MODULE_LOADED:
pass
except NameError:
initpath()
which()
MODULE_LOADED=1
#!/usr/bin/env python
# 2009-01-16, Xavier Delacour <xavier.delacour@gmail.com>
import unittest
from numpy import *;
from numpy.linalg import *;
import sys;
import cvtestutils
from cv import *;
from adaptors import *;
def planted_neighbors(query_points, R = .4):
n,d = query_points.shape
data = zeros(query_points.shape)
for i in range(0,n):
a = random.rand(d)
a = random.rand()*R*a/sqrt(sum(a**2))
data[i] = query_points[i] + a
return data
class feature_tree_test(unittest.TestCase):
def test_kdtree_basic(self):
n = 1000;
d = 64;
query_points = random.rand(n,d)*2-1;
data = planted_neighbors(query_points)
tr = cvCreateKDTree(data);
indices,dist = cvFindFeatures(tr, query_points, 1, 100);
correct = sum([i == j for j,i in enumerate(indices)])
assert(correct >= n * .75);
def test_spilltree_basic(self):
n = 1000;
d = 64;
query_points = random.rand(n,d)*2-1;
data = planted_neighbors(query_points)
tr = cvCreateSpillTree(data);
indices,dist = cvFindFeatures(tr, query_points, 1, 100);
correct = sum([i == j for j,i in enumerate(indices)])
assert(correct >= n * .75);
def suite():
return unittest.TestLoader().loadTestsFromTestCase(feature_tree_test)
if __name__ == '__main__':
suite = suite()
unittest.TextTestRunner(verbosity=2).run(suite)
"""
This script will test highgui's video reading functionality
for a given parameter RAW formats.
"""
# needed for sys.exit(int) and .works file handling
import os
import sys
import works
from works import *
# import the necessary things for OpenCV
from highgui import *
from cv import *
# some defines
TESTNAME = "cvCreateFileCapture"
REQUIRED = []
PREFIX = os.path.join(os.environ["srcdir"],"../../opencv_extra/testdata/python/videos/qcif_")
EXTENSION= ".avi"
# this functions tries to open a videofile
# using the filename PREFIX+FORMAT+.EXTENSION and returns True/False
# on success/fail.
def video_ok( FORMAT ):
# check requirements and delete old .works file
if not works.check_files( REQUIRED, TESTNAME+FORMAT ):
return false
filename = PREFIX+FORMAT+EXTENSION
video = cvCreateFileCapture(PREFIX+FORMAT+EXTENSION)
if video is None:
sys.exit(1)
works.set_file( TESTNAME+FORMAT )
return True
#! /usr/bin/env python
"""
This script will test highgui's video reading functionality
for RAW RGB .avi files
"""
# pixel format to check
FORMAT = "RGB"
# import check routine
import cvCreateFileCapture
# check video file of format FORMAT,
# the function also exits and returns
# 0,1 or 77 accordingly.
cvCreateFileCapture.video_ok(FORMAT)
#! /usr/bin/env python
"""
This script will test highgui's video reading functionality
for RAW RGBA (dummy alpha channel) .avi files
"""
# pixel format to check
FORMAT = "RGBA"
# import check routine
import cvCreateFileCapture
# check video file of format FORMAT,
# the function also exits and returns
# 0,1 or 77 accordingly.
cvCreateFileCapture.video_ok(FORMAT)
#! /usr/bin/env python
"""
This script will test highgui's video reading functionality
for RAW UYVY .avi files
"""
# pixel format to check
FORMAT = "UYVY"
# import check routine
import cvCreateFileCapture
# check video file of format FORMAT,
# the function also exits and returns
# 0,1 or 77 accordingly.
cvCreateFileCapture.video_ok(FORMAT)
#! /usr/bin/env python
"""
This script will test highgui's video reading functionality
for RAW Y8 (luminance only) .avi files
"""
# pixel format to check
FORMAT = "Y8"
# import check routine
import cvCreateFileCapture
# check video file of format FORMAT,
# the function also exits and returns
# 0,1 or 77 accordingly.
cvCreateFileCapture.video_ok(FORMAT)
#! /usr/bin/env python
"""
This script will test highgui's video reading functionality
for RAW YUY2 .avi files
"""
# pixel format to check
FORMAT = "YUY2"
# import check routine
import cvCreateFileCapture
# check video file of format FORMAT,
# the function also exits and returns
# 0,1 or 77 accordingly.
cvCreateFileCapture.video_ok(FORMAT)
#! /usr/bin/env python
"""
This script will test highgui's video reading functionality
for RAW YV12 .avi files
"""
# pixel format to check
FORMAT = "YV12"
# import check routine
import cvCreateFileCapture
# check video file of format FORMAT,
# the function also exits and returns
# 0,1 or 77 accordingly.
cvCreateFileCapture.video_ok(FORMAT)
#! /usr/bin/env python
"""
This script will test highgui's video reading functionality
for RAW YV16 .avi files
"""
# pixel format to check
FORMAT = "YV16"
# import check routine
import cvCreateFileCapture
# check video file of format FORMAT,
# the function also exits and returns
# 0,1 or 77 accordingly.
cvCreateFileCapture.video_ok(FORMAT)
#! /usr/bin/env python
"""
This script will test highgui's video reading functionality
for RAW YVU9 .avi files
"""
# pixel format to check
FORMAT = "YVU9"
# import check routine
import cvCreateFileCapture
# check video file of format FORMAT,
# the function also exits and returns
# 0,1 or 77 accordingly.
cvCreateFileCapture.video_ok(FORMAT)
#! /usr/bin/env python
"""
This script will test highgui's trackbar functionality
"""
# name if this test and it's requirements
TESTNAME = "cvCreateTrackbar"
REQUIRED = ["cvShowImage"]
# needed for sys.exit(int) and .works file handling
import os
import sys
import works
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# import the necessary things for OpenCV
from highgui import *
from cv import *
# some definitions
win_name = "testing..."
bar_name = "brightness"
bar_count= 100
# position of imagefiles we need
PREFIX=os.path.join(os.environ["srcdir"],"../../opencv_extra/testdata/python/images/")
# 'moved' indicates if trackbar has been moved
moved = False
# 'range' indicates if trackbar was outside range [0..bar_count]
range = False
# function to call on a trackbar event
def trackcall( p ):
# Trackbar position must be in [0..bar_count]
if (p > bar_count or p < 0):
globals()["range"] = True
cvConvertScale( image, image2,float(p)/float(bar_count) )
cvShowImage( win_name, image2 );
globals()["moved"] = True
# create output window
cvNamedWindow(win_name,CV_WINDOW_AUTOSIZE)
image = cvLoadImage(PREFIX+"cvCreateTrackbar.jpg")
image2 = cvLoadImage(PREFIX+"cvCreateTrackbar.jpg")
cvShowImage(win_name,image)
# create the trackbar and save return value
res = cvCreateTrackbar( bar_name, win_name, 0, bar_count, trackcall )
# check return value
if res == 0:
# something went wrong, so return an error code
print "(ERROR) Couldn't create trackbar."
sys.exit(1)
# init. window with image
trackcall(bar_count/2)
# reset 'moved' indicator
moved = False
# now give the user 20 seconds to do some input
print "(INFO) Please move trackbar within the next 20 SECONDS to 'PASS' this test."
print "(HINT) You can complete this test prematurely by pressing any key."
print "(INFO) In the case of no user input, the test will be remarked as 'FAIL'."
key = cvWaitKey(20000)
if range:
# trackbar position value was outside allowed range [0..bar_count]
print "(ERROR) Trackbar position was outside range."
sys.exit(1)
if not moved and (key==-1):
# trackbar has not been moved
print "(ERROR) No user input detected."
sys.exit(1)
elif not moved and (key>0):
# 20sec. passed, trackbar has been moved
print "(INFO) No trackbar movement detected (but key pressed)."
sys.exit(77)
# create flag file for following tests
works.set_file(TESTNAME)
# return 0 ('PASS')
sys.exit(0)
#! /usr/bin/env python
"""
This script will test highgui's cvGetCaptureProperty() function
"""
# name of this test and it's requirements
TESTNAME = "cvGetCaptureProperty"
REQUIRED = ["cvCreateFileCapture"]
# needed for sys.exit(int) and .works file handling
import os
import sys
import works
# path to imagefiles we need
PREFIX=os.path.join(os.environ["srcdir"],"../../opencv_extra/testdata/python/videos/")
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# import the necessary things for OpenCV
from highgui import *
from cv import *
# create a video reader using the tiny video 'vd_uncompressed.avi'
video = cvCreateFileCapture(PREFIX+"uncompressed.avi")
# retrieve video dimensions and compare with known values
print str(cvGetCaptureProperty( video, CV_CAP_PROP_FOURCC ))
print "Checking image dimensions"
if cvGetCaptureProperty( video, CV_CAP_PROP_FRAME_WIDTH ) != 720:
sys.exit(1)
if cvGetCaptureProperty( video, CV_CAP_PROP_FRAME_HEIGHT ) != 576:
sys.exit(1)
print "pass"
print "Checking framerate"
if cvGetCaptureProperty( video, CV_CAP_PROP_FPS ) != 25:
sys.exit(1)
print "pass"
print str(cvGetCaptureProperty( video, CV_CAP_PROP_FOURCC ) )
# ATTENTION: We do not release the video reader, window or any image.
# This is bad manners, but Python and OpenCV don't care...
# create flag file for sollowing tests
works.set_file(TESTNAME)
# return 0 ('PASS')
sys.exit(0)
#! /usr/bin/env python
"""
This script will test highgui's Get/Set functionality for the trackbar
"""
# name of this test and it's requirements
TESTNAME = "cvGetSetTrackbarPos"
REQUIRED = ["cvCreateTrackbar"]
# needed for sys.exit(int) and .works file handling
import sys
import works
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# import the necessary things for OpenCV
from highgui import *
from cv import *
# some definitions
win_name = "testing..."
bar_name = "foo"
# little dummy function as callback for trackbar
def dummy(value):
pass
# create output window
cvNamedWindow(win_name,CV_WINDOW_AUTOSIZE)
# create our trackbar
cvCreateTrackbar( bar_name, win_name, 127, 255, dummy )
# trackbar pos must be 127
if cvGetTrackbarPos( bar_name, win_name ) != 127:
print "(ERROR) cvGetTrackbarPos() returned wrong value (!=127)."
sys.exit(1)
# set the trackbar to new position 255 and compare it
cvSetTrackbarPos( bar_name, win_name, 255 )
if cvGetTrackbarPos( bar_name, win_name ) != 255:
print "(ERROR) cvSetTrackbarPos() didn't set value correctly (!=255)."
sys.exit(1)
# create flag file for following tests
works.set_file(TESTNAME)
# return 0 (success)
sys.exit(0)
#! /usr/bin/env python
"""
This script will test highgui's window handle/name functionality
"""
# name of this test and it's requirements
TESTNAME = "cvGetWindowHandleName"
REQUIRED = ["cvNamedWindow"]
# needed for sys.exit(int) and .works file handling
import sys
import works
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# import the necessary things for OpenCV
from highgui import *
from cv import *
# some definitions
win_name = "testing..."
# create a window ( 'cvNamedWindow.works' says: "Ok, go for it!" )
cvNamedWindow(win_name,CV_WINDOW_AUTOSIZE)
# check if the window handle and the according name are correct
win_name_2 = cvGetWindowName( cvGetWindowHandle(win_name) )
if win_name_2!=win_name:
# print "(ERROR) Incorrect window handle/name."
sys.exit(1)
# destroy the window
cvDestroyWindow( win_name )
# create flag file for following tests
works.set_file(TESTNAME)
# return 0 ('PASS')
sys.exit(0)
#! /usr/bin/env python
"""
This script will test highgui's video reading functionality
"""
# name of this test and it's requirements
TESTNAME = "cvGrabFrame"
REQUIRED = ["cvCreateFileCaptureRGBA"]
# needed for sys.exit(int) and .works file handling
import os
import sys
import works
# path to imagefiles we need
PREFIX=os.path.join(os.environ["srcdir"],"../../opencv_extra/testdata/python/videos/")
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# import the necessary things for OpenCV
from highgui import *
from cv import *
# create a video reader using the tiny video 'uncompressed.avi'
video = cvCreateFileCapture(PREFIX+"uncompressed.avi")
# call cvGrabFrame to grab a frame and save return value
res = cvGrabFrame(video)
if res==0:
print "(ERROR) Couldn't call cvGrabFrame()."
sys.exit(1)
# ATTENTION: We do not release the video reader, window or any image.
# This is bad manners, but Python and OpenCV don't care...
# create flag file for sollowing tests
works.set_file(TESTNAME)
# return 0 ('PASS')
sys.exit(0)
#! /usr/bin/env python
"""
This script will test highgui's InitSystem function
ATTENTION: This test doesn't do much, yet, but cvInitSystem
is called with default parameters on the first highgui function call anyway.
"""
# name of this test and it's requirements
TESTNAME = "cvInitSystem"
REQUIRED = []
# needed for sys.exit(int) and .works file handling
import sys
import works
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED, TESTNAME):
sys.exit(77)
# import the necessary things for OpenCV
import highgui
# try to initialize the highgui system
# res = highgui.cvInitSystem(globals["0,characs)
# if res != 0:
# sys.exit(1)
# create flag file for the following tests
works.set_file(TESTNAME)
# return 0 ('PASS')
sys.exit(0)
"""
This script will test highgui's image loading functionality
for a given parameter of a file extension.
"""
# needed for sys.exit(int) and .works file handling
import os
import sys
import works
from works import *
#import the necessary things for OpenCV
from highgui import *
from cv import *
# some defines
TESTNAME = "cvLoadImage"
REQUIRED = []
# path to imagefiles we need
PREFIX=os.path.join(os.environ["srcdir"],"../../opencv_extra/testdata/python/images/baboon_256x256")
# this functions tries to open an imagefile
# using the filename PREFIX.EXTENSION and returns True/False
# on success/fail.
def image_ok( EXTENSION ):
# check requirements and delete old .works file
WORKSNAME = TESTNAME+'.'+EXTENSION
if not works.check_files( REQUIRED, WORKSNAME ):
print "worksfile "+WORKSNAME+" not found."
return False
image = cvLoadImage(PREFIX+'.'+EXTENSION)
if image is None:
return False
else:
works.set_file( TESTNAME+EXTENSION )
return True
#! /usr/bin/env python
"""
This script will test highgui's image loading functionality
for .bmp files
"""
# file extension to check
EXTENSION = "bmp"
# import check routine
import cvLoadImage
import sys
# check image file of extension EXTENSION,
# the function also exits and returns
# 0,1 or 77 accordingly.
if cvLoadImage.image_ok(EXTENSION):
sys.exit(0)
else:
sys.exit(1)
#! /usr/bin/env python
"""
This script will test highgui's image loading functionality
for .jpg files
"""
# file extension to check
EXTENSION = "jpg"
# import check routine
import cvLoadImage
import sys
# check image file of extension EXTENSION,
# the function also exits and returns
# 0,1 or 77 accordingly.
if cvLoadImage.image_ok(EXTENSION):
sys.exit(0)
else:
sys.exit(1)
#! /usr/bin/env python
"""
This script will test highgui's image loading functionality
for .png files
"""
# file extension to check
EXTENSION = "png"
# import check routine
import cvLoadImage
import sys
# check image file of extension EXTENSION,
# the function also exits and returns
# 0,1 or 77 accordingly.
if cvLoadImage.image_ok(EXTENSION):
sys.exit(0)
else:
sys.exit(1)
#! /usr/bin/env python
"""
This script will test highgui's image loading functionality
for .ppm files
"""
# file extension to check
EXTENSION = "ppm"
# import check routine
import cvLoadImage
import sys
# check image file of extension EXTENSION,
# the function also exits and returns
# 0,1 or 77 accordingly.
if cvLoadImage.image_ok(EXTENSION):
sys.exit(0)
else:
sys.exit(1)
#! /usr/bin/env python
"""
This script will test highgui's image loading functionality
for .sr files
"""
# file extension to check
EXTENSION = "sr"
# import check routine
import cvLoadImage
import sys
# check image file of extension EXTENSION,
# the function also exits and returns
# 0,1 or 77 accordingly.
if cvLoadImage.image_ok(EXTENSION):
sys.exit(0)
else:
sys.exit(1)
#! /usr/bin/env python
"""
This script will test highgui's image loading functionality
for .tiff files
"""
# file extension to check
EXTENSION = "tiff"
# import check routine
import cvLoadImage
import sys
# check image file of extension EXTENSION,
# the function also exits and returns
# 0,1 or 77 accordingly.
if cvLoadImage.image_ok(EXTENSION):
sys.exit(0)
else:
sys.exit(1)
#! /usr/bin/env python
"""
This script will test highgui's window move/resize functionality
"""
# name of this test and it's requirements
TESTNAME = "cvMoveResizeWindow"
REQUIRED = ["cvNamedWindow"]
# needed for sys.exit(int) and .works file handling
import sys
import works
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# import the necessary things for OpenCV
from highgui import *
from cv import *
# create a window
cvNamedWindow(TESTNAME, CV_WINDOW_AUTOSIZE)
# move the window around
cvMoveWindow(TESTNAME, 0, 0)
cvMoveWindow(TESTNAME, 100, 0)
cvMoveWindow(TESTNAME, 100, 100)
cvMoveWindow(TESTNAME, 0, 100)
# resize the window
for i in range(1,10):
cvResizeWindow(TESTNAME, i*100, i*100)
# destroy the window
cvDestroyWindow(TESTNAME)
# create flag file for following tests
works.set_file(TESTNAME)
# return 0 (success)
sys.exit(0)
#! /usr/bin/env python
"""
This script will test highgui's window functionality
"""
# name of this test and it's requirements
TESTNAME = "cvNamedWindow"
REQUIRED = []
# needed for sys.exit(int) and .works file handling
import sys
import works
# check requirements and delete flag file if it exists
if not works.check_files( REQUIRED, TESTNAME ):
sys.exit(77)
# import the necessary things for OpenCV
from highgui import *
from cv import *
# some definitions
win_name = "testing..."
# create a window and save return code
res = cvNamedWindow(win_name,CV_WINDOW_AUTOSIZE)
# if returncode is ok, window creation was sucessful
if res == 0:
# something went wrong, so return an errorcode
sys.exit(1)
# destroy the window
cvDestroyWindow( win_name )
# create flag file for following tests
works.set_file(TESTNAME)
# return 0 ('PASS')
sys.exit(0)
#! /usr/bin/env python
"""
This script will test highgui's cvQueryFrame() function
"""
# name of this test and it's requirements
TESTNAME = "cvQueryFrame"
REQUIRED = ["cvGrabFrame","cvRetrieveFrame"]
# needed for sys.exit(int) and .works file handling
import os
import sys
import works
# path to imagefiles we need
PREFIX=os.path.join(os.environ["srcdir"],"../../opencv_extra/testdata/python/videos/")
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# import the necessary things for OpenCV
from highgui import *
from cv import *
# create a video reader using the tiny video 'uncompressed.avi'
video = cvCreateFileCapture(PREFIX+"uncompressed.avi")
# call cvQueryFrame for 30 frames and check if the returned image is ok
for k in range(0,30):
image = cvQueryFrame( video )
if image is None:
# returned image is not a correct IplImage (pointer),
# so return an error code
sys.exit(77)
# ATTENTION: We do not release the video reader, window or any image.
# This is bad manners, but Python and OpenCV don't care...
# create flag file for sollowing tests
works.set_file(TESTNAME)
# return 0 ('PASS')
sys.exit(0)
#! /usr/bin/env python
"""
This script will test highgui's cvRetrieveFrame function
"""
# name of this test and it's requirements
TESTNAME = "cvRetrieveFrame"
REQUIRED = ["cvGrabFrame"]
# needed for sys.exit(int) and .works file handling
import os
import sys
import works
# path to imagefiles we need
PREFIX=os.path.join(os.environ["srcdir"],"../../opencv_extra/testdata/python/videos/")
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# import the necessary things for OpenCV
from highgui import *
from cv import *
# create a video reader using the tiny video 'uncompressed.avi'
video = cvCreateFileCapture(PREFIX+"uncompressed.avi")
# call cvGrabFrame to grab a frame from video
res=cvGrabFrame(video)
if res==0:
print "(ERROR) Couldn't call cvGrabFrame()"
sys.exit(1)
# call cvRetrieveFrame and check if returned image is valid
image = cvRetrieveFrame(video)
if image is None:
# returned image is not a correct IplImage (pointer),
# so return an error code
sys.exit(1)
# ATTENTION: We do not release the video reader or image.
# This is bad manners, but Python and OpenCV don't care...
# create flag file for sollowing tests
works.set_file(TESTNAME)
# return 0 ('PASS')
sys.exit(0)
#! /usr/bin/env python
"""
This script will test highgui's image saving functionality
"""
# name if this test and it's requirements
TESTNAME = "cvSaveImage"
REQUIRED = ["cvLoadImagejpg"]
#needed for sys.exit(int), filehandling and .works file checks
import os
import sys
import works
# path to imagefiles we need
PREFIX=os.path.join(os.environ["srcdir"],"../../opencv_extra/testdata/python/images/")
# delete old .works file and check requirements
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# import the necessary things for OpenCV
from highgui import *
from cv import *
# our temporary test file
file_name = "./highgui_testfile.bmp"
# try to load an image from a file
image = cvLoadImage(PREFIX+"baboon.jpg")
# if the returned object is not Null, loading was successful.
if image==0:
print "(INFO) Couldn't load test image. Skipping rest of this test."
sys.exit(77)
res = cvSaveImage("./highgui_testfile.bmp", image)
if res == 0:
print "(ERROR) Couldn't save image to '"+file_name+"'."
sys.exit(1)
# remove temporary file
os.remove(file_name)
# create flag file
works.set_file(TESTNAME)
# return 0 ('PASS')
sys.exit(0)
#! /usr/bin/env python
"""
This script will test highgui's mouse functionality
"""
# name of this test and it's requirements
TESTNAME = "cvSetMouseCallback"
REQUIRED = ["cvShowImage"]
# needed for sys.exit(int) and .works file handling
import os
import sys
import works
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# import the necessary things for OpenCV
from highgui import *
from cv import *
# global variable which stores information about the pressed mousebuttons
mouse_events = [False,False,False,False,False,False,False,False,False,False]
event_detected = False
# some definitions
win_name = "testing..."
EVENTS = ['CV_EVENT_MOUSEMOVE', 'CV_EVENT_LBUTTONDOWN', 'CV_EVENT_RBUTTONDOWN', 'CV_EVENT_MBUTTONDOWN', 'CV_EVENT_LBUTTONUP',
'CV_EVENT_RBUTTONUP', 'CV_EVENT_MBUTTONUP' , 'CV_EVENT_LBUTTONDBLCLK','CV_EVENT_RBUTTONDBLCLK','CV_EVENT_MBUTTONDBLCLK']
# our callback function, 5th parameter not used here.
def callback_function(event,x,y,flag,param):
globals()["event_detected"] = True
# check if event already occured; if not, output info about new event.
if globals()["mouse_events"][event] == False:
print "Event "+globals()["EVENTS"][event]+" detected."
globals()["mouse_events"][event] = True
return
# create a window ('cvNamedWindow.works' exists, so it must work)
cvNamedWindow(win_name,CV_WINDOW_AUTOSIZE)
# show the baboon in the window
PREFIX = os.path.join(os.environ["srcdir"],"../../opencv_extra/testdata/python/images/")
cvShowImage(win_name, cvLoadImage(PREFIX+"cvSetMouseCallback.jpg"))
# assign callback function 'callback_function' to window, no parameters used here
cvSetMouseCallback( win_name, callback_function )
# give the user information about the test and wait for input
print "(INFO) Please hover the mouse over the baboon image and press"
print "(INFO) your available mousebuttons inside the window to 'PASS' this test."
print "(INFO) You may also perform double-clicks."
print "(INFO) Press a key on your keyboard ot wait 20 seconds to continue."
print "(HINT) If no mouseevent was detected this test will be remarked as 'FAIL'."
# now wait 20 seconds for user to press a key
cvWaitKey(20000)
# reset mouse callback
cvSetMouseCallback( win_name, 0 )
# destroy the window
cvDestroyWindow( win_name )
# check if a mouse event had beed detected
if not event_detected:
# user didn't interact properly or mouse functionality doesn't work correctly
print "(ERROR) No mouse event detected."
sys.exit(1)
# create flag file for following tests
works.set_file(TESTNAME)
# return 0 (success)
sys.exit(0)
#! /usr/bin/env python
"""
This script will test highgui's window functionality
"""
# name of this test and it's requirements
TESTNAME = "cvShowImage"
REQUIRED = ["cvLoadImagejpg", "cvNamedWindow"]
# needed for sys.exit(int) and .works file handling
import os
import sys
import works
# path to imagefiles we need
PREFIX=os.path.join(os.environ["srcdir"],"../../opencv_extra/testdata/python/images/")
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# import the necessary things for OpenCV
from highgui import *
from cv import *
# defined window name
win_name = "testing..."
# we expect a window to be createable, thanks to 'cvNamedWindow.works'
cvNamedWindow(win_name, CV_WINDOW_AUTOSIZE)
# we expect the image to be loadable, thanks to 'cvLoadImage.works'
image = cvLoadImage(PREFIX+"cvShowImage.jpg")
if image is None:
print "(ERROR) Couldn't load image "+PREFIX+"cvShowImage.jpg"
sys.exit(1)
# try to show image in window
res = cvShowImage( win_name, image )
cvWaitKey(0)
if res == 0:
cvReleaseImage(image)
cvDestroyWindow(win_name)
sys.exit(1)
# destroy window
cvDestroyWindow(win_name)
# create flag file for following tests
works.set_file(TESTNAME)
# return 0 ('PASS')
sys.exit(0)
#! /usr/bin/env python
"""
This script will test highgui's cvWaitKey(int) function
"""
# name of this test and it's requirements
TESTNAME = "cvWaitKey"
REQUIRED = ["cvShowImage"]
# needed for sys.exit(int) and .works file handling
import os
import sys
import works
# path to imagefiles we need
PREFIX=os.path.join(os.environ["srcdir"],"../../opencv_extra/testdata/python/images/")
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED, TESTNAME):
sys.exit(77)
# import the necessary things for OpenCV
from highgui import *
# request some user input
print "(INFO) Press anykey within the next 20 seconds to 'PASS' this test."
# create a dummy window which reacts on cvWaitKey()
cvNamedWindow(TESTNAME, CV_WINDOW_AUTOSIZE)
# display an image
cvShowImage(TESTNAME, cvLoadImage(PREFIX+"cvWaitKey.jpg"))
# wait 20 seconds using cvWaitKey(20000),
# return 'FAIL' if no key has been pressed.
if cvWaitKey(20000) == -1:
print "(ERROR) No key pressed, remarking as 'FAIL'."
sys.exit(1)
#create flag file for the following tests
works.set_file(TESTNAME)
# return 0 ('PASS')
sys.exit(0)
QCIF=["QCIF_00.bmp","QCIF_01.bmp","QCIF_02.bmp","QCIF_03.bmp","QCIF_04.bmp","QCIF_05.bmp",
"QCIF_06.bmp","QCIF_07.bmp","QCIF_08.bmp","QCIF_09.bmp","QCIF_10.bmp","QCIF_11.bmp",
"QCIF_12.bmp","QCIF_13.bmp","QCIF_14.bmp","QCIF_15.bmp","QCIF_16.bmp","QCIF_17.bmp",
"QCIF_18.bmp","QCIF_19.bmp","QCIF_20.bmp","QCIF_21.bmp","QCIF_22.bmp","QCIF_23.bmp",
"QCIF_24.bmp","QCIF_25.bmp","QCIF_26.bmp","QCIF_27.bmp","QCIF_28.bmp","QCIF_29.bmp"]
"""
This script will compare tho images and decides with a threshold
if these to images are "equal enough"
"""
# import the necessary things for OpenCV
from cv import *
from highgui import *
import frames
import sys
import os
PREFIX=os.path.join(os.environ["srcdir"],"../../opencv_extra/testdata/python/images/")
DisplayImages=False
if DisplayImages:
videowindow="video"
referencewindow="reference"
cvNamedWindow(videowindow,CV_WINDOW_AUTOSIZE)
cvNamedWindow(referencewindow,CV_WINDOW_AUTOSIZE)
# returns True/False if match/non-match
def match( image, index, thres ):
# load image from comparison set
QCIFcompare=cvLoadImage(PREFIX+frames.QCIF[index])
if QCIFcompare is None:
print "Couldn't open image "+PREFIX+frames.QCIF[index]+" for comparison!"
sys.exit(1)
# resize comparison image to input image dimensions
size=cvSize(image.width,image.height)
compare=cvCreateImage(size,IPL_DEPTH_8U,image.nChannels)
cvResize(QCIFcompare,compare)
# compare images
diff=cvNorm( image, compare, CV_RELATIVE_L2 )
if DisplayImages:
cvShowImage(videowindow,image)
cvShowImage(referencewindow,compare)
if diff<=thres:
cvWaitKey(200)
else:
print "index==",index,": max==",thres," is==",diff
cvWaitKey(5000)
cvReleaseImage(QCIFcompare)
cvReleaseImage(compare)
if diff<=thres:
return True
else:
return False
#! /usr/bin/env python
"""
This script checks HighGUI's cvQueryFrame function
on a 3GP-compressed .3gp file.
"""
# name if this test and it's requirements
TESTNAME = "query_3gp"
REQUIRED = []
ERRORS=[0.043,0.031,0.032,0.031,0.029,0.030,0.030,0.031,0.030,0.029,0.034,0.027,0.029,0.029,0.029,0.029,0.029,0.028,0.031,0.030,0.035,0.031,0.031,0.032,0.031,0.032,0.033,0.031,0.033]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import query_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='3gp.3gp'
# run check routine
result=query_test.query_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvQueryFrame function
on an .avi file containing uncompressed 24bit Bitmap frames.
"""
# name if this test and it's requirements
TESTNAME = "query_bmp24"
REQUIRED = []
ERRORS=[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import query_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='bmp24.avi'
# run check routine
result=query_test.query_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvQueryFrame function
on an .avi file containing uncompressed 32bit Bitmap frames.
"""
# name if this test and it's requirements
TESTNAME = "query_bmp32"
REQUIRED = []
ERRORS=[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import query_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='bmp32.avi'
# run check routine
result=query_test.query_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvQueryFrame function
on a DV-compressed .dv file.
"""
# name if this test and it's requirements
TESTNAME = "query_cinepak"
REQUIRED = []
ERRORS=[0.086,0.082,0.087,0.085,0.086,0.085,0.086,0.086,0.086,0.086,0.089,0.087,0.090,0.088,0.088,0.088,0.089,0.088,0.089,0.088,0.091,0.089,0.092,0.091,0.091,0.090,0.091,0.090,0.091]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import query_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='cinepak.avi'
# run check routine
result=query_test.query_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvQueryFrame function
on a DivX-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "query_divx"
REQUIRED = []
ERRORS=[0.084,0.081,0.085,0.083,0.085,0.083,0.085,0.085,0.084,0.084,0.087,0.086,0.088,0.086,0.087,0.086,0.086,0.086,0.087,0.086,0.089,0.087,0.090,0.089,0.089,0.088,0.089,0.089,0.089]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import query_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='divx.avi'
# run check routine
result=query_test.query_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvQueryFrame function
on a DV-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "query_dv_pal_progressive_avi"
REQUIRED = []
ERRORS=[0.051,0.047,0.051,0.050,0.052,0.049,0.051,0.050,0.050,0.051,0.054,0.052,0.053,0.052,0.055,0.052,0.053,0.052,0.053,0.052,0.056,0.055,0.056,0.055,0.058,0.055,0.056,0.055,0.056]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import query_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='dv_pal_progressive.avi'
# run check routine
result=query_test.query_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvQueryFrame function
on a DV-compressed .dv file.
"""
# name if this test and it's requirements
TESTNAME = "query_dv_pal_progressive_dv"
REQUIRED = []
ERRORS=[0.288,0.288,0.290,0.289,0.290,0.288,0.288,0.289,0.288,0.289,0.293,0.290,0.293,0.291,0.292,0.290,0.291,0.292,0.292,0.292,0.293,0.290,0.294,0.292,0.292,0.291,0.292,0.293,0.293]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import query_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='dv_pal_progressive.dv'
# run check routine
result=query_test.query_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvQueryFrame function
on a HuffYUV-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "query_huffyuv"
REQUIRED = []
ERRORS=[0.085,0.082,0.086,0.084,0.086,0.084,0.085,0.085,0.085,0.086,0.088,0.087,0.089,0.088,0.088,0.087,0.088,0.087,0.088,0.087,0.091,0.089,0.091,0.090,0.090,0.090,0.090,0.090,0.090]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import query_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='huffyuv.avi'
# run check routine
result=query_test.query_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvQueryFrame function
on an Intel Indeo-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "query_indeo"
REQUIRED = []
ERRORS=[0.085,0.082,0.086,0.084,0.086,0.084,0.085,0.085,0.085,0.086,0.088,0.087,0.089,0.088,0.088,0.087,0.088,0.087,0.088,0.087,0.091,0.089,0.091,0.090,0.090,0.090,0.090,0.090,0.090]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import query_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='indeo.avi'
# run check routine
result=query_test.query_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvQueryFrame function
on a MPEG4-compressed .mp4 file.
"""
# name if this test and it's requirements
TESTNAME = "query_mpeg4"
REQUIRED = []
ERRORS=[0.042,0.025,0.026,0.025,0.024,0.024,0.026,0.024,0.025,0.024,0.028,0.023,0.024,0.024,0.024,0.024,0.025,0.023,0.027,0.024,0.030,0.025,0.026,0.026,0.026,0.026,0.026,0.024,0.027]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import query_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='mpeg4.mp4'
# run check routine
result=query_test.query_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
"""
This script will test highgui's cvQueryFrame() function
for different video formats
"""
# import the necessary things for OpenCV and comparson routine
import os
from highgui import *
from cv import *
import match
# path to videos and images we need
PREFIX=os.path.join(os.environ["srcdir"],"../../opencv_extra/testdata/python/")
# this is the folder with the videos and images
# and name of output window
IMAGES = PREFIX+"images/"
VIDEOS = PREFIX+"videos/"
# testing routine, called for each entry in FILENAMES
# and compares each frame with corresponding frame in COMPARISON
def query_ok(FILENAME,ERRORS):
# create a video reader using the tiny videofile VIDEOS+FILENAME
video=cvCreateFileCapture(VIDEOS+FILENAME)
if video is None:
# couldn't open video (FAIL)
return 1
# call cvQueryFrame for 29 frames and check if the returned image is ok
for k in range(29):
image=cvQueryFrame(video)
if image is None:
# returned image is NULL (FAIL)
return 1
if not match.match(image,k,ERRORS[k]):
return 1
cvReleaseCapture(video)
# everything is fine (PASS)
return 0
#! /usr/bin/env python
"""
This script checks HighGUI's cvQueryFrame function
on an uncompressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "query_uncompressed"
REQUIRED = []
ERRORS=[0.085,0.082,0.086,0.084,0.086,0.084,0.085,0.085,0.085,0.086,0.088,0.087,0.089,0.088,0.088,0.087,0.088,0.087,0.088,0.087,0.091,0.089,0.091,0.090,0.090,0.090,0.090,0.090,0.090]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import query_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='uncompressed.avi'
# run check routine
result=query_test.query_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvQueryFrame function
on a WMV9-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "query_wmv9"
REQUIRED = []
ERRORS=[0.084,0.088,0.086,0.086,0.089,0.085,0.090,0.088,0.087,0.090,0.095,0.088,0.090,0.091,0.092,0.088,0.090,0.090,0.090,0.091,0.095,0.093,0.093,0.094,0.097,0.090,0.094,0.092,0.092]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import query_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='wmv9.avi'
# run check routine
result=query_test.query_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's frame seeking functionality
on a 3GP-compressed .3gp file.
"""
# name if this test and it's requirements
TESTNAME = "seek_frame_3gp"
REQUIRED = []
ERRORS=[0.043,0.031,0.032,0.031,0.029,0.030,0.030,0.031,0.030,0.029,0.034,0.027,0.029,0.029,0.029,0.029,0.029,0.028,0.031,0.030,0.035,0.031,0.031,0.032,0.031,0.032,0.033,0.031,0.033]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='3gp.3gp'
# run check routine
result=seek_test.seek_frame_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's frame seeking functionality
on an .avi file containing uncompressed 24bit Bitmap frames.
"""
# name if this test and it's requirements
TESTNAME = "seek_frame_bmp24"
REQUIRED = []
ERRORS=[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='bmp24.avi'
# run check routine
result=seek_test.seek_frame_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's frame seeking functionality
on an .avi file containing uncompressed 32bit Bitmap frames.
"""
# name if this test and it's requirements
TESTNAME = "seek_frame_bmp32"
REQUIRED = []
ERRORS=[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='bmp32.avi'
# run check routine
result=seek_test.seek_frame_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's frame seeking functionality
on a CinePak-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "seek_frame_cinepak"
REQUIRED = []
ERRORS=[0.086,0.082,0.087,0.085,0.086,0.085,0.086,0.086,0.086,0.086,0.089,0.087,0.090,0.088,0.088,0.088,0.089,0.088,0.089,0.088,0.091,0.089,0.092,0.091,0.091,0.090,0.091,0.090,0.091]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='cinepak.avi'
# run check routine
result=seek_test.seek_frame_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's frame seeking functionality
on a DivX-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "seek_frame_divx"
REQUIRED = []
ERRORS=[0.084,0.081,0.085,0.083,0.085,0.083,0.085,0.085,0.084,0.084,0.087,0.086,0.088,0.086,0.087,0.086,0.086,0.086,0.087,0.086,0.089,0.087,0.090,0.089,0.089,0.088,0.089,0.089,0.089]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='divx.avi'
# run check routine
result=seek_test.seek_frame_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's frame seeking functionality
on a DV-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "seek_frame_dv_pal_progressive_avi"
REQUIRED = []
ERRORS=[0.051,0.047,0.051,0.050,0.052,0.049,0.051,0.050,0.050,0.051,0.054,0.052,0.053,0.052,0.055,0.052,0.053,0.052,0.053,0.052,0.056,0.055,0.056,0.055,0.058,0.055,0.056,0.055,0.056]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='dv_pal_progressive.avi'
# run check routine
result=seek_test.seek_frame_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's frame seeking functionality
on a DV-compressed .dv file.
"""
# name if this test and it's requirements
TESTNAME = "seek_frame_dv_pal_progressive_dv"
REQUIRED = []
ERRORS=[0.288,0.288,0.290,0.289,0.290,0.288,0.288,0.289,0.288,0.289,0.293,0.290,0.293,0.291,0.292,0.290,0.291,0.292,0.292,0.292,0.293,0.290,0.294,0.292,0.292,0.291,0.292,0.293,0.293]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='dv_pal_progressive.dv'
# run check routine
result=seek_test.seek_frame_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's frame seeking functionality
on a HuffYUV-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "seek_frame_huffyuv"
REQUIRED = []
ERRORS=[0.085,0.082,0.086,0.084,0.086,0.084,0.085,0.085,0.085,0.086,0.088,0.087,0.089,0.088,0.088,0.087,0.088,0.087,0.088,0.087,0.091,0.089,0.091,0.090,0.090,0.090,0.090,0.090,0.090]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='huffyuv.avi'
# run check routine
result=seek_test.seek_frame_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's frame seeking functionality
on an Intel Indeo-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "seek_frame_indeo"
REQUIRED = []
ERRORS=[0.085,0.082,0.086,0.084,0.086,0.084,0.085,0.085,0.085,0.086,0.088,0.087,0.089,0.088,0.088,0.087,0.088,0.087,0.088,0.087,0.091,0.089,0.091,0.090,0.090,0.090,0.090,0.090,0.090]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='indeo.avi'
# run check routine
result=seek_test.seek_frame_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's frame seeking functionality
on a MPEG4-compressed .mp4 file.
"""
# name if this test and it's requirements
TESTNAME = "seek_frame_mp4"
REQUIRED = []
ERRORS=[0.042,0.025,0.026,0.025,0.024,0.024,0.026,0.024,0.025,0.024,0.028,0.023,0.024,0.024,0.024,0.024,0.025,0.023,0.027,0.024,0.030,0.025,0.026,0.026,0.026,0.026,0.026,0.024,0.027]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='mpeg4.mp4'
# run check routine
result=seek_test.seek_frame_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's frame seeking functionality
on an uncompressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "seek_frame_uncompressed"
REQUIRED = []
ERRORS=[0.085,0.082,0.086,0.084,0.086,0.084,0.085,0.085,0.085,0.086,0.088,0.087,0.089,0.088,0.088,0.087,0.088,0.087,0.088,0.087,0.091,0.089,0.091,0.090,0.090,0.090,0.090,0.090,0.090]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='uncompressed.avi'
# run check routine
result=seek_test.seek_frame_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's frame seeking functionality
on a WMV9-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "seek_frame_wmv9"
REQUIRED = []
ERRORS=[0.085,0.082,0.086,0.084,0.086,0.084,0.085,0.085,0.085,0.086,0.088,0.087,0.089,0.088,0.088,0.087,0.088,0.087,0.088,0.087,0.091,0.089,0.091,0.090,0.090,0.090,0.090,0.090,0.090]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='wmv9.avi'
# run check routine
result=seek_test.seek_frame_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
"""
This script will test highgui's seek functionality
for different video formats
"""
# import the necessary things for OpenCV and comparson routine
import os
#import python
#from python.highgui import *
#from python.cv import *
import match
from highgui import *
from cv import *
# path to videos and images we need
PREFIX=os.path.join(os.environ["srcdir"],"../../opencv_extra/testdata/python/")
# this is the folder with the videos and images
# and name of output window
IMAGES = PREFIX+"images/"
VIDEOS = PREFIX+"videos/"
show_frames=False
# testing routine, seeks through file and compares read images with frames in frames.QCIF[]
def seek_frame_ok(FILENAME,ERRORS):
# create a video reader using the tiny videofile VIDEOS+FILENAME
video=cvCreateFileCapture(VIDEOS+FILENAME)
if video is None:
# couldn't open video (FAIL)
return 1
if show_frames:
cvNamedWindow("test", CV_WINDOW_AUTOSIZE)
# skip 2 frames and read 3rd frame each until EOF and check if the read image is ok
for k in [0,3,6,9,12,15,18,21,24,27]:
cvSetCaptureProperty(video, CV_CAP_PROP_POS_FRAMES, k)
# try to query frame
image=cvQueryFrame(video)
if image is None:
# returned image is NULL (FAIL)
return 1
compresult = match.match(image,k,ERRORS[k])
if not compresult:
return 1
if show_frames:
cvShowImage("test",image)
cvWaitKey(200)
# same as above, just backwards...
for k in [27,24,21,18,15,12,9,6,3,0]:
cvSetCaptureProperty(video, CV_CAP_PROP_POS_FRAMES, k)
# try to query frame
image=cvQueryFrame(video)
if image is None:
# returned image is NULL (FAIL)
return 1
compresult = match.match(image,k,ERRORS[k])
if not compresult:
return 1
if show_frames:
cvShowImage("test",image)
cvWaitKey(200)
# ATTENTION: We do not release the video reader, window or any image.
# This is bad manners, but Python and OpenCV don't care,
# the whole memory segment will be freed on finish anyway...
del video
# everything is fine (PASS)
return 0
# testing routine, seeks through file and compares read images with frames in frames.QCIF[]
def seek_time_ok(FILENAME,ERRORS):
# create a video reader using the tiny videofile VIDEOS+FILENAME
video=cvCreateFileCapture(VIDEOS+FILENAME)
if video is None:
# couldn't open video (FAIL)
return 1
if show_frames:
cvNamedWindow("test", CV_WINDOW_AUTOSIZE)
# skip 2 frames and read 3rd frame each until EOF and check if the read image is ok
for k in [0,3,6,9,12,15,18,21,24,27]:
cvSetCaptureProperty(video, CV_CAP_PROP_POS_MSEC, k*40)
# try to query frame
image=cvQueryFrame(video)
if image is None:
# returned image is NULL (FAIL)
return 1
compresult = match.match(image,k,ERRORS[k])
if not compresult:
return 1
if show_frames:
cvShowImage("test",image)
cvWaitKey(200)
# same as above, just backwards...
for k in [27,24,21,18,15,12,9,6,3,0]:
cvSetCaptureProperty(video, CV_CAP_PROP_POS_MSEC, k*40)
# try to query frame
image=cvQueryFrame(video)
if image is None:
# returned image is NULL (FAIL)
return 1
compresult = match.match(image,k,ERRORS[k])
if not compresult:
return 1
if show_frames:
cvShowImage("test",image)
cvWaitKey(200)
# ATTENTION: We do not release the video reader, window or any image.
# This is bad manners, but Python and OpenCV don't care,
# the whole memory segment will be freed on finish anyway...
del video
# everything is fine (PASS)
return 0
#! /usr/bin/env python
"""
This script checks HighGUI's time seeking functionality
on a 3GP-compressed .3gp file.
"""
# name if this test and it's requirements
TESTNAME = "seek_time_3gp"
REQUIRED = []
ERRORS=[0.043,0.031,0.032,0.031,0.029,0.030,0.030,0.031,0.030,0.029,0.034,0.027,0.029,0.029,0.029,0.029,0.029,0.028,0.031,0.030,0.035,0.031,0.031,0.032,0.031,0.032,0.033,0.031,0.033]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='3gp.3gp'
# run check routine
result=seek_test.seek_time_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's time seeking functionality
on an .avi file containing uncompressed 24bit Bitmap frames.
"""
# name if this test and it's requirements
TESTNAME = "seek_time_bmp24"
REQUIRED = []
ERRORS=[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='bmp24.avi'
# run check routine
result=seek_test.seek_time_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's time seeking functionality
on an .avi file containing uncompressed 32bit Bitmap frames.
"""
# name if this test and it's requirements
TESTNAME = "seek_time_bmp32"
REQUIRED = []
ERRORS=[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='bmp32.avi'
# run check routine
result=seek_test.seek_time_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's time seeking functionality
on a CinePak-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "seek_time_cinepak"
REQUIRED = []
ERRORS=[0.086,0.082,0.087,0.085,0.086,0.085,0.086,0.086,0.086,0.086,0.089,0.087,0.090,0.088,0.088,0.088,0.089,0.088,0.089,0.088,0.091,0.089,0.092,0.091,0.091,0.090,0.091,0.090,0.091]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='cinepak.avi'
# run check routine
result=seek_test.seek_time_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's time seeking functionality
on a DivX-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "seek_time_divx"
REQUIRED = []
ERRORS=[0.084,0.081,0.085,0.083,0.085,0.083,0.085,0.085,0.084,0.084,0.087,0.086,0.088,0.086,0.087,0.086,0.086,0.086,0.087,0.086,0.089,0.087,0.090,0.089,0.089,0.088,0.089,0.089,0.089]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='divx.avi'
# run check routine
result=seek_test.seek_time_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's time seeking functionality
on a DV-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "seek_time_dv_pal_progressive_avi"
REQUIRED = []
ERRORS=[0.051,0.047,0.051,0.050,0.052,0.049,0.051,0.050,0.050,0.051,0.054,0.052,0.053,0.052,0.055,0.052,0.053,0.052,0.053,0.052,0.056,0.055,0.056,0.055,0.058,0.055,0.056,0.055,0.056]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='dv_pal_progressive.avi'
# run check routine
result=seek_test.seek_time_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's time seeking functionality
on a DV-compressed .dv file.
"""
# name if this test and it's requirements
TESTNAME = "seek_time_dv_pal_progressive_dv"
REQUIRED = []
ERRORS=[0.288,0.288,0.290,0.289,0.290,0.288,0.288,0.289,0.288,0.289,0.293,0.290,0.293,0.291,0.292,0.290,0.291,0.292,0.292,0.292,0.293,0.290,0.294,0.292,0.292,0.291,0.292,0.293,0.293]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='dv_pal_progressive.dv'
# run check routine
result=seek_test.seek_time_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's time seeking functionality
on a HuffYUV-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "seek_time_huffyuv"
REQUIRED = []
ERRORS=[0.085,0.082,0.086,0.084,0.086,0.084,0.085,0.085,0.085,0.086,0.088,0.087,0.089,0.088,0.088,0.087,0.088,0.087,0.088,0.087,0.091,0.089,0.091,0.090,0.090,0.090,0.090,0.090,0.090]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='huffyuv.avi'
# run check routine
result=seek_test.seek_time_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's time seeking functionality
on an Intel Indeo-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "seek_time_indeo"
REQUIRED = []
ERRORS=[0.085,0.082,0.086,0.084,0.086,0.084,0.085,0.085,0.085,0.086,0.088,0.087,0.089,0.088,0.088,0.087,0.088,0.087,0.088,0.087,0.091,0.089,0.091,0.090,0.090,0.090,0.090,0.090,0.090]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='indeo.avi'
# run check routine
result=seek_test.seek_time_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's time seeking functionality
on an MPEG4-compressed .mp4 file.
"""
# name if this test and it's requirements
TESTNAME = "seek_time_mpeg4"
REQUIRED = []
ERRORS=[0.042,0.025,0.026,0.025,0.024,0.024,0.026,0.024,0.025,0.024,0.028,0.023,0.024,0.024,0.024,0.024,0.025,0.023,0.027,0.024,0.030,0.025,0.026,0.026,0.026,0.026,0.026,0.024,0.027]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='mpeg4.mp4'
# run check routine
result=seek_test.seek_time_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's time seeking functionality
on a uncompressed avi file.
"""
# name if this test and it's requirements
TESTNAME = "seek_time_uncompressed"
REQUIRED = []
ERRORS=[0.085,0.082,0.086,0.084,0.086,0.084,0.085,0.085,0.085,0.086,0.088,0.087,0.089,0.088,0.088,0.087,0.088,0.087,0.088,0.087,0.091,0.089,0.091,0.090,0.090,0.090,0.090,0.090,0.090]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='uncompressed.avi'
# run check routine
result=seek_test.seek_time_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's time seeking functionality
on a WMV9-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "seek_time_wmv9"
REQUIRED = []
ERRORS=[0.043,0.031,0.032,0.031,0.029,0.030,0.030,0.031,0.030,0.029,0.034,0.027,0.029,0.029,0.029,0.029,0.029,0.028,0.031,0.030,0.035,0.031,0.031,0.032,0.031,0.032,0.033,0.031,0.033]
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import seek_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='wmv9.avi'
# run check routine
result=seek_test.seek_time_ok(FILENAME,ERRORS)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvGetCaptureProperty functionality for correct return
of the frame width and height of a 3GP-compressed .3gp file.
"""
# name if this test and it's requirements
TESTNAME = "size_3gp"
REQUIRED = []
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import size_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='3gp.3gp'
# run check routine
result=size_test.size_ok(FILENAME)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvGetCaptureProperty functionality for correct return
of the frame width and height of an .avi file containing uncompressed 24bit Bitmap frames.
"""
# name if this test and it's requirements
TESTNAME = "size_bmp24"
REQUIRED = []
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import size_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='bmp24.avi'
# run check routine
result=size_test.size_ok(FILENAME)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvGetCaptureProperty functionality for correct return
of the frame width and height of an .avi file containing uncompressed 32bit Bitmap frames.
"""
# name if this test and it's requirements
TESTNAME = "size_bmp32"
REQUIRED = []
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import size_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='bmp32.avi'
# run check routine
result=size_test.size_ok(FILENAME)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvGetCaptureProperty functionality for correct return
of the frame width and height of a CinePak-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "size_cinepak"
REQUIRED = []
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import size_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='cinepak.avi'
# run check routine
result=size_test.size_ok(FILENAME)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvGetCaptureProperty functionality for correct return
of the frame width and height of a DivX-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "size_divx"
REQUIRED = []
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import size_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='divx.avi'
# run check routine
result=size_test.size_ok(FILENAME)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvGetCaptureProperty functionality for correct return
of the frame width and height of a DV-compressed .avi file file.
"""
# name if this test and it's requirements
TESTNAME = "size_dv_pal_progressive_avi"
REQUIRED = []
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import size_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='dv_pal_progressive.avi'
# run check routine
result=size_test.size_ok(FILENAME)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvGetCaptureProperty functionality for correct return
of the frame width and height of a DV-compressed .dv file.
"""
# name if this test and it's requirements
TESTNAME = "size_dv_pal_progressive_dv"
REQUIRED = []
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import size_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='dv_pal_progressive.dv'
# run check routine
result=size_test.size_ok(FILENAME)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvGetCaptureProperty functionality for correct return
of the frame width and height of a HuffYUV-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "size_huffyuv"
REQUIRED = []
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import size_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='huffyuv.avi'
# run check routine
result=size_test.size_ok(FILENAME)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvGetCaptureProperty functionality for correct return
of the frame width and height of an Intel Indeo-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "size_indeo"
REQUIRED = []
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import size_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='indeo.avi'
# run check routine
result=size_test.size_ok(FILENAME)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvGetCaptureProperty functionality for correct return
of the frame width and height of an MPEG4-compressed .mp4 file.
"""
# name if this test and it's requirements
TESTNAME = "size_mpeg4"
REQUIRED = []
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import size_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='mpeg4.mp4'
# run check routine
result=size_test.size_ok(FILENAME)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
"""
This script will test HighGUI's cvGetCaptureProperty functionality
for correct returnvalues of width and height information for different video formats
"""
# import the necessary things for OpenCV and comparson routine
import os
from cv import *
from highgui import *
#import python
#from python.highgui import *
# path to images and videos we need
PREFIX =os.path.join(os.environ["srcdir"],"../../opencv_extra/testdata/python/")
# this is the folder with the videos and images
# and name of output window
IMAGES = PREFIX+"images/"
VIDEOS = PREFIX+"videos/"
# testing routine, seeks through file and compares read images with frames in COMPARISON
def size_ok(FILENAME):
# create a video reader using the tiny videofile VIDEOS+FILENAME
video=cvCreateFileCapture(VIDEOS+FILENAME)
if video is None:
# couldn't open video (FAIL)
return 1
# get width and height information via HighGUI's cvGetCaptureProperty function
w=cvGetCaptureProperty(video,CV_CAP_PROP_FRAME_WIDTH)
h=cvGetCaptureProperty(video,CV_CAP_PROP_FRAME_HEIGHT)
# get an image to compare
image=cvQueryFrame(video)
if image is None:
return 1
image = cvCloneImage (image)
if (w!=image.width) or (h!=image.height):
# dimensions don't match parameters (FAIL)
return 1
del video
del image
# everything is fine (PASS)
return 0
#! /usr/bin/env python
"""
This script checks HighGUI's cvGetCaptureProperty functionality for correct return
of the frame width and height of an uncompressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "size_uncompressed"
REQUIRED = []
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import size_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='uncompressed.avi'
# run check routine
result=size_test.size_ok(FILENAME)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
#! /usr/bin/env python
"""
This script checks HighGUI's cvGetCaptureProperty functionality for correct return
of the frame width and height of a WMV9-compressed .avi file.
"""
# name if this test and it's requirements
TESTNAME = "size_wmv9"
REQUIRED = []
# needed for sys.exit(int), .works file handling and check routine
import sys
import works
import size_test
# check requirements and delete old flag file, if it exists
if not works.check_files(REQUIRED,TESTNAME):
sys.exit(77)
# name of file we check here
FILENAME='wmv9.avi'
# run check routine
result=size_test.size_ok(FILENAME)
# create flag file for following tests
works.set_file(TESTNAME)
# return result of test routine
sys.exit(result)
# needed for access() and remove()
import os
# check for required featurest listet in 'filelist' and removes the old .works file of 'testname'
def check_files( filelist, testname ):
# delete old .works file of the calling test, if it exists
filename = "./"+testname+".works"
if os.access(filename,os.F_OK):
os.remove(filename)
# now check for existint .works files
if len(filelist) > 0:
for i in range(0,len(filelist)):
tmpname = "./"+filelist[i]+".works"
if not os.access(tmpname,os.F_OK):
print "(INFO) Skipping '"+testname+"' due to SKIP/FAIL of '"+filelist[i]+"'"
return False
# either the filelist is empty (no requirements) or all requirements match
return True
# create the .works file for test 'testname'
def set_file( testname ):
# create .works file of calling test
works_file = file("./"+testname+".works", 'w',1)
works_file.close
return
#!/usr/bin/env python
import unittest
import sys
import os
import cvtestutils
from cv import cvCreateHist, cvGetSize, cvCreateImage, cvCvtColor, cvSplit, cvCalcHist, cvCalcArrHist, CV_HIST_ARRAY
from highgui import cvLoadImage
image_fname = os.path.join( cvtestutils.datadir(), 'images', 'baboon_256x256.bmp' )
class HistogramTestCase( unittest.TestCase ):
def setUp(self):
frame = cvLoadImage( image_fname )
frame_size = cvGetSize( frame )
r = cvCreateImage (frame_size, 8, 1)
g = cvCreateImage (frame_size, 8, 1)
b = cvCreateImage (frame_size, 8, 1)
cvSplit( frame, r, g, b, None)
self.rgb = (r,g,b)
assert(frame is not None)
hist_size = [64, 64, 64]
ranges = [ [0, 255], [0, 255], [0, 255] ]
self.hist = cvCreateHist( hist_size, CV_HIST_ARRAY, ranges, 1 )
def test_cvCreateHist( self ):
assert( self.hist is not None )
def test_cvCalcArrHist(self):
cvCalcArrHist( self.rgb, self.hist, 0, None)
def test_cvCalcHist(self):
cvCalcHist( self.rgb, self.hist, 0, None)
def suite():
tests = ['test_cvCreateHist', 'test_cvCalcArrHist', 'test_cvCalcHist']
return unittest.TestSuite( map(HistogramTestCase, tests))
if __name__ == '__main__':
unittest.TextTestRunner(verbosity=2).run(suite())
#!/usr/bin/env python
# 2009-01-16, Xavier Delacour <xavier.delacour@gmail.com>
import unittest
from numpy import *;
from numpy.linalg import *;
import sys;
import cvtestutils
from cv import *;
from adaptors import *;
def transform(H,x):
x1 = H * asmatrix(r_[x[0],x[1],1]).transpose()
x1 = asarray(x1).flatten()
return r_[x1[0]/x1[2],x1[1]/x1[2]]
class homography_test(unittest.TestCase):
def test_ransac_identity(self):
pts1 = random.rand(100,2);
result,H = cvFindHomography(pts1, pts1, CV_RANSAC, 1e-5);
assert(result and all(abs(Ipl2NumPy(H) - eye(3)) < 1e-5));
def test_ransac_0_outliers(self):
pts1 = random.rand(100,2);
H1 = asmatrix(random.rand(3,3));
H1 = H1 / H1[2,2]
pts2 = [transform(H1,x) for x in pts1]
result,H = cvFindHomography(pts1, pts2, CV_RANSAC, 1e-5);
assert(result and all(abs(H1-H)<1e-5))
def test_ransac_30_outliers(self):
pts1 = random.rand(100,2);
H1 = asmatrix(random.rand(3,3));
H1 = H1 / H1[2,2]
pts2 = [transform(H1,x) for x in pts1]
pts2[0:30] = random.rand(30,2)
result,H = cvFindHomography(pts1, pts2, CV_RANSAC, 1e-5);
assert(result and all(abs(H1-H)<1e-5))
def test_ransac_70_outliers(self):
pts1 = random.rand(100,2);
H1 = asmatrix(random.rand(3,3));
H1 = H1 / H1[2,2]
pts2 = [transform(H1,x) for x in pts1]
pts2[0:70] = random.rand(70,2)
result,H = cvFindHomography(pts1, pts2, CV_RANSAC, 1e-5);
assert(result and all(abs(H1-H)<1e-5))
def test_ransac_90_outliers(self):
pts1 = random.rand(100,2);
H1 = asmatrix(random.rand(3,3));
H1 = H1 / H1[2,2]
pts2 = [transform(H1,x) for x in pts1]
pts2[0:90] = random.rand(90,2)
result,H = cvFindHomography(pts1, pts2, CV_RANSAC, 1e-5);
assert(not result or not all(abs(H1-H)<1e-5))
def test_lmeds_identity(self):
pts1 = random.rand(100,2);
result,H = cvFindHomography(pts1, pts1, CV_LMEDS);
assert(result and all(abs(Ipl2NumPy(H) - eye(3)) < 1e-5));
def test_lmeds_0_outliers(self):
pts1 = random.rand(100,2);
H1 = asmatrix(random.rand(3,3));
H1 = H1 / H1[2,2]
pts2 = [transform(H1,x) for x in pts1]
result,H = cvFindHomography(pts1, pts2, CV_LMEDS);
assert(result and all(abs(H1-H)<1e-5))
def test_lmeds_30_outliers(self):
pts1 = random.rand(100,2);
H1 = asmatrix(random.rand(3,3));
H1 = H1 / H1[2,2]
pts2 = [transform(H1,x) for x in pts1]
pts2[0:30] = random.rand(30,2)
result,H = cvFindHomography(pts1, pts2, CV_LMEDS);
assert(result and all(abs(H1-H)<1e-5))
def test_lmeds_70_outliers(self):
pts1 = random.rand(100,2);
H1 = asmatrix(random.rand(3,3));
H1 = H1 / H1[2,2]
pts2 = vstack([transform(H1,x) for x in pts1])
pts2[0:70] = random.rand(70,2)
result,H = cvFindHomography(pts1, pts2, CV_LMEDS);
assert(not result or not all(abs(H1-H)<1e-5))
def suite():
return unittest.TestLoader().loadTestsFromTestCase(homography_test)
if __name__ == '__main__':
unittest.TextTestRunner(verbosity=2).run(suite())
#!/usr/bin/env python
# 2009-01-12, Xavier Delacour <xavier.delacour@gmail.com>
# gdb --cd ~/opencv-lsh/tests/python --args /usr/bin/python lsh_tests.py
# set env PYTHONPATH /home/x/opencv-lsh/debug/interfaces/swig/python:/home/x/opencv-lsh/debug/lib
# export PYTHONPATH=/home/x/opencv-lsh/debug/interfaces/swig/python:/home/x/opencv-lsh/debug/lib
import unittest
from numpy import *;
from numpy.linalg import *;
import sys;
import cvtestutils
from cv import *;
from adaptors import *;
def planted_neighbors(query_points, R = .4):
n,d = query_points.shape
data = zeros(query_points.shape)
for i in range(0,n):
a = random.rand(d)
a = random.rand()*R*a/sqrt(sum(a**2))
data[i] = query_points[i] + a
return data
class lsh_test(unittest.TestCase):
def test_basic(self):
n = 10000;
d = 64;
query_points = random.rand(n,d)*2-1;
data = planted_neighbors(query_points)
lsh = cvCreateMemoryLSH(d, n);
cvLSHAdd(lsh, data);
indices,dist = cvLSHQuery(lsh, query_points, 1, 100);
correct = sum([i == j for j,i in enumerate(indices)])
assert(correct >= n * .75);
def test_sensitivity(self):
n = 10000;
d = 64;
query_points = random.rand(n,d);
data = random.rand(n,d);
lsh = cvCreateMemoryLSH(d, 1000, 10, 10);
cvLSHAdd(lsh, data);
good = 0
trials = 20
print
for x in query_points[0:trials]:
x1 = asmatrix(x) # PyArray_to_CvArr doesn't like 1-dim arrays
indices,dist = cvLSHQuery(lsh, x1, n, n);
indices = Ipl2NumPy(indices)
indices = unique(indices[where(indices>=0)])
brute = vstack([(sqrt(sum((a-x)**2)),i,0) for i,a in enumerate(data)])
lshp = vstack([(sqrt(sum((x-data[i])**2)),i,1) for i in indices])
combined = vstack((brute,lshp))
combined = combined[argsort(combined[:,0])]
spread = [i for i,a in enumerate(combined[:,2]) if a==1]
spread = histogram(spread,bins=4,new=True)[0]
print spread, sum(diff(spread)<0)
if sum(diff(spread)<0) == 3: good = good + 1
print good,"pass"
assert(good > trials * .75);
def test_remove(self):
n = 10000;
d = 64;
query_points = random.rand(n,d)*2-1;
data = planted_neighbors(query_points)
lsh = cvCreateMemoryLSH(d, n);
indices = cvLSHAdd(lsh, data);
assert(LSHSize(lsh)==n);
cvLSHRemove(lsh,indices[0:n/2])
assert(LSHSize(lsh)==n/2);
def test_destroy(self):
n = 10000;
d = 64;
lsh = cvCreateMemoryLSH(d, n);
def test_destroy2(self):
n = 10000;
d = 64;
query_points = random.rand(n,d)*2-1;
data = planted_neighbors(query_points)
lsh = cvCreateMemoryLSH(d, n);
indices = cvLSHAdd(lsh, data);
# move this to another file
# img1 = cvLoadImage(img1_fn);
# img2 = cvLoadImage(img2_fn);
# pts1,desc1 = cvExtractSURF(img1); # * make util routine to extract points and descriptors
# pts2,desc2 = cvExtractSURF(img2);
# lsh = cvCreateMemoryLSH(d, n);
# cvLSHAdd(lsh, desc1);
# indices,dist = cvLSHQuery(lsh, desc2, 2, 100);
# matches = [((pts1[x[0]].pt.x,pts1[x[0]].pt.y),(pts2[j].pt.x,pts2[j].pt.y)) \
# for j,x in enumerate(hstack((indices,dist))) \
# if x[2] and (not x[3] or x[2]/x[3]>.6)]
# out = cvCloneImage(img1);
# for p1,p2 in matches:
# cvCircle(out,p1,3,CV_RGB(255,0,0));
# cvLine(out,p1,p2,CV_RGB(100,100,100));
# cvNamedWindow("matches");
# cvShowImage("matches",out);
# cvWaitKey(0);
def suite():
return unittest.TestLoader().loadTestsFromTestCase(lsh_test)
if __name__ == '__main__':
unittest.TextTestRunner(verbosity=2).run(suite())
#!/usr/bin/env python
import cvtestutils
import unittest
from cv import *
class moments_test(unittest.TestCase):
def setUp(self):
# create an image
img = cvCreateMat(100,100,CV_8U);
cvZero( img )
# draw a rectangle in the middle
cvRectangle( img, cvPoint( 25, 25 ), cvPoint( 75, 75 ), CV_RGB(255,255,255), -1 );
self.img = img
# create the storage area
self.storage = cvCreateMemStorage (0)
# find the contours
nb_contours, self.contours = cvFindContours (img,
self.storage,
sizeof_CvContour,
CV_RETR_LIST,
CV_CHAIN_APPROX_SIMPLE,
cvPoint (0,0))
def test_cvMoments_CvMat( self ):
m = CvMoments()
cvMoments( self.img, m, 1 )
def test_cvMoments_CvSeq( self ):
m = CvMoments()
# Now test with CvSeq
for contour in self.contours.hrange():
cvMoments( contour, m, 1 )
def suite():
return unittest.TestLoader().loadTestsFromTestCase(moments_test)
if __name__ == '__main__':
unittest.TextTestRunner(verbosity=2).run(suite())
#!/usr/bin/env python
# 2009-01-16, Xavier Delacour <xavier.delacour@gmail.com>
import unittest
from numpy import *;
from numpy.linalg import *;
import sys;
import cvtestutils
from cv import *;
from adaptors import *;
## these are mostly to test bindings, since there are more/better tests in tests/cxcore
def verify(x,y):
x = Ipl2NumPy(x);
assert(all(abs(x - y)<1e-4));
class roots_test(unittest.TestCase):
def test_cvSolvePoly(self):
verify(cvSolvePoly(asmatrix([-1,1]).astype(float64)),
array([[(1.000000, 0.000000)]]));
verify(cvSolvePoly(asmatrix([-1,1]).astype(float32)),
array([[(1.000000, 0.000000)]]));
verify(cvSolvePoly(asmatrix([-1,0,0,0,0,1]).astype(float64)),
array([[(1, 0)],[(0.309017, 0.951057)],[(0.309017, -0.951057)],
[(-0.809017, 0.587785)],[(-0.809017, -0.587785)]]))
verify(cvSolvePoly(asmatrix([-1,0,0,0,0,1]).astype(float32)),
array([[(1, 0)],[(0.309017, 0.951057)],[(0.309017, -0.951057)],
[(-0.809017, 0.587785)],[(-0.809017, -0.587785)]]))
def test_cvSolveCubic(self):
verify(cvSolveCubic(asmatrix([-1,0,0,1]).astype(float32))[1],
array([[1],[0],[0]]));
verify(cvSolveCubic(asmatrix([-1,0,0,1]).astype(float64))[1],
array([[1],[0],[0]]));
def suite():
return unittest.TestLoader().loadTestsFromTestCase(roots_test)
if __name__ == '__main__':
unittest.TextTestRunner(verbosity=2).run(suite())
#!/usr/bin/env python
"""A simple TestCase class for testing the adaptors.py module.
2007-11-xx, Vicent Mas <vmas@carabos.com> Carabos Coop. V.
2007-11-08, minor modifications for distribution, Mark Asbach <asbach@ient.rwth-aachen.de>
"""
import unittest
import os
import PIL.Image
import numpy
import cvtestutils
import cv
import highgui
import adaptors
import sys
class AdaptorsTestCase(unittest.TestCase):
def test00_array_interface(self):
"""Check if PIL supports the array interface."""
self.assert_(PIL.Image.VERSION>='1.1.6',
"""The installed PIL library doesn't support the array """
"""interface. Please, update to version 1.1.6b2 or higher.""")
def test01_PIL2NumPy(self):
"""Test the adaptors.PIL2NumPy function."""
a = adaptors.PIL2NumPy(self.pil_image)
self.assert_(a.flags['WRITEABLE'] == True,
'PIL2NumPy should return a writeable array.')
b = numpy.asarray(self.pil_image)
self.assert_((a == b).all() == True,
'The returned numpy array has not been properly constructed.')
def test02_NumPy2PIL(self):
"""Test the adaptors.NumPy2PIL function."""
a = numpy.asarray(self.pil_image)
b = adaptors.NumPy2PIL(a)
self.assert_(self.pil_image.tostring() == b.tostring(),
'The returned image has not been properly constructed.')
def test03_Ipl2PIL(self):
"""Test the adaptors.Ipl2PIL function."""
i = adaptors.Ipl2PIL(self.ipl_image)
self.assert_(self.pil_image.tostring() == i.tostring(),
'The returned image has not been properly constructed.')
def test04_PIL2Ipl(self):
"""Test the adaptors.PIL2Ipl function."""
i = adaptors.PIL2Ipl(self.pil_image)
self.assert_(self.ipl_image.imageData == i.imageData,
'The returned image has not been properly constructed.')
def test05_Ipl2NumPy(self):
"""Test the adaptors.Ipl2NumPy function."""
a = adaptors.Ipl2NumPy(self.ipl_image)
a_1d = numpy.reshape(a, (a.size, ))
# For 3-channel IPL images the order of channels will be BGR
# but NumPy array order of channels will be RGB so a conversion
# is needed before we can compare both images
if self.ipl_image.nChannels == 3:
rgb = cv.cvCreateImage(cv.cvSize(self.ipl_image.width, self.ipl_image.height), self.ipl_image.depth, 3)
cv.cvCvtColor(self.ipl_image, rgb, cv.CV_BGR2RGB)
self.assert_(a_1d.tostring() == rgb.imageData,
'The returned image has not been properly constructed.')
else:
self.assert_(a_1d.tostring() == self.ipl_image.imageData,
'The returned image has not been properly constructed.')
def test06_NumPy2Ipl(self):
"""Test the adaptors.NumPy2Ipl function."""
a = adaptors.Ipl2NumPy(self.ipl_image)
b = adaptors.NumPy2Ipl(a)
self.assert_(self.ipl_image.imageData == b.imageData,
'The returned image has not been properly constructed.')
def load_image( self, fname ):
self.ipl_image = highgui.cvLoadImage(fname, 4|2)
self.pil_image = PIL.Image.open(fname, 'r')
class AdaptorsTestCase1(AdaptorsTestCase):
def setUp( self ):
self.load_image( os.path.join(cvtestutils.datadir(),'images','cvSetMouseCallback.jpg'))
class AdaptorsTestCase2(AdaptorsTestCase):
def setUp( self ):
self.load_image( os.path.join(cvtestutils.datadir(),'images','baboon.jpg'))
def suite():
cases=[]
cases.append( unittest.TestLoader().loadTestsFromTestCase( AdaptorsTestCase1 ) )
cases.append( unittest.TestLoader().loadTestsFromTestCase( AdaptorsTestCase2 ) )
return unittest.TestSuite(cases)
if __name__ == '__main__':
unittest.TextTestRunner(verbosity=2).run(suite())
#!/usr/bin/env python
# This script uses the unittest module to find all the tests in the
# same directory and run them.
#
# 2009-01-23, Roman Stanchak (rstanchak@gmail.com)
#
#
# For a test to be detected and run by this script, it must
# 1. Use unittest
# 2. define a suite() method that returns a unittest.TestSuite containing
# the tests to be run
import cvtestutils
import unittest
import types
import os
import imp
def suites( dirname ):
suite_list=[]
for fn in os.listdir( dirname ):
# tests must be named test_*.py or *_tests.py
if not ( fn.lower().endswith('.py') and
(fn.lower().startswith('test_') or fn.lower().endswith('_tests.py')) ):
continue
module_name = fn[0:-3]
fullpath = os.path.realpath( dirname + os.path.sep + fn )
test_module = None
try:
test_module = imp.load_source( module_name, fullpath )
except:
print "Error importing python code in '%s'" % fn
if test_module:
try:
suite_list.append( test_module.suite() )
print "Added tests from %s" % fn
except:
print "%s does not contain a suite() method, skipping" % fn
return unittest.TestSuite(suite_list)
def col2( c1, c2, w=72 ):
return "%s%s" % (c1, c2.rjust(w-len(c1)))
if __name__ == "__main__":
print '----------------------------------------------------------------------'
print 'Searching for tests...'
print '----------------------------------------------------------------------'
suite = suites( os.path.dirname( os.path.realpath(__file__) ))
print '----------------------------------------------------------------------'
print 'Running tests...'
print '----------------------------------------------------------------------'
unittest.TextTestRunner(verbosity=2).run(suite)
#! /bin/sh
if [ -n "${TESTDATA_DIR}" ] ; then
./opencv_test -d $TESTDATA_DIR/cv
else
./opencv_test -d $srcdir/../../opencv_extra/testdata/cv
fi
#! /bin/sh
if [ -n "${TESTDATA_DIR}" ] ; then
./opencv_test_core -d $TESTDATA_DIR/cxcore
else
./opencv_test_core -d $srcdir/../../opencv_extra/testdata/cxcore
fi
#! /bin/sh
if [ -n "${TESTDATA_DIR}" ] ; then
./opencv_test_ml -d $TESTDATA_DIR/ml
else
./opencv_test_ml -d $srcdir/../../opencv_extra/testdata/ml
fi
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment