changeset 672:5473b7460375

moved and rationalized imports in modules
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Tue, 26 May 2015 13:53:40 +0200
parents 849f5f8bf4b9
children 5505f9dbb28e
files python/cvutils.py python/moving.py python/utils.py
diffstat 3 files changed, 18 insertions(+), 49 deletions(-) [+]
line wrap: on
line diff
--- a/python/cvutils.py	Tue May 26 11:40:32 2015 +0200
+++ b/python/cvutils.py	Tue May 26 13:53:40 2015 +0200
@@ -17,6 +17,7 @@
     skimageAvailable = False
     
 from sys import stdout
+from numpy import dot, array, append
 
 #import aggdraw # agg on top of PIL (antialiased drawing)
 
@@ -67,15 +68,14 @@
 
 def loadPointCorrespondences(filename):
     '''Loads and returns the corresponding points in world (first 2 lines) and image spaces (last 2 lines)'''
-    from numpy.lib.npyio import loadtxt
-    from numpy import float32
+    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.core.multiarray import zeros
+    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):
@@ -116,7 +116,7 @@
 
     def computeUndistortMaps(width, height, undistortedImageMultiplication, intrinsicCameraMatrix, distortionCoefficients):
         from copy import deepcopy
-        from numpy import identity, array
+        from numpy import identity
         newImgSize = (int(round(width*undistortedImageMultiplication)), int(round(height*undistortedImageMultiplication)))
         newCameraMatrix = deepcopy(intrinsicCameraMatrix)
         newCameraMatrix[0,2] = newImgSize[0]/2.
@@ -325,7 +325,6 @@
     def computeHomographyFromPDTV(camera):
         '''Returns the homography matrix at ground level from PDTV camera
         https://bitbucket.org/hakanardo/pdtv'''
-        from numpy import array
         # camera = pdtv.load(cameraFilename)
         srcPoints = [[x,y] for x, y in zip([1.,2.,2.,1.],[1.,1.,2.,2.])] # need floats!!
         dstPoints = []
@@ -340,7 +339,7 @@
         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, dot, sum
+        from numpy import abs, logical_and, unravel_index, sum
         from matplotlib.mlab import find
         distx = abs(map1-x)
         disty = abs(map2-y)
@@ -459,10 +458,6 @@
 def projectArray(homography, points):
     '''Returns the coordinates of the projected points through homography
     (format: array 2xN points)'''
-    from numpy.core import dot
-    from numpy.core.multiarray import array
-    from numpy.lib.function_base import append
-
     if points.shape[0] != 2:
         raise Exception('points of dimension {0} {1}'.format(points.shape[0], points.shape[1]))
 
@@ -477,20 +472,18 @@
 def project(homography, p):
     '''Returns the coordinates of the projection of the point p with coordinates p[0], p[1]
     through homography'''
-    from numpy import array
     return projectArray(homography, array([[p[0]],[p[1]]]))
 
 def projectTrajectory(homography, trajectory):
     '''Projects a series of points in the format
     [[x1, x2, ...],
     [y1, y2, ...]]'''
-    from numpy.core.multiarray import array
     return projectArray(homography, array(trajectory))
 
 def invertHomography(homography):
     '''Returns an inverted homography
     Unnecessary for reprojection over camera image'''
-    from numpy.linalg.linalg import inv
+    from numpy import inv
     invH = inv(homography)
     invH /= invH[2,2]
     return invH
@@ -517,7 +510,6 @@
     return undistortedTrajectory
 
 def projectGInputPoints(homography, points):
-    from numpy import array
     return projectTrajectory(homography, array(points+[points[0]]).T)
 
 if opencvAvailable:
@@ -527,9 +519,7 @@
         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.core.multiarray import array
-        from numpy.lib.function_base import median
-        from numpy.core.fromnumeric import sum
+        from numpy import median, sum
 
         nextPoints = array([])
         (img2Points, status, track_error) = cv2.calcOpticalFlowPyrLK(img1, img2, img1Points, nextPoints, winSize=windowSize, maxLevel=level, criteria=criteria)
@@ -568,7 +558,7 @@
 
     def createHOGTrainingSet(imageDirectory, classLabel, rescaleSize = (64, 64), orientations=9, pixelsPerCell=(8, 8), cellsPerBlock=(2, 2), visualize=False, normalize=False):
         from os import listdir
-        from numpy import array, float32
+        from numpy import float32
         from matplotlib.pyplot import imread
 
         inputData = []
--- a/python/moving.py	Tue May 26 11:40:32 2015 +0200
+++ b/python/moving.py	Tue May 26 13:53:40 2015 +0200
@@ -4,8 +4,11 @@
 import utils, cvutils
 from base import VideoFilenameAddable
 
