changeset 769:dfdb2a3722cc dev

moved import statements together
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Wed, 20 Jan 2016 23:47:23 -0500
parents f8e0a8ea8402
children 0f6b0f63eb07
files python/cvutils.py
diffstat 1 files changed, 24 insertions(+), 34 deletions(-) [+]
line wrap: on
line diff
--- a/python/cvutils.py	Thu Jan 14 11:44:39 2016 -0500
+++ b/python/cvutils.py	Wed Jan 20 23:47:23 2016 -0500
@@ -1,7 +1,7 @@
 #! /usr/bin/env python
 '''Image/Video utilities'''
 
-import utils
+import utils, moving
 
 try:
     import cv2
@@ -16,8 +16,16 @@
     print('Scikit-image library could not be loaded (HoG-based classification methods will not be available)')
     skimageAvailable = False
     
-from sys import stdout
-from numpy import dot, array, append, float32
+from sys import stdout, maxint
+from os import listdir
+from copy import deepcopy
+from math import floor, log10, ceil
+
+from numpy import dot, array, append, float32, loadtxt, savetxt, append, zeros, ones, identity, abs as npabs, logical_and, unravel_index, sum as npsum, isnan, mgrid, median, floor as npfloor, ceil as npceil
+from matplotlib.mlab import find
+from matplotlib.pyplot import imread, imsave
+
+
 
 #import aggdraw # agg on top of PIL (antialiased drawing)
 
@@ -77,27 +85,27 @@
 def matlab2PointCorrespondences(filename):
     '''Loads and converts the point correspondences saved 
     by the matlab camera calibration tool'''
-    from numpy.lib.io import loadtxt, savetxt
-    from numpy.lib.function_base import append
     points = loadtxt(filename, delimiter=',')
     savetxt(utils.removeExtension(filename)+'-point-correspondences.txt',append(points[:,:2].T, points[:,3:].T, axis=0))
 
 def loadPointCorrespondences(filename):
     '''Loads and returns the corresponding points in world (first 2 lines) and image spaces (last 2 lines)'''
-    from numpy import loadtxt, float32
     points = loadtxt(filename, dtype=float32)
     return  (points[:2,:].T, points[2:,:].T) # (world points, image points)
 
 def cvMatToArray(cvmat):
     '''Converts an OpenCV CvMat to numpy array.'''
     print('Deprecated, use new interface')
-    from numpy 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 createWhiteImage(height, width, filename):
+    img = ones((height, width, 3), uint8)*255
+    imsave(filename, img)
+
 if opencvAvailable:
     def computeHomography(srcPoints, dstPoints, method=0, ransacReprojThreshold=3.0):
         '''Returns the homography matrix mapping from srcPoints to dstPoints (dimension Nx2)'''
@@ -132,8 +140,6 @@
             cv2.imshow(windowName, img)
 
     def computeUndistortMaps(width, height, undistortedImageMultiplication, intrinsicCameraMatrix, distortionCoefficients):
-        from copy import deepcopy
-        from numpy import identity
         newImgSize = (int(round(width*undistortedImageMultiplication)), int(round(height*undistortedImageMultiplication)))
         newCameraMatrix = deepcopy(intrinsicCameraMatrix)
         newCameraMatrix[0,2] = newImgSize[0]/2.
@@ -214,7 +220,6 @@
 
     def getImagesFromVideo(videoFilename, firstFrameNum = 0, nFrames = 1, saveImage = False, outputPrefix = 'image'):
         '''Returns nFrames images from the video sequence'''
-        from math import floor, log10
         images = []
         capture = cv2.VideoCapture(videoFilename)
         if capture.isOpened():
@@ -283,9 +288,6 @@
 
     def displayTrajectories(videoFilename, objects, boundingBoxes = {}, homography = None, firstFrameNum = 0, lastFrameNumArg = None, printFrames = True, rescale = 1., nFramesStep = 1, saveAllImages = False, undistort = False, intrinsicCameraMatrix = None, distortionCoefficients = None, undistortedImageMultiplication = 1., annotations = [], gtMatches = {}, toMatches = {}):
         '''Displays the objects overlaid frame by frame over the video '''
-        from moving import userTypeNames
-        from math import ceil, log10
-
         capture = cv2.VideoCapture(videoFilename)
         width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
         height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
@@ -302,7 +304,6 @@
             frameNum = firstFrameNum
             capture.set(cv2.CAP_PROP_POS_FRAMES, firstFrameNum)
             if lastFrameNumArg is None:
