diff python/cvutils.py @ 99:e7dc5a780f09

added conversion functions and homography computation
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Tue, 12 Jul 2011 17:01:59 -0400
parents b85912ab4064
children 2a3cafcf5faf
line wrap: on
line diff
--- a/python/cvutils.py	Tue Jul 12 16:43:33 2011 -0400
+++ b/python/cvutils.py	Tue Jul 12 17:01:59 2011 -0400
@@ -2,6 +2,9 @@
 '''Image/Video utilities'''
 
 import Image, ImageDraw # PIL
+import cv
+from sys import stdout
+
 #import aggdraw # agg on top of PIL (antialiased drawing)
 from moving import Point
 #import utils
@@ -24,6 +27,38 @@
     #out = utils.openCheck(resultFilename)
     img.save(resultFilename)
 
+def computeHomography(srcPoints, dstPoints, method=0, ransacReprojThreshold=0.0):
+    '''Returns the homography matrix mapping from srcPoints to dstPoints (dimension Nx2)'''
+    cvSrcPoints = arrayToCvMat(srcPoints);
+    cvDstPoints = arrayToCvMat(dstPoints);
+    H = cv.CreateMat(3, 3, cv.CV_64FC1)
+    cv.FindHomography(cvSrcPoints, cvDstPoints, H, method, ransacReprojThreshold)
+    return H
+
+def cvMatToArray(cvmat):
+    '''Converts an OpenCV CvMat to numpy array.'''
+    from numpy.core.multiarray import zeros
+    a = zeros((cvmat.rows, cvmat.cols))#array([[0.0]*cvmat.width]*cvmat.height)
+    for i in xrange(cvmat.rows):
+        for j in xrange(cvmat.cols):
+            a[i,j] = cvmat[i,j]
+    return a
+
+def arrayToCvMat(a, t = cv.CV_64FC1):
+    '''Converts a numpy array to an OpenCV CvMat, with default type CV_64FC1.'''
+    cvmat = cv.CreateMat(a.shape[0], a.shape[1], t)
+    for i in range(cvmat.rows):
+        for j in range(cvmat.cols):
+            cvmat[i,j] = a[i,j]
+    return cvmat
+
+def printCvMat(cvmat, out = stdout):
+    '''Prints the cvmat to out'''
+    for i in xrange(cvmat.rows):
+        for j in xrange(cvmat.cols):
+            out.write('{0} '.format(cvmat[i,j]))
+        out.write('\n')
+
 def projectArray(homography, points):
     '''Returns the coordinates of the projected points (format 2xN points)
     through homography'''