diff python/moving.py @ 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 93633ce122c3
children 01b89182891a
line wrap: on
line diff
--- 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)