-                from sys import maxint
                 lastFrameNum = maxint
             else:
                 lastFrameNum = lastFrameNumArg
@@ -333,8 +334,8 @@
                                 imgcrop, yCropMin, yCropMax, xCropMin, xCropMax = imageBox(img, obj, frameNum, homography, width, height)
                                 cv2.rectangle(img, (xCropMin, yCropMin), (xCropMax, yCropMax), cvBlue, 1)
                             objDescription = '{} '.format(obj.num)
-                            if userTypeNames[obj.userType] != 'unknown':
-                                objDescription += userTypeNames[obj.userType][0].upper()
+                            if moving.userTypeNames[obj.userType] != 'unknown':
+                                objDescription += moving.userTypeNames[obj.userType][0].upper()
                             if len(annotations) > 0: # if we loaded annotations, but there is no match
                                 if frameNum not in toMatches[obj.getNum()]:
                                     objDescription += " FA"
@@ -383,21 +384,17 @@
         map1 and map2 are the mapping functions from undistorted image
         to distorted (original image)
         map1(x,y) = originalx, originaly'''
-        from numpy import abs, logical_and, unravel_index, sum
-        from matplotlib.mlab import find
-        distx = abs(map1-x)
-        disty = abs(map2-y)
+        distx = npabs(map1-x)
+        disty = npabs(map2-y)
         indices = logical_and(distx<maxDistance, disty<maxDistance)
         closeCoordinates = unravel_index(find(indices), distx.shape) # returns i,j, ie y,x
         xWeights = 1-distx[indices]
         yWeights = 1-disty[indices]
-        return dot(xWeights, closeCoordinates[1])/sum(xWeights), dot(yWeights, closeCoordinates[0])/sum(yWeights)
+        return dot(xWeights, closeCoordinates[1])/npsum(xWeights), dot(yWeights, closeCoordinates[0])/npsum(yWeights)
 
     def undistortTrajectoryFromCVMapping(map1, map2, t):
         '''test 'perfect' inversion'''
-        from moving import Trajectory
-        from numpy import isnan
-        undistortedTrajectory = Trajectory()
+        undistortedTrajectory = moving.Trajectory()
         for i,p in enumerate(t):
             res = undistortedCoordinates(map1, map2, p.x,p.y)
             if not isnan(res).any():
@@ -408,7 +405,6 @@
 
     def computeInverseMapping(originalImageSize, map1, map2):
         'Computes inverse mapping from maps provided by cv2.initUndistortRectifyMap'
-        from numpy import ones, isnan
         invMap1 = -ones(originalImageSize)
         invMap2 = -ones(originalImageSize)
         for x in range(0,originalImageSize[1]):
@@ -432,7 +428,6 @@
             https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_calib3d/py_calibration/py_calibration.html
             Modified by Paul St-Aubin
             '''
-        from numpy import zeros, mgrid, float32, savetxt
         import glob, os
 
         # termination criteria
@@ -533,9 +528,8 @@
     return invH
 
 def undistortTrajectory(invMap1, invMap2, positions):
-    from numpy import floor, ceil
-    floorPositions = floor(positions)
-    #ceilPositions = ceil(positions)
+    floorPositions = npfloor(positions)
+    #ceilPositions = npceil(positions)
     undistortedTrajectory = [[],[]]
     for i in xrange(len(positions[0])):
         x,y = None, None
@@ -563,7 +557,6 @@
         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, other non linear distortion)'''
-        from numpy import median, sum
 
         nextPoints = array([])
         (img2Points, status, track_error) = cv2.calcOpticalFlowPyrLK(img1, img2, img1Points, nextPoints, winSize=windowSize, maxLevel=level, criteria=criteria)
@@ -572,7 +565,7 @@
         for (k, (p1,p2)) in enumerate(zip(img1Points, img2Points)):
             if status[k] == 1:
                 dp = p2-p1
-                d = sum(dp**2)
+                d = npsum(dp**2)
                 if d < maxTranslation2:
                     delta.append(dp)
         if len(delta) >= minNMatches:
@@ -601,9 +594,6 @@
         return float32(features)
 
     def createHOGTrainingSet(imageDirectory, classLabel, rescaleSize = (64, 64), orientations=9, pixelsPerCell=(8, 8), cellsPerBlock=(2, 2), visualize=False, normalize=False):
-        from os import listdir
-        from matplotlib.pyplot import imread
-
         inputData = []
         for filename in listdir(imageDirectory):
             img = imread(imageDirectory+filename)