-from math import sqrt
-from numpy import median
+from math import sqrt, atan2, cos, sin
+from numpy import median, array, zeros, hypot, NaN, std
+from matplotlib.pyplot import plot
+from scipy.stats import scoreatpercentile
+from scipy.spatial.distance import cdist
 
 try:
     from shapely.geometry import Polygon, Point as shapelyPoint
@@ -199,7 +202,6 @@
         return Point(self.x/alpha, self.y/alpha)
 
     def plot(self, options = 'o', **kwargs):
-        from matplotlib.pylab import plot
         plot([self.x], [self.y], options, **kwargs)
 
     def norm2Squared(self):
@@ -230,7 +232,6 @@
             return shapelyPoint(self.x, self.y)
 
     def project(self, homography):
-        from numpy.core.multiarray import array
         projected = cvutils.projectArray(homography, array([[self.x], [self.y]]))
         return Point(projected[0], projected[1])
 
@@ -295,7 +296,6 @@
         The unknown of the equation is the time to reach the intersection
         between the relative trajectory of one road user
         and the circle of radius collisionThreshold around the other road user'''
-        from math import sqrt
         dv = v1-v2
         dp = p1-p2
         a = dv.norm2Squared()#(v1.x-v2.x)**2 + (v1.y-v2.y)**2
@@ -344,8 +344,6 @@
         mode=1: cumulative distance
         mode=2: cumulative distance with trailing distance
     '''
-
-    from numpy import zeros
     ss_spline_d = []
     #Prepare subsegment distances
     for spline in range(len(splines)):
@@ -480,7 +478,6 @@
     
     @staticmethod
     def fromPoint(p):
-        from math import atan2
         norm = p.norm2()
         if norm > 0:
             angle = atan2(p.y, p.x)
@@ -493,7 +490,6 @@
         return NormAngle(max(self.norm+other.norm, 0), self.angle+other.angle)
 
     def getPoint(self):
-        from math import cos, sin
         return Point(self.norm*cos(self.angle), self.norm*sin(self.angle))
 
 
@@ -527,7 +523,6 @@
         return FlowVector(self.position.multiply(alpha), self.velocity.multiply(alpha))
 
     def plot(self, options = '', **kwargs):
-        from matplotlib.pylab import plot
         plot([self.position.x, self.position.x+self.velocity.x], [self.position.y, self.position.y+self.velocity.y], options, **kwargs)
         self.position.plot(options+'x', **kwargs)
     
@@ -681,7 +676,6 @@
 
     @staticmethod
     def _plot(positions, options = '', withOrigin = False, lastCoordinate = None, timeStep = 1, **kwargs):
-        from matplotlib.pylab import plot
         if lastCoordinate is None:
             plot(positions[0][::timeStep], positions[1][::timeStep], options, **kwargs)
         elif 0 <= lastCoordinate <= len(positions[0]):
@@ -710,7 +704,6 @@
         return self.positions[1]
 
     def asArray(self):
-        from numpy.core.multiarray import array
         return array(self.positions)
     
     def xBounds(self):
@@ -757,7 +750,6 @@
 #        def add(x, y): return x+y
 #        sq = map(add, [x*x for x in self.positions[0]], [y*y for y in self.positions[1]])
 #        return sqrt(sq)
-        from numpy import hypot
         return hypot(self.positions[0], self.positions[1])
 
     # def cumulatedDisplacement(self):
@@ -1083,8 +1075,6 @@
 
     def plotCurvilinearPositions(self, lane = None, options = '', withOrigin = False, **kwargs):
         if hasattr(self, 'curvilinearPositions'):
-            from matplotlib.pylab import plot
-            from numpy import NaN
             if lane is None:
                 plot(list(self.getTimeInterval()), self.curvilinearPositions.positions[0], options, **kwargs)
                 if withOrigin:
@@ -1179,13 +1169,11 @@
         cvutils.displayTrajectories(videoFilename, [self], homography = homography, firstFrameNum = self.getFirstInstant(), lastFrameNumArg = self.getLastInstant(), undistort = undistort, intrinsicCameraMatrix = intrinsicCameraMatrix, distortionCoefficients = distortionCoefficients, undistortedImageMultiplication = undistortedImageMultiplication)
 
     def speedDiagnostics(self, framerate = 1., display = False):
-        from numpy import std
-        from scipy.stats import scoreatpercentile
         speeds = framerate*self.getSpeeds()
         coef = utils.linearRegression(range(len(speeds)), speeds)
         print('min/5th perc speed: {} / {}\nspeed diff: {}\nspeed stdev: {}\nregression: {}'.format(min(speeds), scoreatpercentile(speeds, 5), speeds[-2]-speeds[1], std(speeds), coef[0]))
         if display:
