diff python/cvutils.py @ 154:668710d4c773

updated computeTranslation with cv2
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Wed, 07 Sep 2011 16:35:51 -0400
parents 74b1fc68d4df
children 2eef5620c0b3
line wrap: on
line diff
--- a/python/cvutils.py	Tue Sep 06 19:22:24 2011 -0400
+++ b/python/cvutils.py	Wed Sep 07 16:35:51 2011 -0400
@@ -135,28 +135,27 @@
     return invH
 
 if opencvExists:
-    def computeTranslation(img1, img2, img1Points, maxTranslation, minNMatches, windowSize = (5,5), level = 5, criteria = (cv2.TERM_CRITERIA_EPS, 0, 0.01)):
-        '''Computes the translation between of img2 with respect to img1
-        (loaded using OpenCV)
+    def computeTranslation(img1, img2, img1Points, maxTranslation2, minNMatches, windowSize = (5,5), level = 5, criteria = (cv2.TERM_CRITERIA_EPS, 0, 0.01)):
+        '''Computes the translation of img2 with respect to img1
+        (loaded using OpenCV as numpy arrays)
         img1Points are used to compute the translation
 
-        TODO add diagnostic if data is all over the place, and it most likely is not a translation (eg zoom)'''
-        from numpy.core.multiarray import zeros
+        TODO add diagnostic if data is all over the place, and it most likely is not a translation (eg zoom, other non linear distortion)'''
+        from numpy.core.multiarray import array
         from numpy.lib.function_base import median
+        from numpy.core.fromnumeric import sum
 
-        (img2Points, status, track_error) = cv.CalcOpticalFlowPyrLK(img1, img2, zeros((img1.rows,img1.cols+8)), zeros((img1.rows,img1.cols+8)), img1Points, windowSize, level, criteria, 0)
-        
-        deltaX = []
-        deltaY = []
+        nextPoints = array([])
+        (img2Points, status, track_error) = cv2.calcOpticalFlowPyrLK(img1, img2, img1Points, nextPoints, winSize=windowSize, maxLevel=level, criteria=criteria)
+        # calcOpticalFlowPyrLK(prevImg, nextImg, prevPts[, nextPts[, status[, err[, winSize[, maxLevel[, criteria[, derivLambda[, flags]]]]]]]]) -> nextPts, status, err
+        delta = []
         for (k, (p1,p2)) in enumerate(zip(img1Points, img2Points)):
             if status[k] == 1:
-                dx = p2[0]-p1[0]
-                dy = p2[1]-p1[1]
-                d = dx**2 + dy**2
-                if d < maxTranslation:
-                    deltaX.append(dx)
-                    deltaY.append(dy)
-        if len(deltaX) >= 10:
-            return [median(deltaX), median(deltaY)]
+                dp = p2-p1
+                d = sum(dp**2)
+                if d < maxTranslation2:
+                    delta.append(dp)
+        if len(delta) >= minNMatches:
+            return median(delta, axis=0)
         else:
             return None