-            from matplotlib.pyplot import figure, plot, axis
+            from matplotlib.pyplot import figure, axis
             figure(1)
             self.plot()
             axis('equal')
@@ -1214,7 +1202,6 @@
         '''Returns the distances between all features of the 2 objects 
         at the same instant instant1
         or at instant1 and instant2'''
-        from scipy.spatial.distance import cdist
         if _instant2 is None:
             instant2 = instant1
         else:
@@ -1266,8 +1253,6 @@
         #for i in xrange(int(obj1.length())-1):
         #    for j in xrange(int(obj2.length())-1):
         #        inter = segmentIntersection(obj1.getPositionAt(i), obj1.getPositionAt(i+1), obj2.getPositionAt(i), obj2.getPositionAt(i+1))
-        from scipy.spatial.distance import cdist
-        from numpy import zeros
         positions1 = [p.astuple() for p in obj1.getPositions()]
         positions2 = [p.astuple() for p in obj2.getPositions()]
         pets = zeros((int(obj1.length()), int(obj2.length())))
@@ -1339,7 +1324,6 @@
         
         Warning work in progress
         TODO? not use the first/last 1-.. positions'''
-        from numpy import array, median
         nFeatures = len(self.features)
         if nFeatures == 0:
             print('Empty object features\nCannot compute smooth trajectory')
@@ -1409,7 +1393,6 @@
     def classifyUserTypeHoGSVMAtInstant(self, img, pedBikeCarSVM, instant, homography, width, height, bikeCarSVM = None, pedBikeSpeedTreshold = float('Inf'), bikeCarSpeedThreshold = float('Inf'), px = 0.2, py = 0.2, pixelThreshold = 800):
         '''Extract the image box around the object and 
         applies the SVM model on it'''
-        from numpy import array
         croppedImg, yCropMin, yCropMax, xCropMin, xCropMax = imageBox(img, self, instant, homography, width, height, px, py, pixelThreshold)
         if len(croppedImg) > 0: # != []
             hog = array([cvutils.HOG(croppedImg)], dtype = np.float32)
--- a/python/utils.py	Tue May 26 11:40:32 2015 +0200
+++ b/python/utils.py	Tue May 26 13:53:40 2015 +0200
@@ -5,6 +5,7 @@
 from datetime import time, datetime
 from math import sqrt, ceil, floor
 from scipy.stats import kruskal, shapiro
+from numpy import zeros, array, exp, sum as npsum, arange, cumsum
 
 datetimeFormat = "%Y-%m-%d %H:%M:%S"
 
@@ -60,7 +61,6 @@
 
 def cumulativeDensityFunction(sample, normalized = False):
     '''Returns the cumulative density function of the sample of a random variable'''
-    from numpy import arange, cumsum
     xaxis = sorted(sample)
     counts = arange(1,len(sample)+1) # dtype = float
     if normalized:
@@ -70,15 +70,13 @@
 class EmpiricalDiscreteDistribution(EmpiricalDistribution):
     '''Class to represent a sample of a distribution for a discrete random variable
     '''
-    from numpy.core.fromnumeric import sum
-
     def __init__(self, categories, counts):
         self.categories = categories
         self.counts = counts
 
     def mean(self):
         result = [float(x*y) for x,y in zip(self.categories, self.counts)]
-        return sum(result)/self.nSamples()
+        return npsum(result)/self.nSamples()
 
     def var(self, mean = None):
         if not mean:
@@ -87,12 +85,12 @@
             m = mean
         result = 0.
         squares = [float((x-m)*(x-m)*y) for x,y in zip(self.categories, self.counts)]
-        return sum(squares)/(self.nSamples()-1)
+        return npsum(squares)/(self.nSamples()-1)
 
     def referenceCounts(self, probability):
         '''probability is a function that returns the probability of the random variable for the category values'''
         refProba = [probability(c) for c in self.categories]
-        refProba[-1] = 1-sum(refProba[:-1])
+        refProba[-1] = 1-npsum(refProba[:-1])
         refCounts = [r*self.nSamples() for r in refProba]
         return refCounts, refProba
 
@@ -168,7 +166,6 @@
 def kernelSmoothing(x, X, Y, weightFunc, halfwidth):
     '''Returns the smoothed estimate of (X,Y) at x
     Sum_x weight(sample_x,x) * y(x)'''
-    from numpy import zeros, array
     weights = array([weightFunc(x,observedx, halfwidth) for observedx in X])
     if sum(weights)>0:
         return sum(weights*Y)/sum(weights)
@@ -182,7 +179,6 @@
         return 0.
 
 def gaussian(center, x, halfwidth):
-    from numpy import exp
     return exp(-((center-x)/halfwidth)**2/2)
 
 def epanechnikov(center, x, halfwidth):